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