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