Remove InFlightSet hack. No longer needed.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Visibility.h"
32 #include <iostream>
33 #include <set>
34 using namespace llvm;
35
36 namespace {
37   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
38     
39   //===--------------------------------------------------------------------===//
40   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
41   /// instructions for SelectionDAG operations.
42   ///
43   class VISIBILITY_HIDDEN PPCDAGToDAGISel : public SelectionDAGISel {
44     PPCTargetMachine &TM;
45     PPCTargetLowering PPCLowering;
46     unsigned GlobalBaseReg;
47   public:
48     PPCDAGToDAGISel(PPCTargetMachine &tm)
49       : SelectionDAGISel(PPCLowering), TM(tm),
50         PPCLowering(*TM.getTargetLowering()) {}
51     
52     virtual bool runOnFunction(Function &Fn) {
53       // Make sure we re-emit a set of the global base reg if necessary
54       GlobalBaseReg = 0;
55       SelectionDAGISel::runOnFunction(Fn);
56       
57       InsertVRSaveCode(Fn);
58       return true;
59     }
60    
61     /// getI32Imm - Return a target constant with the specified value, of type
62     /// i32.
63     inline SDOperand getI32Imm(unsigned Imm) {
64       return CurDAG->getTargetConstant(Imm, MVT::i32);
65     }
66
67     /// getI64Imm - Return a target constant with the specified value, of type
68     /// i64.
69     inline SDOperand getI64Imm(uint64_t Imm) {
70       return CurDAG->getTargetConstant(Imm, MVT::i64);
71     }
72     
73     /// getSmallIPtrImm - Return a target constant of pointer type.
74     inline SDOperand getSmallIPtrImm(unsigned Imm) {
75       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
76     }
77     
78     
79     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
80     /// base register.  Return the virtual register that holds this value.
81     SDOperand getGlobalBaseReg();
82     
83     // Select - Convert the specified operand from a target-independent to a
84     // target-specific node if it hasn't already been changed.
85     void Select(SDOperand &Result, SDOperand Op);
86     
87     SDNode *SelectBitfieldInsert(SDNode *N);
88
89     /// SelectCC - Select a comparison of the specified values with the
90     /// specified condition code, returning the CR# of the expression.
91     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
92
93     /// SelectAddrImm - Returns true if the address N can be represented by
94     /// a base register plus a signed 16-bit displacement [r+imm].
95     bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
96       
97     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
98     /// represented as an indexed [r+r] operation.  Returns false if it can
99     /// be represented by [r+imm], which are preferred.
100     bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
101     
102     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
103     /// represented as an indexed [r+r] operation.
104     bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
105
106     /// SelectAddrImmShift - Returns true if the address N can be represented by
107     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
108     /// for use by STD and friends.
109     bool SelectAddrImmShift(SDOperand N, SDOperand &Disp, SDOperand &Base);
110     
111     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
112     /// inline asm expressions.
113     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
114                                               char ConstraintCode,
115                                               std::vector<SDOperand> &OutOps,
116                                               SelectionDAG &DAG) {
117       SDOperand Op0, Op1;
118       switch (ConstraintCode) {
119       default: return true;
120       case 'm':   // memory
121         if (!SelectAddrIdx(Op, Op0, Op1))
122           SelectAddrImm(Op, Op0, Op1);
123         break;
124       case 'o':   // offsetable
125         if (!SelectAddrImm(Op, Op0, Op1)) {
126           Select(Op0, Op);     // r+0.
127           Op1 = getSmallIPtrImm(0);
128         }
129         break;
130       case 'v':   // not offsetable
131         SelectAddrIdxOnly(Op, Op0, Op1);
132         break;
133       }
134       
135       OutOps.push_back(Op0);
136       OutOps.push_back(Op1);
137       return false;
138     }
139     
140     SDOperand BuildSDIVSequence(SDNode *N);
141     SDOperand BuildUDIVSequence(SDNode *N);
142     
143     /// InstructionSelectBasicBlock - This callback is invoked by
144     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
145     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
146     
147     void InsertVRSaveCode(Function &Fn);
148
149     virtual const char *getPassName() const {
150       return "PowerPC DAG->DAG Pattern Instruction Selection";
151     } 
152     
153     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
154     /// this target when scheduling the DAG.
155     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
156       // Should use subtarget info to pick the right hazard recognizer.  For
157       // now, always return a PPC970 recognizer.
158       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
159       assert(II && "No InstrInfo?");
160       return new PPCHazardRecognizer970(*II); 
161     }
162
163 // Include the pieces autogenerated from the target description.
164 #include "PPCGenDAGISel.inc"
165     
166 private:
167     SDOperand SelectSETCC(SDOperand Op);
168     void MySelect_PPCbctrl(SDOperand &Result, SDOperand N);
169     void MySelect_PPCcall(SDOperand &Result, SDOperand N);
170   };
171 }
172
173 /// InstructionSelectBasicBlock - This callback is invoked by
174 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
175 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
176   DEBUG(BB->dump());
177   
178   // The selection process is inherently a bottom-up recursive process (users
179   // select their uses before themselves).  Given infinite stack space, we
180   // could just start selecting on the root and traverse the whole graph.  In
181   // practice however, this causes us to run out of stack space on large basic
182   // blocks.  To avoid this problem, select the entry node, then all its uses,
183   // iteratively instead of recursively.
184   std::vector<SDOperand> Worklist;
185   Worklist.push_back(DAG.getEntryNode());
186   
187   // Note that we can do this in the PPC target (scanning forward across token
188   // chain edges) because no nodes ever get folded across these edges.  On a
189   // target like X86 which supports load/modify/store operations, this would
190   // have to be more careful.
191   while (!Worklist.empty()) {
192     SDOperand Node = Worklist.back();
193     Worklist.pop_back();
194
195     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
196          Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
197         CodeGenMap.count(Node)) continue;
198     
199     for (SDNode::use_iterator UI = Node.Val->use_begin(),
200          E = Node.Val->use_end(); UI != E; ++UI) {
201       // Scan the values.  If this use has a value that is a token chain, add it
202       // to the worklist.
203       SDNode *User = *UI;
204       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
205         if (User->getValueType(i) == MVT::Other) {
206           Worklist.push_back(SDOperand(User, i));
207           break; 
208         }
209     }
210
211     // Finally, legalize this node.
212     SDOperand Dummy;
213     Select(Dummy, Node);
214   }
215     
216   // Select target instructions for the DAG.
217   DAG.setRoot(SelectRoot(DAG.getRoot()));
218   CodeGenMap.clear();
219   HandleMap.clear();
220   ReplaceMap.clear();
221   DAG.RemoveDeadNodes();
222   
223   // Emit machine code to BB.
224   ScheduleAndEmitDAG(DAG);
225 }
226
227 /// InsertVRSaveCode - Once the entire function has been instruction selected,
228 /// all virtual registers are created and all machine instructions are built,
229 /// check to see if we need to save/restore VRSAVE.  If so, do it.
230 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
231   // Check to see if this function uses vector registers, which means we have to
232   // save and restore the VRSAVE register and update it with the regs we use.  
233   //
234   // In this case, there will be virtual registers of vector type type created
235   // by the scheduler.  Detect them now.
236   MachineFunction &Fn = MachineFunction::get(&F);
237   SSARegMap *RegMap = Fn.getSSARegMap();
238   bool HasVectorVReg = false;
239   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
240        e = RegMap->getLastVirtReg()+1; i != e; ++i)
241     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
242       HasVectorVReg = true;
243       break;
244     }
245   if (!HasVectorVReg) return;  // nothing to do.
246       
247   // If we have a vector register, we want to emit code into the entry and exit
248   // blocks to save and restore the VRSAVE register.  We do this here (instead
249   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
250   //
251   // 1. This (trivially) reduces the load on the register allocator, by not
252   //    having to represent the live range of the VRSAVE register.
253   // 2. This (more significantly) allows us to create a temporary virtual
254   //    register to hold the saved VRSAVE value, allowing this temporary to be
255   //    register allocated, instead of forcing it to be spilled to the stack.
256
257   // Create two vregs - one to hold the VRSAVE register that is live-in to the
258   // function and one for the value after having bits or'd into it.
259   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
260   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
261   
262   MachineBasicBlock &EntryBB = *Fn.begin();
263   // Emit the following code into the entry block:
264   // InVRSAVE = MFVRSAVE
265   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
266   // MTVRSAVE UpdatedVRSAVE
267   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
268   BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
269   BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
270   BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
271   
272   // Find all return blocks, outputting a restore in each epilog.
273   const TargetInstrInfo &TII = *TM.getInstrInfo();
274   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
275     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
276       IP = BB->end(); --IP;
277       
278       // Skip over all terminator instructions, which are part of the return
279       // sequence.
280       MachineBasicBlock::iterator I2 = IP;
281       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
282         IP = I2;
283       
284       // Emit: MTVRSAVE InVRSave
285       BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
286     }        
287   }
288 }
289
290
291 /// getGlobalBaseReg - Output the instructions required to put the
292 /// base address to use for accessing globals into a register.
293 ///
294 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
295   if (!GlobalBaseReg) {
296     // Insert the set of GlobalBaseReg into the first MBB of the function
297     MachineBasicBlock &FirstMBB = BB->getParent()->front();
298     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
299     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
300
301     if (PPCLowering.getPointerTy() == MVT::i32)
302       GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
303     else
304       GlobalBaseReg = RegMap->createVirtualRegister(PPC::G8RCRegisterClass);
305     
306     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
307     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
308   }
309   return CurDAG->getRegister(GlobalBaseReg, PPCLowering.getPointerTy());
310 }
311
312 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
313 /// or 64-bit immediate, and if the value can be accurately represented as a
314 /// sign extension from a 16-bit value.  If so, this returns true and the
315 /// immediate.
316 static bool isIntS16Immediate(SDNode *N, short &Imm) {
317   if (N->getOpcode() != ISD::Constant)
318     return false;
319
320   Imm = (short)cast<ConstantSDNode>(N)->getValue();
321   if (N->getValueType(0) == MVT::i32)
322     return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
323   else
324     return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
325 }
326
327 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
328   return isIntS16Immediate(Op.Val, Imm);
329 }
330
331
332 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
333 /// operand. If so Imm will receive the 32-bit value.
334 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
335   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
336     Imm = cast<ConstantSDNode>(N)->getValue();
337     return true;
338   }
339   return false;
340 }
341
342 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
343 /// operand.  If so Imm will receive the 64-bit value.
344 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
345   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
346     Imm = cast<ConstantSDNode>(N)->getValue();
347     return true;
348   }
349   return false;
350 }
351
352 // isInt32Immediate - This method tests to see if a constant operand.
353 // If so Imm will receive the 32 bit value.
354 static bool isInt32Immediate(SDOperand N, unsigned &Imm) {
355   return isInt32Immediate(N.Val, Imm);
356 }
357
358
359 // isOpcWithIntImmediate - This method tests to see if the node is a specific
360 // opcode and that it has a immediate integer right operand.
361 // If so Imm will receive the 32 bit value.
362 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
363   return N->getOpcode() == Opc && isInt32Immediate(N->getOperand(1).Val, Imm);
364 }
365
366
367 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
368 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
369 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
370 // not, since all 1s are not contiguous.
371 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
372   if (isShiftedMask_32(Val)) {
373     // look for the first non-zero bit
374     MB = CountLeadingZeros_32(Val);
375     // look for the first zero bit after the run of ones
376     ME = CountLeadingZeros_32((Val - 1) ^ Val);
377     return true;
378   } else {
379     Val = ~Val; // invert mask
380     if (isShiftedMask_32(Val)) {
381       // effectively look for the first zero bit
382       ME = CountLeadingZeros_32(Val) - 1;
383       // effectively look for the first one bit after the run of zeros
384       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
385       return true;
386     }
387   }
388   // no run present
389   return false;
390 }
391
392 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
393 // and mask opcode and mask operation.
394 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
395                             unsigned &SH, unsigned &MB, unsigned &ME) {
396   // Don't even go down this path for i64, since different logic will be
397   // necessary for rldicl/rldicr/rldimi.
398   if (N->getValueType(0) != MVT::i32)
399     return false;
400
401   unsigned Shift  = 32;
402   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
403   unsigned Opcode = N->getOpcode();
404   if (N->getNumOperands() != 2 ||
405       !isInt32Immediate(N->getOperand(1).Val, Shift) || (Shift > 31))
406     return false;
407   
408   if (Opcode == ISD::SHL) {
409     // apply shift left to mask if it comes first
410     if (IsShiftMask) Mask = Mask << Shift;
411     // determine which bits are made indeterminant by shift
412     Indeterminant = ~(0xFFFFFFFFu << Shift);
413   } else if (Opcode == ISD::SRL) { 
414     // apply shift right to mask if it comes first
415     if (IsShiftMask) Mask = Mask >> Shift;
416     // determine which bits are made indeterminant by shift
417     Indeterminant = ~(0xFFFFFFFFu >> Shift);
418     // adjust for the left rotate
419     Shift = 32 - Shift;
420   } else {
421     return false;
422   }
423   
424   // if the mask doesn't intersect any Indeterminant bits
425   if (Mask && !(Mask & Indeterminant)) {
426     SH = Shift & 31;
427     // make sure the mask is still a mask (wrap arounds may not be)
428     return isRunOfOnes(Mask, MB, ME);
429   }
430   return false;
431 }
432
433 /// SelectBitfieldInsert - turn an or of two masked values into
434 /// the rotate left word immediate then mask insert (rlwimi) instruction.
435 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
436   SDOperand Op0 = N->getOperand(0);
437   SDOperand Op1 = N->getOperand(1);
438   
439   uint64_t LKZ, LKO, RKZ, RKO;
440   TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
441   TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
442   
443   unsigned TargetMask = LKZ;
444   unsigned InsertMask = RKZ;
445   
446   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
447     unsigned Op0Opc = Op0.getOpcode();
448     unsigned Op1Opc = Op1.getOpcode();
449     unsigned Value, SH = 0;
450     TargetMask = ~TargetMask;
451     InsertMask = ~InsertMask;
452
453     // If the LHS has a foldable shift and the RHS does not, then swap it to the
454     // RHS so that we can fold the shift into the insert.
455     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
456       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
457           Op0.getOperand(0).getOpcode() == ISD::SRL) {
458         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
459             Op1.getOperand(0).getOpcode() != ISD::SRL) {
460           std::swap(Op0, Op1);
461           std::swap(Op0Opc, Op1Opc);
462           std::swap(TargetMask, InsertMask);
463         }
464       }
465     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
466       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
467           Op1.getOperand(0).getOpcode() != ISD::SRL) {
468         std::swap(Op0, Op1);
469         std::swap(Op0Opc, Op1Opc);
470         std::swap(TargetMask, InsertMask);
471       }
472     }
473     
474     unsigned MB, ME;
475     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
476       SDOperand Tmp1, Tmp2, Tmp3;
477       bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
478
479       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
480           isInt32Immediate(Op1.getOperand(1), Value)) {
481         Op1 = Op1.getOperand(0);
482         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
483       }
484       if (Op1Opc == ISD::AND) {
485         unsigned SHOpc = Op1.getOperand(0).getOpcode();
486         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
487             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
488           Op1 = Op1.getOperand(0).getOperand(0);
489           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
490         } else {
491           Op1 = Op1.getOperand(0);
492         }
493       }
494       
495       Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
496       Select(Tmp1, Tmp3);
497       Select(Tmp2, Op1);
498       SH &= 31;
499       return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
500                                    getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
501     }
502   }
503   return 0;
504 }
505
506 /// SelectAddrImm - Returns true if the address N can be represented by
507 /// a base register plus a signed 16-bit displacement [r+imm].
508 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp, 
509                                     SDOperand &Base) {
510   // If this can be more profitably realized as r+r, fail.
511   if (SelectAddrIdx(N, Disp, Base))
512     return false;
513
514   if (N.getOpcode() == ISD::ADD) {
515     short imm = 0;
516     if (isIntS16Immediate(N.getOperand(1), imm)) {
517       Disp = getI32Imm((int)imm & 0xFFFF);
518       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
519         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
520       } else {
521         Base = N.getOperand(0);
522       }
523       return true; // [r+i]
524     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
525       // Match LOAD (ADD (X, Lo(G))).
526       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
527              && "Cannot handle constant offsets yet!");
528       Disp = N.getOperand(1).getOperand(0);  // The global address.
529       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
530              Disp.getOpcode() == ISD::TargetConstantPool ||
531              Disp.getOpcode() == ISD::TargetJumpTable);
532       Base = N.getOperand(0);
533       return true;  // [&g+r]
534     }
535   } else if (N.getOpcode() == ISD::OR) {
536     short imm = 0;
537     if (isIntS16Immediate(N.getOperand(1), imm)) {
538       // If this is an or of disjoint bitfields, we can codegen this as an add
539       // (for better address arithmetic) if the LHS and RHS of the OR are
540       // provably disjoint.
541       uint64_t LHSKnownZero, LHSKnownOne;
542       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
543                                     LHSKnownZero, LHSKnownOne);
544       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
545         // If all of the bits are known zero on the LHS or RHS, the add won't
546         // carry.
547         Base = N.getOperand(0);
548         Disp = getI32Imm((int)imm & 0xFFFF);
549         return true;
550       }
551     }
552   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
553     // Loading from a constant address.
554
555     // If this address fits entirely in a 16-bit sext immediate field, codegen
556     // this as "d, 0"
557     short Imm;
558     if (isIntS16Immediate(CN, Imm)) {
559       Disp = CurDAG->getTargetConstant(Imm, CN->getValueType(0));
560       Base = CurDAG->getRegister(PPC::R0, CN->getValueType(0));
561       return true;
562     }
563
564     // FIXME: Handle small sext constant offsets in PPC64 mode also!
565     if (CN->getValueType(0) == MVT::i32) {
566       int Addr = (int)CN->getValue();
567     
568       // Otherwise, break this down into an LIS + disp.
569       Disp = getI32Imm((short)Addr);
570       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
571       return true;
572     }
573   }
574   
575   Disp = getSmallIPtrImm(0);
576   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
577     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
578   else
579     Base = N;
580   return true;      // [r+0]
581 }
582
583 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
584 /// represented as an indexed [r+r] operation.  Returns false if it can
585 /// be represented by [r+imm], which are preferred.
586 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base, 
587                                     SDOperand &Index) {
588   short imm = 0;
589   if (N.getOpcode() == ISD::ADD) {
590     if (isIntS16Immediate(N.getOperand(1), imm))
591       return false;    // r+i
592     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
593       return false;    // r+i
594     
595     Base = N.getOperand(0);
596     Index = N.getOperand(1);
597     return true;
598   } else if (N.getOpcode() == ISD::OR) {
599     if (isIntS16Immediate(N.getOperand(1), imm))
600       return false;    // r+i can fold it if we can.
601     
602     // If this is an or of disjoint bitfields, we can codegen this as an add
603     // (for better address arithmetic) if the LHS and RHS of the OR are provably
604     // disjoint.
605     uint64_t LHSKnownZero, LHSKnownOne;
606     uint64_t RHSKnownZero, RHSKnownOne;
607     PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
608                                   LHSKnownZero, LHSKnownOne);
609     
610     if (LHSKnownZero) {
611       PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
612                                     RHSKnownZero, RHSKnownOne);
613       // If all of the bits are known zero on the LHS or RHS, the add won't
614       // carry.
615       if ((LHSKnownZero | RHSKnownZero) == ~0U) {
616         Base = N.getOperand(0);
617         Index = N.getOperand(1);
618         return true;
619       }
620     }
621   }
622   
623   return false;
624 }
625
626 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
627 /// represented as an indexed [r+r] operation.
628 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base, 
629                                         SDOperand &Index) {
630   // Check to see if we can easily represent this as an [r+r] address.  This
631   // will fail if it thinks that the address is more profitably represented as
632   // reg+imm, e.g. where imm = 0.
633   if (SelectAddrIdx(N, Base, Index))
634     return true;
635   
636   // If the operand is an addition, always emit this as [r+r], since this is
637   // better (for code size, and execution, as the memop does the add for free)
638   // than emitting an explicit add.
639   if (N.getOpcode() == ISD::ADD) {
640     Base = N.getOperand(0);
641     Index = N.getOperand(1);
642     return true;
643   }
644   
645   // Otherwise, do it the hard way, using R0 as the base register.
646   Base = CurDAG->getRegister(PPC::R0, N.getValueType());
647   Index = N;
648   return true;
649 }
650
651 /// SelectAddrImmShift - Returns true if the address N can be represented by
652 /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
653 /// for use by STD and friends.
654 bool PPCDAGToDAGISel::SelectAddrImmShift(SDOperand N, SDOperand &Disp, 
655                                          SDOperand &Base) {
656   // If this can be more profitably realized as r+r, fail.
657   if (SelectAddrIdx(N, Disp, Base))
658     return false;
659   
660   if (N.getOpcode() == ISD::ADD) {
661     short imm = 0;
662     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
663       Disp = getI32Imm(((int)imm & 0xFFFF) >> 2);
664       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
665         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
666       } else {
667         Base = N.getOperand(0);
668       }
669       return true; // [r+i]
670     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
671       // Match LOAD (ADD (X, Lo(G))).
672       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
673              && "Cannot handle constant offsets yet!");
674       Disp = N.getOperand(1).getOperand(0);  // The global address.
675       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
676              Disp.getOpcode() == ISD::TargetConstantPool ||
677              Disp.getOpcode() == ISD::TargetJumpTable);
678       Base = N.getOperand(0);
679       return true;  // [&g+r]
680     }
681   } else if (N.getOpcode() == ISD::OR) {
682     short imm = 0;
683     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
684       // If this is an or of disjoint bitfields, we can codegen this as an add
685       // (for better address arithmetic) if the LHS and RHS of the OR are
686       // provably disjoint.
687       uint64_t LHSKnownZero, LHSKnownOne;
688       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
689                                     LHSKnownZero, LHSKnownOne);
690       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
691         // If all of the bits are known zero on the LHS or RHS, the add won't
692         // carry.
693         Base = N.getOperand(0);
694         Disp = getI32Imm(((int)imm & 0xFFFF) >> 2);
695         return true;
696       }
697     }
698   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
699     // Loading from a constant address.
700     
701     // If this address fits entirely in a 14-bit sext immediate field, codegen
702     // this as "d, 0"
703     short Imm;
704     if (isIntS16Immediate(CN, Imm)) {
705       Disp = getSmallIPtrImm((unsigned short)Imm >> 2);
706       Base = CurDAG->getRegister(PPC::R0, CN->getValueType(0));
707       return true;
708     }
709     
710     // FIXME: Handle small sext constant offsets in PPC64 mode also!
711     if (CN->getValueType(0) == MVT::i32) {
712       int Addr = (int)CN->getValue();
713       
714       // Otherwise, break this down into an LIS + disp.
715       Disp = getI32Imm((short)Addr >> 2);
716       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
717       return true;
718     }
719   }
720   
721   Disp = getSmallIPtrImm(0);
722   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
723     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
724   else
725     Base = N;
726   return true;      // [r+0]
727 }
728
729
730 /// SelectCC - Select a comparison of the specified values with the specified
731 /// condition code, returning the CR# of the expression.
732 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
733                                     ISD::CondCode CC) {
734   // Always select the LHS.
735   Select(LHS, LHS);
736   unsigned Opc;
737   
738   if (LHS.getValueType() == MVT::i32) {
739     unsigned Imm;
740     if (ISD::isUnsignedIntSetCC(CC)) {
741       if (isInt32Immediate(RHS, Imm) && isUInt16(Imm))
742         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
743                                                getI32Imm(Imm & 0xFFFF)), 0);
744       Opc = PPC::CMPLW;
745     } else {
746       short SImm;
747       if (isIntS16Immediate(RHS, SImm))
748         return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
749                                                getI32Imm((int)SImm & 0xFFFF)),
750                          0);
751       Opc = PPC::CMPW;
752     }
753   } else if (LHS.getValueType() == MVT::i64) {
754     uint64_t Imm;
755     if (ISD::isUnsignedIntSetCC(CC)) {
756       if (isInt64Immediate(RHS.Val, Imm) && isUInt16(Imm))
757         return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
758                                                getI64Imm(Imm & 0xFFFF)), 0);
759       Opc = PPC::CMPLD;
760     } else {
761       short SImm;
762       if (isIntS16Immediate(RHS, SImm))
763         return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
764                                                getI64Imm((int)SImm & 0xFFFF)),
765                          0);
766       Opc = PPC::CMPD;
767     }
768   } else if (LHS.getValueType() == MVT::f32) {
769     Opc = PPC::FCMPUS;
770   } else {
771     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
772     Opc = PPC::FCMPUD;
773   }
774   Select(RHS, RHS);
775   return SDOperand(CurDAG->getTargetNode(Opc, MVT::i32, LHS, RHS), 0);
776 }
777
778 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
779 /// to Condition.
780 static unsigned getBCCForSetCC(ISD::CondCode CC) {
781   switch (CC) {
782   default: assert(0 && "Unknown condition!"); abort();
783   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
784   case ISD::SETUEQ:
785   case ISD::SETEQ:  return PPC::BEQ;
786   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
787   case ISD::SETUNE:
788   case ISD::SETNE:  return PPC::BNE;
789   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
790   case ISD::SETULT:
791   case ISD::SETLT:  return PPC::BLT;
792   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
793   case ISD::SETULE:
794   case ISD::SETLE:  return PPC::BLE;
795   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
796   case ISD::SETUGT:
797   case ISD::SETGT:  return PPC::BGT;
798   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
799   case ISD::SETUGE:
800   case ISD::SETGE:  return PPC::BGE;
801     
802   case ISD::SETO:   return PPC::BUN;
803   case ISD::SETUO:  return PPC::BNU;
804   }
805   return 0;
806 }
807
808 /// getCRIdxForSetCC - Return the index of the condition register field
809 /// associated with the SetCC condition, and whether or not the field is
810 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
811 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
812   switch (CC) {
813   default: assert(0 && "Unknown condition!"); abort();
814   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
815   case ISD::SETULT:
816   case ISD::SETLT:  Inv = false;  return 0;
817   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
818   case ISD::SETUGE:
819   case ISD::SETGE:  Inv = true;   return 0;
820   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
821   case ISD::SETUGT:
822   case ISD::SETGT:  Inv = false;  return 1;
823   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
824   case ISD::SETULE:
825   case ISD::SETLE:  Inv = true;   return 1;
826   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
827   case ISD::SETUEQ:
828   case ISD::SETEQ:  Inv = false;  return 2;
829   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
830   case ISD::SETUNE:
831   case ISD::SETNE:  Inv = true;   return 2;
832   case ISD::SETO:   Inv = true;   return 3;
833   case ISD::SETUO:  Inv = false;  return 3;
834   }
835   return 0;
836 }
837
838 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
839   SDNode *N = Op.Val;
840   unsigned Imm;
841   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
842   if (isInt32Immediate(N->getOperand(1), Imm)) {
843     // We can codegen setcc op, imm very efficiently compared to a brcond.
844     // Check for those cases here.
845     // setcc op, 0
846     if (Imm == 0) {
847       SDOperand Op;
848       Select(Op, N->getOperand(0));
849       switch (CC) {
850       default: break;
851       case ISD::SETEQ:
852         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
853         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
854                                     getI32Imm(5), getI32Imm(31));
855       case ISD::SETNE: {
856         SDOperand AD =
857           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
858                                           Op, getI32Imm(~0U)), 0);
859         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
860                                     AD.getValue(1));
861       }
862       case ISD::SETLT:
863         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
864                                     getI32Imm(31), getI32Imm(31));
865       case ISD::SETGT: {
866         SDOperand T =
867           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
868         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
869         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
870                                     getI32Imm(31), getI32Imm(31));
871       }
872       }
873     } else if (Imm == ~0U) {        // setcc op, -1
874       SDOperand Op;
875       Select(Op, N->getOperand(0));
876       switch (CC) {
877       default: break;
878       case ISD::SETEQ:
879         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
880                                              Op, getI32Imm(1)), 0);
881         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
882                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
883                                                               getI32Imm(0)), 0),
884                                     Op.getValue(1));
885       case ISD::SETNE: {
886         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
887         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
888                                            Op, getI32Imm(~0U));
889         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
890                                     Op, SDOperand(AD, 1));
891       }
892       case ISD::SETLT: {
893         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
894                                                        getI32Imm(1)), 0);
895         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
896                                                        Op), 0);
897         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
898                                     getI32Imm(31), getI32Imm(31));
899       }
900       case ISD::SETGT:
901         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
902                                              getI32Imm(1), getI32Imm(31),
903                                              getI32Imm(31)), 0);
904         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
905       }
906     }
907   }
908   
909   bool Inv;
910   unsigned Idx = getCRIdxForSetCC(CC, Inv);
911   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
912   SDOperand IntCR;
913   
914   // Force the ccreg into CR7.
915   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
916   
917   SDOperand InFlag(0, 0);  // Null incoming flag value.
918   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
919                                InFlag).getValue(1);
920   
921   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
922     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
923                                             CCReg), 0);
924   else
925     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
926   
927   if (!Inv) {
928     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
929                                 getI32Imm((32-(3-Idx)) & 31),
930                                 getI32Imm(31), getI32Imm(31));
931   } else {
932     SDOperand Tmp =
933       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
934                                       getI32Imm((32-(3-Idx)) & 31),
935                                       getI32Imm(31),getI32Imm(31)), 0);
936     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
937   }
938 }
939
940
941 // Select - Convert the specified operand from a target-independent to a
942 // target-specific node if it hasn't already been changed.
943 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
944   SDNode *N = Op.Val;
945   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
946       N->getOpcode() < PPCISD::FIRST_NUMBER) {
947     Result = Op;
948     return;   // Already selected.
949   }
950
951   // If this has already been converted, use it.
952   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
953   if (CGMI != CodeGenMap.end()) {
954     Result = CGMI->second;
955     return;
956   }
957   
958   switch (N->getOpcode()) {
959   default: break;
960   case ISD::SETCC:
961     Result = SelectSETCC(Op);
962     return;
963   case PPCISD::GlobalBaseReg:
964     Result = getGlobalBaseReg();
965     return;
966     
967   case ISD::FrameIndex: {
968     int FI = cast<FrameIndexSDNode>(N)->getIndex();
969     SDOperand TFI = CurDAG->getTargetFrameIndex(FI, Op.getValueType());
970     unsigned Opc = Op.getValueType() == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
971     if (N->hasOneUse()) {
972       Result = CurDAG->SelectNodeTo(N, Opc, Op.getValueType(), TFI,
973                                     getSmallIPtrImm(0));
974       return;
975     }
976     Result = CodeGenMap[Op] = 
977       SDOperand(CurDAG->getTargetNode(Opc, Op.getValueType(), TFI,
978                                       getSmallIPtrImm(0)), 0);
979     return;
980   }
981
982   case PPCISD::MFCR: {
983     SDOperand InFlag;
984     Select(InFlag, N->getOperand(1));
985     // Use MFOCRF if supported.
986     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
987       Result = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
988                                                N->getOperand(0), InFlag), 0);
989     else
990       Result = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag), 0);
991     CodeGenMap[Op] = Result;
992     return;
993   }
994     
995   case ISD::SDIV: {
996     // FIXME: since this depends on the setting of the carry flag from the srawi
997     //        we should really be making notes about that for the scheduler.
998     // FIXME: It sure would be nice if we could cheaply recognize the 
999     //        srl/add/sra pattern the dag combiner will generate for this as
1000     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1001     unsigned Imm;
1002     if (isInt32Immediate(N->getOperand(1), Imm)) {
1003       SDOperand N0;
1004       Select(N0, N->getOperand(0));
1005       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1006         SDNode *Op =
1007           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
1008                                 N0, getI32Imm(Log2_32(Imm)));
1009         Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
1010                                       SDOperand(Op, 0), SDOperand(Op, 1));
1011       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1012         SDNode *Op =
1013           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
1014                                 N0, getI32Imm(Log2_32(-Imm)));
1015         SDOperand PT =
1016           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
1017                                           SDOperand(Op, 0), SDOperand(Op, 1)),
1018                     0);
1019         Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1020       }
1021       return;
1022     }
1023     
1024     // Other cases are autogenerated.
1025     break;
1026   }
1027   case ISD::AND: {
1028     unsigned Imm, Imm2;
1029     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1030     // with a mask, emit rlwinm
1031     if (isInt32Immediate(N->getOperand(1), Imm) &&
1032         (isShiftedMask_32(Imm) || isShiftedMask_32(~Imm))) {
1033       SDOperand Val;
1034       unsigned SH, MB, ME;
1035       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
1036         Select(Val, N->getOperand(0).getOperand(0));
1037       } else if (Imm == 0) {
1038         // AND X, 0 -> 0, not "rlwinm 32".
1039         Select(Result, N->getOperand(1));
1040         return ;
1041       } else {        
1042         Select(Val, N->getOperand(0));
1043         isRunOfOnes(Imm, MB, ME);
1044         SH = 0;
1045       }
1046       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
1047                                     getI32Imm(SH), getI32Imm(MB),
1048                                     getI32Imm(ME));
1049       return;
1050     }
1051     // ISD::OR doesn't get all the bitfield insertion fun.
1052     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1053     if (isInt32Immediate(N->getOperand(1), Imm) && 
1054         N->getOperand(0).getOpcode() == ISD::OR &&
1055         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1056       unsigned MB, ME;
1057       Imm = ~(Imm^Imm2);
1058       if (isRunOfOnes(Imm, MB, ME)) {
1059         SDOperand Tmp1, Tmp2;
1060         Select(Tmp1, N->getOperand(0).getOperand(0));
1061         Select(Tmp2, N->getOperand(0).getOperand(1));
1062         Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1063                                                  Tmp1, Tmp2,
1064                                                  getI32Imm(0), getI32Imm(MB),
1065                                                  getI32Imm(ME)), 0);
1066         return;
1067       }
1068     }
1069     
1070     // Other cases are autogenerated.
1071     break;
1072   }
1073   case ISD::OR:
1074     if (N->getValueType(0) == MVT::i32)
1075       if (SDNode *I = SelectBitfieldInsert(N)) {
1076         Result = CodeGenMap[Op] = SDOperand(I, 0);
1077         return;
1078       }
1079       
1080     // Other cases are autogenerated.
1081     break;
1082   case ISD::SHL: {
1083     unsigned Imm, SH, MB, ME;
1084     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1085         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1086       SDOperand Val;
1087       Select(Val, N->getOperand(0).getOperand(0));
1088       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1089                                     Val, getI32Imm(SH), getI32Imm(MB),
1090                                     getI32Imm(ME));
1091       return;
1092     }
1093     
1094     // Other cases are autogenerated.
1095     break;
1096   }
1097   case ISD::SRL: {
1098     unsigned Imm, SH, MB, ME;
1099     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1100         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
1101       SDOperand Val;
1102       Select(Val, N->getOperand(0).getOperand(0));
1103       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1104                                     Val, getI32Imm(SH), getI32Imm(MB),
1105                                     getI32Imm(ME));
1106       return;
1107     }
1108     
1109     // Other cases are autogenerated.
1110     break;
1111   }
1112   case ISD::SELECT_CC: {
1113     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1114     
1115     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1116     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1117       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1118         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1119           if (N1C->isNullValue() && N3C->isNullValue() &&
1120               N2C->getValue() == 1ULL && CC == ISD::SETNE &&
1121               // FIXME: Implement this optzn for PPC64.
1122               N->getValueType(0) == MVT::i32) {
1123             SDOperand LHS;
1124             Select(LHS, N->getOperand(0));
1125             SDNode *Tmp =
1126               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1127                                     LHS, getI32Imm(~0U));
1128             Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1129                                           SDOperand(Tmp, 0), LHS,
1130                                           SDOperand(Tmp, 1));
1131             return;
1132           }
1133
1134     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1135     unsigned BROpc = getBCCForSetCC(CC);
1136
1137     bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1138     unsigned SelectCCOp;
1139     if (N->getValueType(0) == MVT::i32)
1140       SelectCCOp = PPC::SELECT_CC_I4;
1141     else if (N->getValueType(0) == MVT::i64)
1142       SelectCCOp = PPC::SELECT_CC_I8;
1143     else if (N->getValueType(0) == MVT::f32)
1144       SelectCCOp = PPC::SELECT_CC_F4;
1145     else if (N->getValueType(0) == MVT::f64)
1146       SelectCCOp = PPC::SELECT_CC_F8;
1147     else
1148       SelectCCOp = PPC::SELECT_CC_VRRC;
1149
1150     SDOperand N2, N3;
1151     Select(N2, N->getOperand(2));
1152     Select(N3, N->getOperand(3));
1153     Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1154                                   N2, N3, getI32Imm(BROpc));
1155     return;
1156   }
1157   case ISD::BR_CC: {
1158     SDOperand Chain;
1159     Select(Chain, N->getOperand(0));
1160     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1161     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1162     Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, 
1163                                   CondCode, getI32Imm(getBCCForSetCC(CC)), 
1164                                   N->getOperand(4), Chain);
1165     return;
1166   }
1167   case ISD::BRIND: {
1168     // FIXME: Should custom lower this.
1169     SDOperand Chain, Target;
1170     Select(Chain, N->getOperand(0));
1171     Select(Target,N->getOperand(1));
1172     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1173     Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, Target,
1174                                             Chain), 0);
1175     Result = CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
1176     return;
1177   }
1178   // FIXME: These are manually selected because tblgen isn't handling varargs
1179   // nodes correctly.
1180   case PPCISD::BCTRL:            MySelect_PPCbctrl(Result, Op); return;
1181   case PPCISD::CALL:             MySelect_PPCcall(Result, Op); return;
1182   }
1183   
1184   SelectCode(Result, Op);
1185 }
1186
1187
1188 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1189 // correctly.
1190 void PPCDAGToDAGISel::MySelect_PPCbctrl(SDOperand &Result, SDOperand N) {
1191   SDOperand Chain(0, 0);
1192   SDOperand InFlag(0, 0);
1193   SDNode *ResNode;
1194   
1195   bool hasFlag =
1196     N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1197
1198   std::vector<SDOperand> Ops;
1199   // Push varargs arguments, including optional flag.
1200   for (unsigned i = 1, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1201     Select(Chain, N.getOperand(i));
1202     Ops.push_back(Chain);
1203   }
1204
1205   Select(Chain, N.getOperand(0));
1206   Ops.push_back(Chain);
1207
1208   if (hasFlag) {
1209     Select(Chain, N.getOperand(N.getNumOperands()-1));
1210     Ops.push_back(Chain);
1211   }
1212   
1213   ResNode = CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag, Ops);
1214   Chain = SDOperand(ResNode, 0);
1215   InFlag = SDOperand(ResNode, 1);
1216   SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val,
1217                                    Chain.ResNo);
1218   SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val,
1219                                    InFlag.ResNo);
1220   Result = SDOperand(ResNode, N.ResNo);
1221   return;
1222 }
1223
1224 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1225 // correctly.
1226 void PPCDAGToDAGISel::MySelect_PPCcall(SDOperand &Result, SDOperand N) {
1227   SDOperand Chain(0, 0);
1228   SDOperand InFlag(0, 0);
1229   SDOperand N1(0, 0);
1230   SDOperand Tmp0(0, 0);
1231   SDNode *ResNode;
1232   Chain = N.getOperand(0);
1233   N1 = N.getOperand(1);
1234   
1235   // Pattern: (PPCcall:void (imm:i32):$func)
1236   // Emits: (BLA:void (imm:i32):$func)
1237   // Pattern complexity = 4  cost = 1
1238   if (N1.getOpcode() == ISD::Constant) {
1239     unsigned Tmp0C = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1240     
1241     std::vector<SDOperand> Ops;
1242     Ops.push_back(CurDAG->getTargetConstant(Tmp0C, MVT::i32));
1243
1244     bool hasFlag =
1245       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1246     
1247     // Push varargs arguments, not including optional flag.
1248     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1249       Select(Chain, N.getOperand(i));
1250       Ops.push_back(Chain);
1251     }
1252     Select(Chain, N.getOperand(0));
1253     Ops.push_back(Chain);
1254     if (hasFlag) {
1255       Select(Chain, N.getOperand(N.getNumOperands()-1));
1256       Ops.push_back(Chain);
1257     }
1258     ResNode = CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag, Ops);
1259     
1260     Chain = SDOperand(ResNode, 0);
1261     InFlag = SDOperand(ResNode, 1);
1262     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val, 
1263                                      Chain.ResNo);
1264     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, 
1265                                      InFlag.ResNo);
1266     Result = SDOperand(ResNode, N.ResNo);
1267     return;
1268   }
1269   
1270   // Pattern: (PPCcall:void (tglobaladdr:i32):$dst)
1271   // Emits: (BL:void (tglobaladdr:i32):$dst)
1272   // Pattern complexity = 4  cost = 1
1273   if (N1.getOpcode() == ISD::TargetGlobalAddress) {
1274     std::vector<SDOperand> Ops;
1275     Ops.push_back(N1);
1276     
1277     bool hasFlag =
1278       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1279
1280     // Push varargs arguments, not including optional flag.
1281     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1282       Select(Chain, N.getOperand(i));
1283       Ops.push_back(Chain);
1284     }
1285     Select(Chain, N.getOperand(0));
1286     Ops.push_back(Chain);
1287     if (hasFlag) {
1288       Select(Chain, N.getOperand(N.getNumOperands()-1));
1289       Ops.push_back(Chain);
1290     }
1291     
1292     ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, Ops);
1293     
1294     Chain = SDOperand(ResNode, 0);
1295     InFlag = SDOperand(ResNode, 1);
1296     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val,
1297                                      Chain.ResNo);
1298     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, 
1299                                      InFlag.ResNo);
1300     Result = SDOperand(ResNode, N.ResNo);
1301     return;
1302   }
1303   
1304   // Pattern: (PPCcall:void (texternalsym:i32):$dst)
1305   // Emits: (BL:void (texternalsym:i32):$dst)
1306   // Pattern complexity = 4  cost = 1
1307   if (N1.getOpcode() == ISD::TargetExternalSymbol) {
1308     std::vector<SDOperand> Ops;
1309     Ops.push_back(N1);
1310     
1311     bool hasFlag =
1312       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1313
1314     // Push varargs arguments, not including optional flag.
1315     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1316       Select(Chain, N.getOperand(i));
1317       Ops.push_back(Chain);
1318     }
1319     Select(Chain, N.getOperand(0));
1320     Ops.push_back(Chain);
1321     if (hasFlag) {
1322       Select(Chain, N.getOperand(N.getNumOperands()-1));
1323       Ops.push_back(Chain);
1324     }
1325     
1326     ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, Ops);
1327
1328     Chain = SDOperand(ResNode, 0);
1329     InFlag = SDOperand(ResNode, 1);
1330     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val,
1331                                      Chain.ResNo);
1332     SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val,
1333                                      InFlag.ResNo);
1334     Result = SDOperand(ResNode, N.ResNo);
1335     return;
1336   }
1337   std::cerr << "Cannot yet select: ";
1338   N.Val->dump(CurDAG);
1339   std::cerr << '\n';
1340   abort();
1341 }
1342
1343
1344 /// createPPCISelDag - This pass converts a legalized DAG into a 
1345 /// PowerPC-specific DAG, ready for instruction scheduling.
1346 ///
1347 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1348   return new PPCDAGToDAGISel(TM);
1349 }
1350