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