eliminate static ctors for Statistic objects.
[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 #define DEBUG_TYPE "ppc-codegen"
16 #include "PPC.h"
17 #include "PPCPredicates.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCISelLowering.h"
20 #include "PPCHazardRecognizers.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Constants.h"
28 #include "llvm/GlobalValue.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Compiler.h"
33 #include <queue>
34 #include <set>
35 using namespace llvm;
36
37 namespace {
38   //===--------------------------------------------------------------------===//
39   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
40   /// instructions for SelectionDAG operations.
41   ///
42   class VISIBILITY_HIDDEN 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     /// getI64Imm - Return a target constant with the specified value, of type
67     /// i64.
68     inline SDOperand getI64Imm(uint64_t Imm) {
69       return CurDAG->getTargetConstant(Imm, MVT::i64);
70     }
71     
72     /// getSmallIPtrImm - Return a target constant of pointer type.
73     inline SDOperand getSmallIPtrImm(unsigned Imm) {
74       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
75     }
76     
77     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s 
78     /// with any number of 0s on either side.  The 1s are allowed to wrap from
79     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
80     /// 0x0F0F0000 is not, since all 1s are not contiguous.
81     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
82
83
84     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
85     /// rotate and mask opcode and mask operation.
86     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
87                                 unsigned &SH, unsigned &MB, unsigned &ME);
88     
89     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
90     /// base register.  Return the virtual register that holds this value.
91     SDNode *getGlobalBaseReg();
92     
93     // Select - Convert the specified operand from a target-independent to a
94     // target-specific node if it hasn't already been changed.
95     SDNode *Select(SDOperand Op);
96     
97     SDNode *SelectBitfieldInsert(SDNode *N);
98
99     /// SelectCC - Select a comparison of the specified values with the
100     /// specified condition code, returning the CR# of the expression.
101     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
102
103     /// SelectAddrImm - Returns true if the address N can be represented by
104     /// a base register plus a signed 16-bit displacement [r+imm].
105     bool SelectAddrImm(SDOperand Op, SDOperand N, SDOperand &Disp,
106                        SDOperand &Base) {
107       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG);
108     }
109     
110     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
111     /// immediate field.  Because preinc imms have already been validated, just
112     /// accept it.
113     bool SelectAddrImmOffs(SDOperand Op, SDOperand N, SDOperand &Out) const {
114       Out = N;
115       return true;
116     }
117       
118     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
119     /// represented as an indexed [r+r] operation.  Returns false if it can
120     /// be represented by [r+imm], which are preferred.
121     bool SelectAddrIdx(SDOperand Op, SDOperand N, SDOperand &Base,
122                        SDOperand &Index) {
123       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
124     }
125     
126     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
127     /// represented as an indexed [r+r] operation.
128     bool SelectAddrIdxOnly(SDOperand Op, SDOperand N, SDOperand &Base,
129                            SDOperand &Index) {
130       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
131     }
132
133     /// SelectAddrImmShift - Returns true if the address N can be represented by
134     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
135     /// for use by STD and friends.
136     bool SelectAddrImmShift(SDOperand Op, SDOperand N, SDOperand &Disp,
137                             SDOperand &Base) {
138       return PPCLowering.SelectAddressRegImmShift(N, Disp, Base, *CurDAG);
139     }
140       
141     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
142     /// inline asm expressions.
143     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
144                                               char ConstraintCode,
145                                               std::vector<SDOperand> &OutOps,
146                                               SelectionDAG &DAG) {
147       SDOperand Op0, Op1;
148       switch (ConstraintCode) {
149       default: return true;
150       case 'm':   // memory
151         if (!SelectAddrIdx(Op, Op, Op0, Op1))
152           SelectAddrImm(Op, Op, Op0, Op1);
153         break;
154       case 'o':   // offsetable
155         if (!SelectAddrImm(Op, Op, Op0, Op1)) {
156           Op0 = Op;
157           AddToISelQueue(Op0);     // r+0.
158           Op1 = getSmallIPtrImm(0);
159         }
160         break;
161       case 'v':   // not offsetable
162         SelectAddrIdxOnly(Op, Op, Op0, Op1);
163         break;
164       }
165       
166       OutOps.push_back(Op0);
167       OutOps.push_back(Op1);
168       return false;
169     }
170     
171     SDOperand BuildSDIVSequence(SDNode *N);
172     SDOperand BuildUDIVSequence(SDNode *N);
173     
174     /// InstructionSelectBasicBlock - This callback is invoked by
175     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
176     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
177     
178     void InsertVRSaveCode(Function &Fn);
179
180     virtual const char *getPassName() const {
181       return "PowerPC DAG->DAG Pattern Instruction Selection";
182     } 
183     
184     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
185     /// this target when scheduling the DAG.
186     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
187       // Should use subtarget info to pick the right hazard recognizer.  For
188       // now, always return a PPC970 recognizer.
189       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
190       assert(II && "No InstrInfo?");
191       return new PPCHazardRecognizer970(*II); 
192     }
193
194 // Include the pieces autogenerated from the target description.
195 #include "PPCGenDAGISel.inc"
196     
197 private:
198     SDNode *SelectSETCC(SDOperand Op);
199   };
200 }
201
202 /// InstructionSelectBasicBlock - This callback is invoked by
203 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
204 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
205   DEBUG(BB->dump());
206
207   // Select target instructions for the DAG.
208   DAG.setRoot(SelectRoot(DAG.getRoot()));
209   DAG.RemoveDeadNodes();
210   
211   // Emit machine code to BB.
212   ScheduleAndEmitDAG(DAG);
213 }
214
215 /// InsertVRSaveCode - Once the entire function has been instruction selected,
216 /// all virtual registers are created and all machine instructions are built,
217 /// check to see if we need to save/restore VRSAVE.  If so, do it.
218 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
219   // Check to see if this function uses vector registers, which means we have to
220   // save and restore the VRSAVE register and update it with the regs we use.  
221   //
222   // In this case, there will be virtual registers of vector type type created
223   // by the scheduler.  Detect them now.
224   MachineFunction &Fn = MachineFunction::get(&F);
225   SSARegMap *RegMap = Fn.getSSARegMap();
226   bool HasVectorVReg = false;
227   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
228        e = RegMap->getLastVirtReg()+1; i != e; ++i)
229     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
230       HasVectorVReg = true;
231       break;
232     }
233   if (!HasVectorVReg) return;  // nothing to do.
234       
235   // If we have a vector register, we want to emit code into the entry and exit
236   // blocks to save and restore the VRSAVE register.  We do this here (instead
237   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
238   //
239   // 1. This (trivially) reduces the load on the register allocator, by not
240   //    having to represent the live range of the VRSAVE register.
241   // 2. This (more significantly) allows us to create a temporary virtual
242   //    register to hold the saved VRSAVE value, allowing this temporary to be
243   //    register allocated, instead of forcing it to be spilled to the stack.
244
245   // Create two vregs - one to hold the VRSAVE register that is live-in to the
246   // function and one for the value after having bits or'd into it.
247   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
248   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
249   
250   const TargetInstrInfo &TII = *TM.getInstrInfo();
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, TII.get(PPC::MFVRSAVE), InVRSAVE);
258   BuildMI(EntryBB, IP, TII.get(PPC::UPDATE_VRSAVE), UpdatedVRSAVE).addReg(InVRSAVE);
259   BuildMI(EntryBB, IP, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
260   
261   // Find all return blocks, outputting a restore in each epilog.
262   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
263     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
264       IP = BB->end(); --IP;
265       
266       // Skip over all terminator instructions, which are part of the return
267       // sequence.
268       MachineBasicBlock::iterator I2 = IP;
269       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
270         IP = I2;
271       
272       // Emit: MTVRSAVE InVRSave
273       BuildMI(*BB, IP, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
274     }        
275   }
276 }
277
278
279 /// getGlobalBaseReg - Output the instructions required to put the
280 /// base address to use for accessing globals into a register.
281 ///
282 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
283   if (!GlobalBaseReg) {
284     const TargetInstrInfo &TII = *TM.getInstrInfo();
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
290     if (PPCLowering.getPointerTy() == MVT::i32) {
291       GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
292       BuildMI(FirstMBB, MBBI, TII.get(PPC::MovePCtoLR), PPC::LR);
293       BuildMI(FirstMBB, MBBI, TII.get(PPC::MFLR), GlobalBaseReg);
294     } else {
295       GlobalBaseReg = RegMap->createVirtualRegister(PPC::G8RCRegisterClass);
296       BuildMI(FirstMBB, MBBI, TII.get(PPC::MovePCtoLR8), PPC::LR8);
297       BuildMI(FirstMBB, MBBI, TII.get(PPC::MFLR8), GlobalBaseReg);
298     }
299   }
300   return CurDAG->getRegister(GlobalBaseReg, PPCLowering.getPointerTy()).Val;
301 }
302
303 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
304 /// or 64-bit immediate, and if the value can be accurately represented as a
305 /// sign extension from a 16-bit value.  If so, this returns true and the
306 /// immediate.
307 static bool isIntS16Immediate(SDNode *N, short &Imm) {
308   if (N->getOpcode() != ISD::Constant)
309     return false;
310
311   Imm = (short)cast<ConstantSDNode>(N)->getValue();
312   if (N->getValueType(0) == MVT::i32)
313     return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
314   else
315     return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
316 }
317
318 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
319   return isIntS16Immediate(Op.Val, Imm);
320 }
321
322
323 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
324 /// operand. If so Imm will receive the 32-bit value.
325 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
326   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
327     Imm = cast<ConstantSDNode>(N)->getValue();
328     return true;
329   }
330   return false;
331 }
332
333 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
334 /// operand.  If so Imm will receive the 64-bit value.
335 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
336   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
337     Imm = cast<ConstantSDNode>(N)->getValue();
338     return true;
339   }
340   return false;
341 }
342
343 // isInt32Immediate - This method tests to see if a constant operand.
344 // If so Imm will receive the 32 bit value.
345 static bool isInt32Immediate(SDOperand N, unsigned &Imm) {
346   return isInt32Immediate(N.Val, Imm);
347 }
348
349
350 // isOpcWithIntImmediate - This method tests to see if the node is a specific
351 // opcode and that it has a immediate integer right operand.
352 // If so Imm will receive the 32 bit value.
353 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
354   return N->getOpcode() == Opc && isInt32Immediate(N->getOperand(1).Val, Imm);
355 }
356
357 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
358   if (isShiftedMask_32(Val)) {
359     // look for the first non-zero bit
360     MB = CountLeadingZeros_32(Val);
361     // look for the first zero bit after the run of ones
362     ME = CountLeadingZeros_32((Val - 1) ^ Val);
363     return true;
364   } else {
365     Val = ~Val; // invert mask
366     if (isShiftedMask_32(Val)) {
367       // effectively look for the first zero bit
368       ME = CountLeadingZeros_32(Val) - 1;
369       // effectively look for the first one bit after the run of zeros
370       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
371       return true;
372     }
373   }
374   // no run present
375   return false;
376 }
377
378 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask, 
379                                       bool IsShiftMask, unsigned &SH, 
380                                       unsigned &MB, unsigned &ME) {
381   // Don't even go down this path for i64, since different logic will be
382   // necessary for rldicl/rldicr/rldimi.
383   if (N->getValueType(0) != MVT::i32)
384     return false;
385
386   unsigned Shift  = 32;
387   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
388   unsigned Opcode = N->getOpcode();
389   if (N->getNumOperands() != 2 ||
390       !isInt32Immediate(N->getOperand(1).Val, Shift) || (Shift > 31))
391     return false;
392   
393   if (Opcode == ISD::SHL) {
394     // apply shift left to mask if it comes first
395     if (IsShiftMask) Mask = Mask << Shift;
396     // determine which bits are made indeterminant by shift
397     Indeterminant = ~(0xFFFFFFFFu << Shift);
398   } else if (Opcode == ISD::SRL) { 
399     // apply shift right to mask if it comes first
400     if (IsShiftMask) Mask = Mask >> Shift;
401     // determine which bits are made indeterminant by shift
402     Indeterminant = ~(0xFFFFFFFFu >> Shift);
403     // adjust for the left rotate
404     Shift = 32 - Shift;
405   } else if (Opcode == ISD::ROTL) {
406     Indeterminant = 0;
407   } else {
408     return false;
409   }
410   
411   // if the mask doesn't intersect any Indeterminant bits
412   if (Mask && !(Mask & Indeterminant)) {
413     SH = Shift & 31;
414     // make sure the mask is still a mask (wrap arounds may not be)
415     return isRunOfOnes(Mask, MB, ME);
416   }
417   return false;
418 }
419
420 /// SelectBitfieldInsert - turn an or of two masked values into
421 /// the rotate left word immediate then mask insert (rlwimi) instruction.
422 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
423   SDOperand Op0 = N->getOperand(0);
424   SDOperand Op1 = N->getOperand(1);
425   
426   uint64_t LKZ, LKO, RKZ, RKO;
427   TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
428   TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
429   
430   unsigned TargetMask = LKZ;
431   unsigned InsertMask = RKZ;
432   
433   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
434     unsigned Op0Opc = Op0.getOpcode();
435     unsigned Op1Opc = Op1.getOpcode();
436     unsigned Value, SH = 0;
437     TargetMask = ~TargetMask;
438     InsertMask = ~InsertMask;
439
440     // If the LHS has a foldable shift and the RHS does not, then swap it to the
441     // RHS so that we can fold the shift into the insert.
442     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
443       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
444           Op0.getOperand(0).getOpcode() == ISD::SRL) {
445         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
446             Op1.getOperand(0).getOpcode() != ISD::SRL) {
447           std::swap(Op0, Op1);
448           std::swap(Op0Opc, Op1Opc);
449           std::swap(TargetMask, InsertMask);
450         }
451       }
452     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
453       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
454           Op1.getOperand(0).getOpcode() != ISD::SRL) {
455         std::swap(Op0, Op1);
456         std::swap(Op0Opc, Op1Opc);
457         std::swap(TargetMask, InsertMask);
458       }
459     }
460     
461     unsigned MB, ME;
462     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
463       SDOperand Tmp1, Tmp2, Tmp3;
464       bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
465
466       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
467           isInt32Immediate(Op1.getOperand(1), Value)) {
468         Op1 = Op1.getOperand(0);
469         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
470       }
471       if (Op1Opc == ISD::AND) {
472         unsigned SHOpc = Op1.getOperand(0).getOpcode();
473         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
474             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
475           Op1 = Op1.getOperand(0).getOperand(0);
476           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
477         } else {
478           Op1 = Op1.getOperand(0);
479         }
480       }
481       
482       Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
483       AddToISelQueue(Tmp3);
484       AddToISelQueue(Op1);
485       SH &= 31;
486       SDOperand Ops[] = { Tmp3, Op1, getI32Imm(SH), getI32Imm(MB),
487                           getI32Imm(ME) };
488       return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Ops, 5);
489     }
490   }
491   return 0;
492 }
493
494 /// SelectCC - Select a comparison of the specified values with the specified
495 /// condition code, returning the CR# of the expression.
496 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
497                                     ISD::CondCode CC) {
498   // Always select the LHS.
499   AddToISelQueue(LHS);
500   unsigned Opc;
501   
502   if (LHS.getValueType() == MVT::i32) {
503     unsigned Imm;
504     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
505       if (isInt32Immediate(RHS, Imm)) {
506         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
507         if (isUInt16(Imm))
508           return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
509                                                  getI32Imm(Imm & 0xFFFF)), 0);
510         // If this is a 16-bit signed immediate, fold it.
511         if (isInt16(Imm))
512           return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
513                                                  getI32Imm(Imm & 0xFFFF)), 0);
514         
515         // For non-equality comparisons, the default code would materialize the
516         // constant, then compare against it, like this:
517         //   lis r2, 4660
518         //   ori r2, r2, 22136 
519         //   cmpw cr0, r3, r2
520         // Since we are just comparing for equality, we can emit this instead:
521         //   xoris r0,r3,0x1234
522         //   cmplwi cr0,r0,0x5678
523         //   beq cr0,L6
524         SDOperand Xor(CurDAG->getTargetNode(PPC::XORIS, MVT::i32, LHS,
525                                             getI32Imm(Imm >> 16)), 0);
526         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, Xor,
527                                                getI32Imm(Imm & 0xFFFF)), 0);
528       }
529       Opc = PPC::CMPLW;
530     } else if (ISD::isUnsignedIntSetCC(CC)) {
531       if (isInt32Immediate(RHS, Imm) && isUInt16(Imm))
532         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
533                                                getI32Imm(Imm & 0xFFFF)), 0);
534       Opc = PPC::CMPLW;
535     } else {
536       short SImm;
537       if (isIntS16Immediate(RHS, SImm))
538         return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
539                                                getI32Imm((int)SImm & 0xFFFF)),
540                          0);
541       Opc = PPC::CMPW;
542     }
543   } else if (LHS.getValueType() == MVT::i64) {
544     uint64_t Imm;
545     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
546       if (isInt64Immediate(RHS.Val, Imm)) {
547         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
548         if (isUInt16(Imm))
549           return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
550                                                  getI32Imm(Imm & 0xFFFF)), 0);
551         // If this is a 16-bit signed immediate, fold it.
552         if (isInt16(Imm))
553           return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
554                                                  getI32Imm(Imm & 0xFFFF)), 0);
555         
556         // For non-equality comparisons, the default code would materialize the
557         // constant, then compare against it, like this:
558         //   lis r2, 4660
559         //   ori r2, r2, 22136 
560         //   cmpd cr0, r3, r2
561         // Since we are just comparing for equality, we can emit this instead:
562         //   xoris r0,r3,0x1234
563         //   cmpldi cr0,r0,0x5678
564         //   beq cr0,L6
565         if (isUInt32(Imm)) {
566           SDOperand Xor(CurDAG->getTargetNode(PPC::XORIS8, MVT::i64, LHS,
567                                               getI64Imm(Imm >> 16)), 0);
568           return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, Xor,
569                                                  getI64Imm(Imm & 0xFFFF)), 0);
570         }
571       }
572       Opc = PPC::CMPLD;
573     } else if (ISD::isUnsignedIntSetCC(CC)) {
574       if (isInt64Immediate(RHS.Val, Imm) && isUInt16(Imm))
575         return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
576                                                getI64Imm(Imm & 0xFFFF)), 0);
577       Opc = PPC::CMPLD;
578     } else {
579       short SImm;
580       if (isIntS16Immediate(RHS, SImm))
581         return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
582                                                getI64Imm(SImm & 0xFFFF)),
583                          0);
584       Opc = PPC::CMPD;
585     }
586   } else if (LHS.getValueType() == MVT::f32) {
587     Opc = PPC::FCMPUS;
588   } else {
589     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
590     Opc = PPC::FCMPUD;
591   }
592   AddToISelQueue(RHS);
593   return SDOperand(CurDAG->getTargetNode(Opc, MVT::i32, LHS, RHS), 0);
594 }
595
596 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
597   switch (CC) {
598   default: assert(0 && "Unknown condition!"); abort();
599   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
600   case ISD::SETUEQ:
601   case ISD::SETEQ:  return PPC::PRED_EQ;
602   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
603   case ISD::SETUNE:
604   case ISD::SETNE:  return PPC::PRED_NE;
605   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
606   case ISD::SETULT:
607   case ISD::SETLT:  return PPC::PRED_LT;
608   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
609   case ISD::SETULE:
610   case ISD::SETLE:  return PPC::PRED_LE;
611   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
612   case ISD::SETUGT:
613   case ISD::SETGT:  return PPC::PRED_GT;
614   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
615   case ISD::SETUGE:
616   case ISD::SETGE:  return PPC::PRED_GE;
617     
618   case ISD::SETO:   return PPC::PRED_NU;
619   case ISD::SETUO:  return PPC::PRED_UN;
620   }
621 }
622
623 /// getCRIdxForSetCC - Return the index of the condition register field
624 /// associated with the SetCC condition, and whether or not the field is
625 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
626 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
627   switch (CC) {
628   default: assert(0 && "Unknown condition!"); abort();
629   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
630   case ISD::SETULT:
631   case ISD::SETLT:  Inv = false;  return 0;
632   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
633   case ISD::SETUGE:
634   case ISD::SETGE:  Inv = true;   return 0;
635   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
636   case ISD::SETUGT:
637   case ISD::SETGT:  Inv = false;  return 1;
638   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
639   case ISD::SETULE:
640   case ISD::SETLE:  Inv = true;   return 1;
641   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
642   case ISD::SETUEQ:
643   case ISD::SETEQ:  Inv = false;  return 2;
644   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
645   case ISD::SETUNE:
646   case ISD::SETNE:  Inv = true;   return 2;
647   case ISD::SETO:   Inv = true;   return 3;
648   case ISD::SETUO:  Inv = false;  return 3;
649   }
650   return 0;
651 }
652
653 SDNode *PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
654   SDNode *N = Op.Val;
655   unsigned Imm;
656   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
657   if (isInt32Immediate(N->getOperand(1), Imm)) {
658     // We can codegen setcc op, imm very efficiently compared to a brcond.
659     // Check for those cases here.
660     // setcc op, 0
661     if (Imm == 0) {
662       SDOperand Op = N->getOperand(0);
663       AddToISelQueue(Op);
664       switch (CC) {
665       default: break;
666       case ISD::SETEQ: {
667         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
668         SDOperand Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
669         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
670       }
671       case ISD::SETNE: {
672         SDOperand AD =
673           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
674                                           Op, getI32Imm(~0U)), 0);
675         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
676                                     AD.getValue(1));
677       }
678       case ISD::SETLT: {
679         SDOperand Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
680         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
681       }
682       case ISD::SETGT: {
683         SDOperand T =
684           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
685         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
686         SDOperand Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
687         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
688       }
689       }
690     } else if (Imm == ~0U) {        // setcc op, -1
691       SDOperand Op = N->getOperand(0);
692       AddToISelQueue(Op);
693       switch (CC) {
694       default: break;
695       case ISD::SETEQ:
696         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
697                                              Op, getI32Imm(1)), 0);
698         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
699                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
700                                                               getI32Imm(0)), 0),
701                                     Op.getValue(1));
702       case ISD::SETNE: {
703         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
704         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
705                                            Op, getI32Imm(~0U));
706         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
707                                     Op, SDOperand(AD, 1));
708       }
709       case ISD::SETLT: {
710         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
711                                                        getI32Imm(1)), 0);
712         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
713                                                        Op), 0);
714         SDOperand Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
715         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
716       }
717       case ISD::SETGT: {
718         SDOperand Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
719         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Ops, 4), 0);
720         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, 
721                                     getI32Imm(1));
722       }
723       }
724     }
725   }
726   
727   bool Inv;
728   unsigned Idx = getCRIdxForSetCC(CC, Inv);
729   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
730   SDOperand IntCR;
731   
732   // Force the ccreg into CR7.
733   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
734   
735   SDOperand InFlag(0, 0);  // Null incoming flag value.
736   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
737                                InFlag).getValue(1);
738   
739   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
740     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
741                                             CCReg), 0);
742   else
743     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
744   
745   SDOperand Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
746                       getI32Imm(31), getI32Imm(31) };
747   if (!Inv) {
748     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
749   } else {
750     SDOperand Tmp =
751       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Ops, 4), 0);
752     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
753   }
754 }
755
756
757 // Select - Convert the specified operand from a target-independent to a
758 // target-specific node if it hasn't already been changed.
759 SDNode *PPCDAGToDAGISel::Select(SDOperand Op) {
760   SDNode *N = Op.Val;
761   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
762       N->getOpcode() < PPCISD::FIRST_NUMBER)
763     return NULL;   // Already selected.
764
765   switch (N->getOpcode()) {
766   default: break;
767   
768   case ISD::Constant: {
769     if (N->getValueType(0) == MVT::i64) {
770       // Get 64 bit value.
771       int64_t Imm = cast<ConstantSDNode>(N)->getValue();
772       // Assume no remaining bits.
773       unsigned Remainder = 0;
774       // Assume no shift required.
775       unsigned Shift = 0;
776       
777       // If it can't be represented as a 32 bit value.
778       if (!isInt32(Imm)) {
779         Shift = CountTrailingZeros_64(Imm);
780         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
781         
782         // If the shifted value fits 32 bits.
783         if (isInt32(ImmSh)) {
784           // Go with the shifted value.
785           Imm = ImmSh;
786         } else {
787           // Still stuck with a 64 bit value.
788           Remainder = Imm;
789           Shift = 32;
790           Imm >>= 32;
791         }
792       }
793       
794       // Intermediate operand.
795       SDNode *Result;
796
797       // Handle first 32 bits.
798       unsigned Lo = Imm & 0xFFFF;
799       unsigned Hi = (Imm >> 16) & 0xFFFF;
800       
801       // Simple value.
802       if (isInt16(Imm)) {
803        // Just the Lo bits.
804         Result = CurDAG->getTargetNode(PPC::LI8, MVT::i64, getI32Imm(Lo));
805       } else if (Lo) {
806         // Handle the Hi bits.
807         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
808         Result = CurDAG->getTargetNode(OpC, MVT::i64, getI32Imm(Hi));
809         // And Lo bits.
810         Result = CurDAG->getTargetNode(PPC::ORI8, MVT::i64,
811                                        SDOperand(Result, 0), getI32Imm(Lo));
812       } else {
813        // Just the Hi bits.
814         Result = CurDAG->getTargetNode(PPC::LIS8, MVT::i64, getI32Imm(Hi));
815       }
816       
817       // If no shift, we're done.
818       if (!Shift) return Result;
819
820       // Shift for next step if the upper 32-bits were not zero.
821       if (Imm) {
822         Result = CurDAG->getTargetNode(PPC::RLDICR, MVT::i64,
823                                        SDOperand(Result, 0),
824                                        getI32Imm(Shift), getI32Imm(63 - Shift));
825       }
826
827       // Add in the last bits as required.
828       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
829         Result = CurDAG->getTargetNode(PPC::ORIS8, MVT::i64,
830                                        SDOperand(Result, 0), getI32Imm(Hi));
831       } 
832       if ((Lo = Remainder & 0xFFFF)) {
833         Result = CurDAG->getTargetNode(PPC::ORI8, MVT::i64,
834                                        SDOperand(Result, 0), getI32Imm(Lo));
835       }
836       
837       return Result;
838     }
839     break;
840   }
841   
842   case ISD::SETCC:
843     return SelectSETCC(Op);
844   case PPCISD::GlobalBaseReg:
845     return getGlobalBaseReg();
846     
847   case ISD::FrameIndex: {
848     int FI = cast<FrameIndexSDNode>(N)->getIndex();
849     SDOperand TFI = CurDAG->getTargetFrameIndex(FI, Op.getValueType());
850     unsigned Opc = Op.getValueType() == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
851     if (N->hasOneUse())
852       return CurDAG->SelectNodeTo(N, Opc, Op.getValueType(), TFI,
853                                   getSmallIPtrImm(0));
854     return CurDAG->getTargetNode(Opc, Op.getValueType(), TFI,
855                                  getSmallIPtrImm(0));
856   }
857
858   case PPCISD::MFCR: {
859     SDOperand InFlag = N->getOperand(1);
860     AddToISelQueue(InFlag);
861     // Use MFOCRF if supported.
862     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
863       return CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
864                                    N->getOperand(0), InFlag);
865     else
866       return CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag);
867   }
868     
869   case ISD::SDIV: {
870     // FIXME: since this depends on the setting of the carry flag from the srawi
871     //        we should really be making notes about that for the scheduler.
872     // FIXME: It sure would be nice if we could cheaply recognize the 
873     //        srl/add/sra pattern the dag combiner will generate for this as
874     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
875     unsigned Imm;
876     if (isInt32Immediate(N->getOperand(1), Imm)) {
877       SDOperand N0 = N->getOperand(0);
878       AddToISelQueue(N0);
879       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
880         SDNode *Op =
881           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
882                                 N0, getI32Imm(Log2_32(Imm)));
883         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
884                                     SDOperand(Op, 0), SDOperand(Op, 1));
885       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
886         SDNode *Op =
887           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
888                                 N0, getI32Imm(Log2_32(-Imm)));
889         SDOperand PT =
890           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
891                                           SDOperand(Op, 0), SDOperand(Op, 1)),
892                     0);
893         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
894       }
895     }
896     
897     // Other cases are autogenerated.
898     break;
899   }
900     
901   case ISD::LOAD: {
902     // Handle preincrement loads.
903     LoadSDNode *LD = cast<LoadSDNode>(Op);
904     MVT::ValueType LoadedVT = LD->getLoadedVT();
905     
906     // Normal loads are handled by code generated from the .td file.
907     if (LD->getAddressingMode() != ISD::PRE_INC)
908       break;
909     
910     SDOperand Offset = LD->getOffset();
911     if (isa<ConstantSDNode>(Offset) ||
912         Offset.getOpcode() == ISD::TargetGlobalAddress) {
913       
914       unsigned Opcode;
915       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
916       if (LD->getValueType(0) != MVT::i64) {
917         // Handle PPC32 integer and normal FP loads.
918         assert(!isSExt || LoadedVT == MVT::i16 && "Invalid sext update load");
919         switch (LoadedVT) {
920           default: assert(0 && "Invalid PPC load type!");
921           case MVT::f64: Opcode = PPC::LFDU; break;
922           case MVT::f32: Opcode = PPC::LFSU; break;
923           case MVT::i32: Opcode = PPC::LWZU; break;
924           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
925           case MVT::i1:
926           case MVT::i8:  Opcode = PPC::LBZU; break;
927         }
928       } else {
929         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
930         assert(!isSExt || LoadedVT == MVT::i16 && "Invalid sext update load");
931         switch (LoadedVT) {
932           default: assert(0 && "Invalid PPC load type!");
933           case MVT::i64: Opcode = PPC::LDU; break;
934           case MVT::i32: Opcode = PPC::LWZU8; break;
935           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
936           case MVT::i1:
937           case MVT::i8:  Opcode = PPC::LBZU8; break;
938         }
939       }
940       
941       SDOperand Chain = LD->getChain();
942       SDOperand Base = LD->getBasePtr();
943       AddToISelQueue(Chain);
944       AddToISelQueue(Base);
945       AddToISelQueue(Offset);
946       SDOperand Ops[] = { Offset, Base, Chain };
947       // FIXME: PPC64
948       return CurDAG->getTargetNode(Opcode, MVT::i32, MVT::i32,
949                                    MVT::Other, Ops, 3);
950     } else {
951       assert(0 && "R+R preindex loads not supported yet!");
952     }
953   }
954     
955   case ISD::AND: {
956     unsigned Imm, Imm2, SH, MB, ME;
957
958     // If this is an and of a value rotated between 0 and 31 bits and then and'd
959     // with a mask, emit rlwinm
960     if (isInt32Immediate(N->getOperand(1), Imm) &&
961         isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
962       SDOperand Val = N->getOperand(0).getOperand(0);
963       AddToISelQueue(Val);
964       SDOperand Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
965       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
966     }
967     // If this is just a masked value where the input is not handled above, and
968     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
969     if (isInt32Immediate(N->getOperand(1), Imm) &&
970         isRunOfOnes(Imm, MB, ME) && 
971         N->getOperand(0).getOpcode() != ISD::ROTL) {
972       SDOperand Val = N->getOperand(0);
973       AddToISelQueue(Val);
974       SDOperand Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
975       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
976     }
977     // AND X, 0 -> 0, not "rlwinm 32".
978     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
979       AddToISelQueue(N->getOperand(1));
980       ReplaceUses(SDOperand(N, 0), N->getOperand(1));
981       return NULL;
982     }
983     // ISD::OR doesn't get all the bitfield insertion fun.
984     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
985     if (isInt32Immediate(N->getOperand(1), Imm) && 
986         N->getOperand(0).getOpcode() == ISD::OR &&
987         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
988       unsigned MB, ME;
989       Imm = ~(Imm^Imm2);
990       if (isRunOfOnes(Imm, MB, ME)) {
991         AddToISelQueue(N->getOperand(0).getOperand(0));
992         AddToISelQueue(N->getOperand(0).getOperand(1));
993         SDOperand Ops[] = { N->getOperand(0).getOperand(0),
994                             N->getOperand(0).getOperand(1),
995                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
996         return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Ops, 5);
997       }
998     }
999     
1000     // Other cases are autogenerated.
1001     break;
1002   }
1003   case ISD::OR:
1004     if (N->getValueType(0) == MVT::i32)
1005       if (SDNode *I = SelectBitfieldInsert(N))
1006         return I;
1007       
1008     // Other cases are autogenerated.
1009     break;
1010   case ISD::SHL: {
1011     unsigned Imm, SH, MB, ME;
1012     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1013         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1014       AddToISelQueue(N->getOperand(0).getOperand(0));
1015       SDOperand Ops[] = { N->getOperand(0).getOperand(0),
1016                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1017       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1018     }
1019     
1020     // Other cases are autogenerated.
1021     break;
1022   }
1023   case ISD::SRL: {
1024     unsigned Imm, SH, MB, ME;
1025     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1026         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
1027       AddToISelQueue(N->getOperand(0).getOperand(0));
1028       SDOperand Ops[] = { N->getOperand(0).getOperand(0),
1029                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1030       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1031     }
1032     
1033     // Other cases are autogenerated.
1034     break;
1035   }
1036   case ISD::SELECT_CC: {
1037     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1038     
1039     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1040     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1041       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1042         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1043           if (N1C->isNullValue() && N3C->isNullValue() &&
1044               N2C->getValue() == 1ULL && CC == ISD::SETNE &&
1045               // FIXME: Implement this optzn for PPC64.
1046               N->getValueType(0) == MVT::i32) {
1047             AddToISelQueue(N->getOperand(0));
1048             SDNode *Tmp =
1049               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1050                                     N->getOperand(0), getI32Imm(~0U));
1051             return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1052                                         SDOperand(Tmp, 0), N->getOperand(0),
1053                                         SDOperand(Tmp, 1));
1054           }
1055
1056     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1057     unsigned BROpc = getPredicateForSetCC(CC);
1058
1059     unsigned SelectCCOp;
1060     if (N->getValueType(0) == MVT::i32)
1061       SelectCCOp = PPC::SELECT_CC_I4;
1062     else if (N->getValueType(0) == MVT::i64)
1063       SelectCCOp = PPC::SELECT_CC_I8;
1064     else if (N->getValueType(0) == MVT::f32)
1065       SelectCCOp = PPC::SELECT_CC_F4;
1066     else if (N->getValueType(0) == MVT::f64)
1067       SelectCCOp = PPC::SELECT_CC_F8;
1068     else
1069       SelectCCOp = PPC::SELECT_CC_VRRC;
1070
1071     AddToISelQueue(N->getOperand(2));
1072     AddToISelQueue(N->getOperand(3));
1073     SDOperand Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1074                         getI32Imm(BROpc) };
1075     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1076   }
1077   case PPCISD::COND_BRANCH: {
1078     AddToISelQueue(N->getOperand(0));  // Op #0 is the Chain.
1079     // Op #1 is the PPC::PRED_* number.
1080     // Op #2 is the CR#
1081     // Op #3 is the Dest MBB
1082     AddToISelQueue(N->getOperand(4));  // Op #4 is the Flag.
1083     SDOperand Ops[] = { N->getOperand(1), N->getOperand(2), N->getOperand(3),
1084       N->getOperand(0), N->getOperand(4) };
1085     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1086   }
1087   case ISD::BR_CC: {
1088     AddToISelQueue(N->getOperand(0));
1089     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1090     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1091     SDOperand Ops[] = { getI32Imm(getPredicateForSetCC(CC)), CondCode, 
1092                         N->getOperand(4), N->getOperand(0) };
1093     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1094   }
1095   case ISD::BRIND: {
1096     // FIXME: Should custom lower this.
1097     SDOperand Chain = N->getOperand(0);
1098     SDOperand Target = N->getOperand(1);
1099     AddToISelQueue(Chain);
1100     AddToISelQueue(Target);
1101     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1102     Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, Target,
1103                                             Chain), 0);
1104     return CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
1105   }
1106   }
1107   
1108   return SelectCode(Op);
1109 }
1110
1111
1112
1113 /// createPPCISelDag - This pass converts a legalized DAG into a 
1114 /// PowerPC-specific DAG, ready for instruction scheduling.
1115 ///
1116 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1117   return new PPCDAGToDAGISel(TM);
1118 }
1119