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