24aca56460cd6e07690cbdd3f36974e80f60cf25
[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 #include "PPC.h"
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCTargetMachine.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalAlias.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/Support/CommandLine.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 #define DEBUG_TYPE "ppc-codegen"
38
39 // FIXME: Remove this once the bug has been fixed!
40 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
41 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
42
43 namespace llvm {
44   void initializePPCDAGToDAGISelPass(PassRegistry&);
45 }
46
47 namespace {
48   //===--------------------------------------------------------------------===//
49   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
50   /// instructions for SelectionDAG operations.
51   ///
52   class PPCDAGToDAGISel : public SelectionDAGISel {
53     const PPCTargetMachine &TM;
54     const PPCTargetLowering &PPCLowering;
55     const PPCSubtarget &PPCSubTarget;
56     unsigned GlobalBaseReg;
57   public:
58     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
59       : SelectionDAGISel(tm), TM(tm),
60         PPCLowering(*TM.getTargetLowering()),
61         PPCSubTarget(*TM.getSubtargetImpl()) {
62       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
63     }
64
65     virtual bool runOnMachineFunction(MachineFunction &MF) {
66       // Make sure we re-emit a set of the global base reg if necessary
67       GlobalBaseReg = 0;
68       SelectionDAGISel::runOnMachineFunction(MF);
69
70       if (!PPCSubTarget.isSVR4ABI())
71         InsertVRSaveCode(MF);
72
73       return true;
74     }
75
76     virtual void PostprocessISelDAG();
77
78     /// getI32Imm - Return a target constant with the specified value, of type
79     /// i32.
80     inline SDValue getI32Imm(unsigned Imm) {
81       return CurDAG->getTargetConstant(Imm, MVT::i32);
82     }
83
84     /// getI64Imm - Return a target constant with the specified value, of type
85     /// i64.
86     inline SDValue getI64Imm(uint64_t Imm) {
87       return CurDAG->getTargetConstant(Imm, MVT::i64);
88     }
89
90     /// getSmallIPtrImm - Return a target constant of pointer type.
91     inline SDValue getSmallIPtrImm(unsigned Imm) {
92       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
93     }
94
95     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
96     /// with any number of 0s on either side.  The 1s are allowed to wrap from
97     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
98     /// 0x0F0F0000 is not, since all 1s are not contiguous.
99     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
100
101
102     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
103     /// rotate and mask opcode and mask operation.
104     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
105                                 unsigned &SH, unsigned &MB, unsigned &ME);
106
107     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
108     /// base register.  Return the virtual register that holds this value.
109     SDNode *getGlobalBaseReg();
110
111     // Select - Convert the specified operand from a target-independent to a
112     // target-specific node if it hasn't already been changed.
113     SDNode *Select(SDNode *N);
114
115     SDNode *SelectBitfieldInsert(SDNode *N);
116
117     /// SelectCC - Select a comparison of the specified values with the
118     /// specified condition code, returning the CR# of the expression.
119     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
120
121     /// SelectAddrImm - Returns true if the address N can be represented by
122     /// a base register plus a signed 16-bit displacement [r+imm].
123     bool SelectAddrImm(SDValue N, SDValue &Disp,
124                        SDValue &Base) {
125       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
126     }
127
128     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
129     /// immediate field.  Note that the operand at this point is already the
130     /// result of a prior SelectAddressRegImm call.
131     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
132       if (N.getOpcode() == ISD::TargetConstant ||
133           N.getOpcode() == ISD::TargetGlobalAddress) {
134         Out = N;
135         return true;
136       }
137
138       return false;
139     }
140
141     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
142     /// represented as an indexed [r+r] operation.  Returns false if it can
143     /// be represented by [r+imm], which are preferred.
144     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
145       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
146     }
147
148     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
149     /// represented as an indexed [r+r] operation.
150     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
151       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
152     }
153
154     /// SelectAddrImmX4 - Returns true if the address N can be represented by
155     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
156     /// Suitable for use by STD and friends.
157     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
158       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
159     }
160
161     // Select an address into a single register.
162     bool SelectAddr(SDValue N, SDValue &Base) {
163       Base = N;
164       return true;
165     }
166
167     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
168     /// inline asm expressions.  It is always correct to compute the value into
169     /// a register.  The case of adding a (possibly relocatable) constant to a
170     /// register can be improved, but it is wrong to substitute Reg+Reg for
171     /// Reg in an asm, because the load or store opcode would have to change.
172    virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
173                                               char ConstraintCode,
174                                               std::vector<SDValue> &OutOps) {
175       OutOps.push_back(Op);
176       return false;
177     }
178
179     void InsertVRSaveCode(MachineFunction &MF);
180
181     virtual const char *getPassName() const {
182       return "PowerPC DAG->DAG Pattern Instruction Selection";
183     }
184
185 // Include the pieces autogenerated from the target description.
186 #include "PPCGenDAGISel.inc"
187
188 private:
189     SDNode *SelectSETCC(SDNode *N);
190
191     void PeepholePPC64();
192     void PeepholdCROps();
193
194     bool AllUsersSelectZero(SDNode *N);
195     void SwapAllSelectUsers(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::GPRC_NOR0RegClass);
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::G8RC_NOX0RegClass);
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 (!Val)
346     return false;
347
348   if (isShiftedMask_32(Val)) {
349     // look for the first non-zero bit
350     MB = countLeadingZeros(Val);
351     // look for the first zero bit after the run of ones
352     ME = countLeadingZeros((Val - 1) ^ Val);
353     return true;
354   } else {
355     Val = ~Val; // invert mask
356     if (isShiftedMask_32(Val)) {
357       // effectively look for the first zero bit
358       ME = countLeadingZeros(Val) - 1;
359       // effectively look for the first one bit after the run of zeros
360       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
361       return true;
362     }
363   }
364   // no run present
365   return false;
366 }
367
368 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
369                                       bool isShiftMask, unsigned &SH,
370                                       unsigned &MB, unsigned &ME) {
371   // Don't even go down this path for i64, since different logic will be
372   // necessary for rldicl/rldicr/rldimi.
373   if (N->getValueType(0) != MVT::i32)
374     return false;
375
376   unsigned Shift  = 32;
377   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
378   unsigned Opcode = N->getOpcode();
379   if (N->getNumOperands() != 2 ||
380       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
381     return false;
382
383   if (Opcode == ISD::SHL) {
384     // apply shift left to mask if it comes first
385     if (isShiftMask) Mask = Mask << Shift;
386     // determine which bits are made indeterminant by shift
387     Indeterminant = ~(0xFFFFFFFFu << Shift);
388   } else if (Opcode == ISD::SRL) {
389     // apply shift right to mask if it comes first
390     if (isShiftMask) Mask = Mask >> Shift;
391     // determine which bits are made indeterminant by shift
392     Indeterminant = ~(0xFFFFFFFFu >> Shift);
393     // adjust for the left rotate
394     Shift = 32 - Shift;
395   } else if (Opcode == ISD::ROTL) {
396     Indeterminant = 0;
397   } else {
398     return false;
399   }
400
401   // if the mask doesn't intersect any Indeterminant bits
402   if (Mask && !(Mask & Indeterminant)) {
403     SH = Shift & 31;
404     // make sure the mask is still a mask (wrap arounds may not be)
405     return isRunOfOnes(Mask, MB, ME);
406   }
407   return false;
408 }
409
410 /// SelectBitfieldInsert - turn an or of two masked values into
411 /// the rotate left word immediate then mask insert (rlwimi) instruction.
412 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
413   SDValue Op0 = N->getOperand(0);
414   SDValue Op1 = N->getOperand(1);
415   SDLoc dl(N);
416
417   APInt LKZ, LKO, RKZ, RKO;
418   CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
419   CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
420
421   unsigned TargetMask = LKZ.getZExtValue();
422   unsigned InsertMask = RKZ.getZExtValue();
423
424   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
425     unsigned Op0Opc = Op0.getOpcode();
426     unsigned Op1Opc = Op1.getOpcode();
427     unsigned Value, SH = 0;
428     TargetMask = ~TargetMask;
429     InsertMask = ~InsertMask;
430
431     // If the LHS has a foldable shift and the RHS does not, then swap it to the
432     // RHS so that we can fold the shift into the insert.
433     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
434       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
435           Op0.getOperand(0).getOpcode() == ISD::SRL) {
436         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
437             Op1.getOperand(0).getOpcode() != ISD::SRL) {
438           std::swap(Op0, Op1);
439           std::swap(Op0Opc, Op1Opc);
440           std::swap(TargetMask, InsertMask);
441         }
442       }
443     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
444       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
445           Op1.getOperand(0).getOpcode() != ISD::SRL) {
446         std::swap(Op0, Op1);
447         std::swap(Op0Opc, Op1Opc);
448         std::swap(TargetMask, InsertMask);
449       }
450     }
451
452     unsigned MB, ME;
453     if (isRunOfOnes(InsertMask, MB, ME)) {
454       SDValue Tmp1, Tmp2;
455
456       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
457           isInt32Immediate(Op1.getOperand(1), Value)) {
458         Op1 = Op1.getOperand(0);
459         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
460       }
461       if (Op1Opc == ISD::AND) {
462        // The AND mask might not be a constant, and we need to make sure that
463        // if we're going to fold the masking with the insert, all bits not
464        // know to be zero in the mask are known to be one.
465         APInt MKZ, MKO;
466         CurDAG->ComputeMaskedBits(Op1.getOperand(1), MKZ, MKO);
467         bool CanFoldMask = InsertMask == MKO.getZExtValue();
468
469         unsigned SHOpc = Op1.getOperand(0).getOpcode();
470         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
471             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
472           // Note that Value must be in range here (less than 32) because
473           // otherwise there would not be any bits set in InsertMask.
474           Op1 = Op1.getOperand(0).getOperand(0);
475           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
476         }
477       }
478
479       SH &= 31;
480       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
481                           getI32Imm(ME) };
482       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
483     }
484   }
485   return 0;
486 }
487
488 /// SelectCC - Select a comparison of the specified values with the specified
489 /// condition code, returning the CR# of the expression.
490 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
491                                     ISD::CondCode CC, SDLoc dl) {
492   // Always select the LHS.
493   unsigned Opc;
494
495   if (LHS.getValueType() == MVT::i32) {
496     unsigned Imm;
497     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
498       if (isInt32Immediate(RHS, Imm)) {
499         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
500         if (isUInt<16>(Imm))
501           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
502                                                 getI32Imm(Imm & 0xFFFF)), 0);
503         // If this is a 16-bit signed immediate, fold it.
504         if (isInt<16>((int)Imm))
505           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
506                                                 getI32Imm(Imm & 0xFFFF)), 0);
507
508         // For non-equality comparisons, the default code would materialize the
509         // constant, then compare against it, like this:
510         //   lis r2, 4660
511         //   ori r2, r2, 22136
512         //   cmpw cr0, r3, r2
513         // Since we are just comparing for equality, we can emit this instead:
514         //   xoris r0,r3,0x1234
515         //   cmplwi cr0,r0,0x5678
516         //   beq cr0,L6
517         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
518                                            getI32Imm(Imm >> 16)), 0);
519         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
520                                               getI32Imm(Imm & 0xFFFF)), 0);
521       }
522       Opc = PPC::CMPLW;
523     } else if (ISD::isUnsignedIntSetCC(CC)) {
524       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
525         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
526                                               getI32Imm(Imm & 0xFFFF)), 0);
527       Opc = PPC::CMPLW;
528     } else {
529       short SImm;
530       if (isIntS16Immediate(RHS, SImm))
531         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
532                                               getI32Imm((int)SImm & 0xFFFF)),
533                          0);
534       Opc = PPC::CMPW;
535     }
536   } else if (LHS.getValueType() == MVT::i64) {
537     uint64_t Imm;
538     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
539       if (isInt64Immediate(RHS.getNode(), Imm)) {
540         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
541         if (isUInt<16>(Imm))
542           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
543                                                 getI32Imm(Imm & 0xFFFF)), 0);
544         // If this is a 16-bit signed immediate, fold it.
545         if (isInt<16>(Imm))
546           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
547                                                 getI32Imm(Imm & 0xFFFF)), 0);
548
549         // For non-equality comparisons, the default code would materialize the
550         // constant, then compare against it, like this:
551         //   lis r2, 4660
552         //   ori r2, r2, 22136
553         //   cmpd cr0, r3, r2
554         // Since we are just comparing for equality, we can emit this instead:
555         //   xoris r0,r3,0x1234
556         //   cmpldi cr0,r0,0x5678
557         //   beq cr0,L6
558         if (isUInt<32>(Imm)) {
559           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
560                                              getI64Imm(Imm >> 16)), 0);
561           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
562                                                 getI64Imm(Imm & 0xFFFF)), 0);
563         }
564       }
565       Opc = PPC::CMPLD;
566     } else if (ISD::isUnsignedIntSetCC(CC)) {
567       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
568         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
569                                               getI64Imm(Imm & 0xFFFF)), 0);
570       Opc = PPC::CMPLD;
571     } else {
572       short SImm;
573       if (isIntS16Immediate(RHS, SImm))
574         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
575                                               getI64Imm(SImm & 0xFFFF)),
576                          0);
577       Opc = PPC::CMPD;
578     }
579   } else if (LHS.getValueType() == MVT::f32) {
580     Opc = PPC::FCMPUS;
581   } else {
582     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
583     Opc = PPCSubTarget.hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
584   }
585   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
586 }
587
588 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
589   switch (CC) {
590   case ISD::SETUEQ:
591   case ISD::SETONE:
592   case ISD::SETOLE:
593   case ISD::SETOGE:
594     llvm_unreachable("Should be lowered by legalize!");
595   default: llvm_unreachable("Unknown condition!");
596   case ISD::SETOEQ:
597   case ISD::SETEQ:  return PPC::PRED_EQ;
598   case ISD::SETUNE:
599   case ISD::SETNE:  return PPC::PRED_NE;
600   case ISD::SETOLT:
601   case ISD::SETLT:  return PPC::PRED_LT;
602   case ISD::SETULE:
603   case ISD::SETLE:  return PPC::PRED_LE;
604   case ISD::SETOGT:
605   case ISD::SETGT:  return PPC::PRED_GT;
606   case ISD::SETUGE:
607   case ISD::SETGE:  return PPC::PRED_GE;
608   case ISD::SETO:   return PPC::PRED_NU;
609   case ISD::SETUO:  return PPC::PRED_UN;
610     // These two are invalid for floating point.  Assume we have int.
611   case ISD::SETULT: return PPC::PRED_LT;
612   case ISD::SETUGT: return PPC::PRED_GT;
613   }
614 }
615
616 /// getCRIdxForSetCC - Return the index of the condition register field
617 /// associated with the SetCC condition, and whether or not the field is
618 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
619 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
620   Invert = false;
621   switch (CC) {
622   default: llvm_unreachable("Unknown condition!");
623   case ISD::SETOLT:
624   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
625   case ISD::SETOGT:
626   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
627   case ISD::SETOEQ:
628   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
629   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
630   case ISD::SETUGE:
631   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
632   case ISD::SETULE:
633   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
634   case ISD::SETUNE:
635   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
636   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
637   case ISD::SETUEQ:
638   case ISD::SETOGE:
639   case ISD::SETOLE:
640   case ISD::SETONE:
641     llvm_unreachable("Invalid branch code: should be expanded by legalize");
642   // These are invalid for floating point.  Assume integer.
643   case ISD::SETULT: return 0;
644   case ISD::SETUGT: return 1;
645   }
646 }
647
648 // getVCmpInst: return the vector compare instruction for the specified
649 // vector type and condition code. Since this is for altivec specific code,
650 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
651 static unsigned int getVCmpInst(MVT::SimpleValueType VecVT, ISD::CondCode CC,
652                                 bool HasVSX) {
653   switch (CC) {
654     case ISD::SETEQ:
655     case ISD::SETUEQ:
656     case ISD::SETNE:
657     case ISD::SETUNE:
658       if (VecVT == MVT::v16i8)
659         return PPC::VCMPEQUB;
660       else if (VecVT == MVT::v8i16)
661         return PPC::VCMPEQUH;
662       else if (VecVT == MVT::v4i32)
663         return PPC::VCMPEQUW;
664       // v4f32 != v4f32 could be translate to unordered not equal
665       else if (VecVT == MVT::v4f32)
666         return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
667       else if (VecVT == MVT::v2f64)
668         return PPC::XVCMPEQDP;
669       break;
670     case ISD::SETLT:
671     case ISD::SETGT:
672     case ISD::SETLE:
673     case ISD::SETGE:
674       if (VecVT == MVT::v16i8)
675         return PPC::VCMPGTSB;
676       else if (VecVT == MVT::v8i16)
677         return PPC::VCMPGTSH;
678       else if (VecVT == MVT::v4i32)
679         return PPC::VCMPGTSW;
680       else if (VecVT == MVT::v4f32)
681         return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
682       else if (VecVT == MVT::v2f64)
683         return PPC::XVCMPGTDP;
684       break;
685     case ISD::SETULT:
686     case ISD::SETUGT:
687     case ISD::SETUGE:
688     case ISD::SETULE:
689       if (VecVT == MVT::v16i8)
690         return PPC::VCMPGTUB;
691       else if (VecVT == MVT::v8i16)
692         return PPC::VCMPGTUH;
693       else if (VecVT == MVT::v4i32)
694         return PPC::VCMPGTUW;
695       break;
696     case ISD::SETOEQ:
697       if (VecVT == MVT::v4f32)
698         return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
699       else if (VecVT == MVT::v2f64)
700         return PPC::XVCMPEQDP;
701       break;
702     case ISD::SETOLT:
703     case ISD::SETOGT:
704     case ISD::SETOLE:
705       if (VecVT == MVT::v4f32)
706         return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
707       else if (VecVT == MVT::v2f64)
708         return PPC::XVCMPGTDP;
709       break;
710     case ISD::SETOGE:
711       if (VecVT == MVT::v4f32)
712         return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
713       else if (VecVT == MVT::v2f64)
714         return PPC::XVCMPGEDP;
715       break;
716     default:
717       break;
718   }
719   llvm_unreachable("Invalid integer vector compare condition");
720 }
721
722 // getVCmpEQInst: return the equal compare instruction for the specified vector
723 // type. Since this is for altivec specific code, only support the altivec
724 // types (v16i8, v8i16, v4i32, and v4f32).
725 static unsigned int getVCmpEQInst(MVT::SimpleValueType VecVT, bool HasVSX) {
726   switch (VecVT) {
727     case MVT::v16i8:
728       return PPC::VCMPEQUB;
729     case MVT::v8i16:
730       return PPC::VCMPEQUH;
731     case MVT::v4i32:
732       return PPC::VCMPEQUW;
733     case MVT::v4f32:
734       return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
735     case MVT::v2f64:
736       return PPC::XVCMPEQDP;
737     default:
738       llvm_unreachable("Invalid integer vector compare condition");
739   }
740 }
741
742 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
743   SDLoc dl(N);
744   unsigned Imm;
745   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
746   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
747   bool isPPC64 = (PtrVT == MVT::i64);
748
749   if (!PPCSubTarget.useCRBits() &&
750       isInt32Immediate(N->getOperand(1), Imm)) {
751     // We can codegen setcc op, imm very efficiently compared to a brcond.
752     // Check for those cases here.
753     // setcc op, 0
754     if (Imm == 0) {
755       SDValue Op = N->getOperand(0);
756       switch (CC) {
757       default: break;
758       case ISD::SETEQ: {
759         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
760         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
761         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
762       }
763       case ISD::SETNE: {
764         if (isPPC64) break;
765         SDValue AD =
766           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
767                                          Op, getI32Imm(~0U)), 0);
768         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
769                                     AD.getValue(1));
770       }
771       case ISD::SETLT: {
772         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
773         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
774       }
775       case ISD::SETGT: {
776         SDValue T =
777           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
778         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
779         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
780         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
781       }
782       }
783     } else if (Imm == ~0U) {        // setcc op, -1
784       SDValue Op = N->getOperand(0);
785       switch (CC) {
786       default: break;
787       case ISD::SETEQ:
788         if (isPPC64) break;
789         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
790                                             Op, getI32Imm(1)), 0);
791         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
792                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
793                                                              MVT::i32,
794                                                              getI32Imm(0)), 0),
795                                       Op.getValue(1));
796       case ISD::SETNE: {
797         if (isPPC64) break;
798         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
799         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
800                                             Op, getI32Imm(~0U));
801         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
802                                     Op, SDValue(AD, 1));
803       }
804       case ISD::SETLT: {
805         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
806                                                     getI32Imm(1)), 0);
807         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
808                                                     Op), 0);
809         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
810         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
811       }
812       case ISD::SETGT: {
813         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
814         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
815                      0);
816         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
817                                     getI32Imm(1));
818       }
819       }
820     }
821   }
822
823   SDValue LHS = N->getOperand(0);
824   SDValue RHS = N->getOperand(1);
825
826   // Altivec Vector compare instructions do not set any CR register by default and
827   // vector compare operations return the same type as the operands.
828   if (LHS.getValueType().isVector()) {
829     EVT VecVT = LHS.getValueType();
830     MVT::SimpleValueType VT = VecVT.getSimpleVT().SimpleTy;
831     unsigned int VCmpInst = getVCmpInst(VT, CC, PPCSubTarget.hasVSX());
832
833     switch (CC) {
834       case ISD::SETEQ:
835       case ISD::SETOEQ:
836       case ISD::SETUEQ:
837         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
838       case ISD::SETNE:
839       case ISD::SETONE:
840       case ISD::SETUNE: {
841         SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
842         return CurDAG->SelectNodeTo(N, PPCSubTarget.hasVSX() ? PPC::XXLNOR :
843                                                                PPC::VNOR,
844                                     VecVT, VCmp, VCmp);
845       } 
846       case ISD::SETLT:
847       case ISD::SETOLT:
848       case ISD::SETULT:
849         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, RHS, LHS);
850       case ISD::SETGT:
851       case ISD::SETOGT:
852       case ISD::SETUGT:
853         return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
854       case ISD::SETGE:
855       case ISD::SETOGE:
856       case ISD::SETUGE: {
857         // Small optimization: Altivec provides a 'Vector Compare Greater Than
858         // or Equal To' instruction (vcmpgefp), so in this case there is no
859         // need for extra logic for the equal compare.
860         if (VecVT.getSimpleVT().isFloatingPoint()) {
861           return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
862         } else {
863           SDValue VCmpGT(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
864           unsigned int VCmpEQInst = getVCmpEQInst(VT, PPCSubTarget.hasVSX());
865           SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
866           return CurDAG->SelectNodeTo(N, PPCSubTarget.hasVSX() ? PPC::XXLOR :
867                                                                  PPC::VOR,
868                                       VecVT, VCmpGT, VCmpEQ);
869         }
870       }
871       case ISD::SETLE:
872       case ISD::SETOLE:
873       case ISD::SETULE: {
874         SDValue VCmpLE(CurDAG->getMachineNode(VCmpInst, dl, VecVT, RHS, LHS), 0);
875         unsigned int VCmpEQInst = getVCmpEQInst(VT, PPCSubTarget.hasVSX());
876         SDValue VCmpEQ(CurDAG->getMachineNode(VCmpEQInst, dl, VecVT, LHS, RHS), 0);
877         return CurDAG->SelectNodeTo(N, PPCSubTarget.hasVSX() ? PPC::XXLOR :
878                                                                PPC::VOR,
879                                     VecVT, VCmpLE, VCmpEQ);
880       }
881       default:
882         llvm_unreachable("Invalid vector compare type: should be expanded by legalize");
883     }
884   }
885
886   if (PPCSubTarget.useCRBits())
887     return 0;
888
889   bool Inv;
890   unsigned Idx = getCRIdxForSetCC(CC, Inv);
891   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
892   SDValue IntCR;
893
894   // Force the ccreg into CR7.
895   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
896
897   SDValue InFlag(0, 0);  // Null incoming flag value.
898   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
899                                InFlag).getValue(1);
900
901   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
902                                          CCReg), 0);
903
904   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
905                       getI32Imm(31), getI32Imm(31) };
906   if (!Inv)
907     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
908
909   // Get the specified bit.
910   SDValue Tmp =
911     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
912   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
913 }
914
915
916 // Select - Convert the specified operand from a target-independent to a
917 // target-specific node if it hasn't already been changed.
918 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
919   SDLoc dl(N);
920   if (N->isMachineOpcode()) {
921     N->setNodeId(-1);
922     return NULL;   // Already selected.
923   }
924
925   switch (N->getOpcode()) {
926   default: break;
927
928   case ISD::Constant: {
929     if (N->getValueType(0) == MVT::i64) {
930       // Get 64 bit value.
931       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
932       // Assume no remaining bits.
933       unsigned Remainder = 0;
934       // Assume no shift required.
935       unsigned Shift = 0;
936
937       // If it can't be represented as a 32 bit value.
938       if (!isInt<32>(Imm)) {
939         Shift = countTrailingZeros<uint64_t>(Imm);
940         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
941
942         // If the shifted value fits 32 bits.
943         if (isInt<32>(ImmSh)) {
944           // Go with the shifted value.
945           Imm = ImmSh;
946         } else {
947           // Still stuck with a 64 bit value.
948           Remainder = Imm;
949           Shift = 32;
950           Imm >>= 32;
951         }
952       }
953
954       // Intermediate operand.
955       SDNode *Result;
956
957       // Handle first 32 bits.
958       unsigned Lo = Imm & 0xFFFF;
959       unsigned Hi = (Imm >> 16) & 0xFFFF;
960
961       // Simple value.
962       if (isInt<16>(Imm)) {
963        // Just the Lo bits.
964         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
965       } else if (Lo) {
966         // Handle the Hi bits.
967         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
968         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
969         // And Lo bits.
970         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
971                                         SDValue(Result, 0), getI32Imm(Lo));
972       } else {
973        // Just the Hi bits.
974         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
975       }
976
977       // If no shift, we're done.
978       if (!Shift) return Result;
979
980       // Shift for next step if the upper 32-bits were not zero.
981       if (Imm) {
982         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
983                                         SDValue(Result, 0),
984                                         getI32Imm(Shift),
985                                         getI32Imm(63 - Shift));
986       }
987
988       // Add in the last bits as required.
989       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
990         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
991                                         SDValue(Result, 0), getI32Imm(Hi));
992       }
993       if ((Lo = Remainder & 0xFFFF)) {
994         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
995                                         SDValue(Result, 0), getI32Imm(Lo));
996       }
997
998       return Result;
999     }
1000     break;
1001   }
1002
1003   case ISD::SETCC: {
1004     SDNode *SN = SelectSETCC(N);
1005     if (SN)
1006       return SN;
1007     break;
1008   }
1009   case PPCISD::GlobalBaseReg:
1010     return getGlobalBaseReg();
1011
1012   case ISD::FrameIndex: {
1013     int FI = cast<FrameIndexSDNode>(N)->getIndex();
1014     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
1015     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
1016     if (N->hasOneUse())
1017       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
1018                                   getSmallIPtrImm(0));
1019     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
1020                                   getSmallIPtrImm(0));
1021   }
1022
1023   case PPCISD::MFOCRF: {
1024     SDValue InFlag = N->getOperand(1);
1025     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
1026                                   N->getOperand(0), InFlag);
1027   }
1028
1029   case ISD::SDIV: {
1030     // FIXME: since this depends on the setting of the carry flag from the srawi
1031     //        we should really be making notes about that for the scheduler.
1032     // FIXME: It sure would be nice if we could cheaply recognize the
1033     //        srl/add/sra pattern the dag combiner will generate for this as
1034     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
1035     unsigned Imm;
1036     if (isInt32Immediate(N->getOperand(1), Imm)) {
1037       SDValue N0 = N->getOperand(0);
1038       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
1039         SDNode *Op =
1040           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1041                                  N0, getI32Imm(Log2_32(Imm)));
1042         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1043                                     SDValue(Op, 0), SDValue(Op, 1));
1044       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
1045         SDNode *Op =
1046           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1047                                  N0, getI32Imm(Log2_32(-Imm)));
1048         SDValue PT =
1049           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
1050                                          SDValue(Op, 0), SDValue(Op, 1)),
1051                     0);
1052         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1053       }
1054     }
1055
1056     // Other cases are autogenerated.
1057     break;
1058   }
1059
1060   case ISD::LOAD: {
1061     // Handle preincrement loads.
1062     LoadSDNode *LD = cast<LoadSDNode>(N);
1063     EVT LoadedVT = LD->getMemoryVT();
1064
1065     // Normal loads are handled by code generated from the .td file.
1066     if (LD->getAddressingMode() != ISD::PRE_INC)
1067       break;
1068
1069     SDValue Offset = LD->getOffset();
1070     if (Offset.getOpcode() == ISD::TargetConstant ||
1071         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1072
1073       unsigned Opcode;
1074       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1075       if (LD->getValueType(0) != MVT::i64) {
1076         // Handle PPC32 integer and normal FP loads.
1077         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1078         switch (LoadedVT.getSimpleVT().SimpleTy) {
1079           default: llvm_unreachable("Invalid PPC load type!");
1080           case MVT::f64: Opcode = PPC::LFDU; break;
1081           case MVT::f32: Opcode = PPC::LFSU; break;
1082           case MVT::i32: Opcode = PPC::LWZU; break;
1083           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1084           case MVT::i1:
1085           case MVT::i8:  Opcode = PPC::LBZU; break;
1086         }
1087       } else {
1088         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1089         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1090         switch (LoadedVT.getSimpleVT().SimpleTy) {
1091           default: llvm_unreachable("Invalid PPC load type!");
1092           case MVT::i64: Opcode = PPC::LDU; break;
1093           case MVT::i32: Opcode = PPC::LWZU8; break;
1094           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1095           case MVT::i1:
1096           case MVT::i8:  Opcode = PPC::LBZU8; break;
1097         }
1098       }
1099
1100       SDValue Chain = LD->getChain();
1101       SDValue Base = LD->getBasePtr();
1102       SDValue Ops[] = { Offset, Base, Chain };
1103       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1104                                     PPCLowering.getPointerTy(),
1105                                     MVT::Other, Ops);
1106     } else {
1107       unsigned Opcode;
1108       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1109       if (LD->getValueType(0) != MVT::i64) {
1110         // Handle PPC32 integer and normal FP loads.
1111         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1112         switch (LoadedVT.getSimpleVT().SimpleTy) {
1113           default: llvm_unreachable("Invalid PPC load type!");
1114           case MVT::f64: Opcode = PPC::LFDUX; break;
1115           case MVT::f32: Opcode = PPC::LFSUX; break;
1116           case MVT::i32: Opcode = PPC::LWZUX; break;
1117           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1118           case MVT::i1:
1119           case MVT::i8:  Opcode = PPC::LBZUX; break;
1120         }
1121       } else {
1122         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1123         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1124                "Invalid sext update load");
1125         switch (LoadedVT.getSimpleVT().SimpleTy) {
1126           default: llvm_unreachable("Invalid PPC load type!");
1127           case MVT::i64: Opcode = PPC::LDUX; break;
1128           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1129           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1130           case MVT::i1:
1131           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1132         }
1133       }
1134
1135       SDValue Chain = LD->getChain();
1136       SDValue Base = LD->getBasePtr();
1137       SDValue Ops[] = { Base, Offset, Chain };
1138       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1139                                     PPCLowering.getPointerTy(),
1140                                     MVT::Other, Ops);
1141     }
1142   }
1143
1144   case ISD::AND: {
1145     unsigned Imm, Imm2, SH, MB, ME;
1146     uint64_t Imm64;
1147
1148     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1149     // with a mask, emit rlwinm
1150     if (isInt32Immediate(N->getOperand(1), Imm) &&
1151         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1152       SDValue Val = N->getOperand(0).getOperand(0);
1153       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1154       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1155     }
1156     // If this is just a masked value where the input is not handled above, and
1157     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1158     if (isInt32Immediate(N->getOperand(1), Imm) &&
1159         isRunOfOnes(Imm, MB, ME) &&
1160         N->getOperand(0).getOpcode() != ISD::ROTL) {
1161       SDValue Val = N->getOperand(0);
1162       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1163       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1164     }
1165     // If this is a 64-bit zero-extension mask, emit rldicl.
1166     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1167         isMask_64(Imm64)) {
1168       SDValue Val = N->getOperand(0);
1169       MB = 64 - CountTrailingOnes_64(Imm64);
1170       SH = 0;
1171
1172       // If the operand is a logical right shift, we can fold it into this
1173       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
1174       // for n <= mb. The right shift is really a left rotate followed by a
1175       // mask, and this mask is a more-restrictive sub-mask of the mask implied
1176       // by the shift.
1177       if (Val.getOpcode() == ISD::SRL &&
1178           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
1179         assert(Imm < 64 && "Illegal shift amount");
1180         Val = Val.getOperand(0);
1181         SH = 64 - Imm;
1182       }
1183
1184       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
1185       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops, 3);
1186     }
1187     // AND X, 0 -> 0, not "rlwinm 32".
1188     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1189       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1190       return NULL;
1191     }
1192     // ISD::OR doesn't get all the bitfield insertion fun.
1193     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1194     if (isInt32Immediate(N->getOperand(1), Imm) &&
1195         N->getOperand(0).getOpcode() == ISD::OR &&
1196         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1197       unsigned MB, ME;
1198       Imm = ~(Imm^Imm2);
1199       if (isRunOfOnes(Imm, MB, ME)) {
1200         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1201                             N->getOperand(0).getOperand(1),
1202                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1203         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
1204       }
1205     }
1206
1207     // Other cases are autogenerated.
1208     break;
1209   }
1210   case ISD::OR:
1211     if (N->getValueType(0) == MVT::i32)
1212       if (SDNode *I = SelectBitfieldInsert(N))
1213         return I;
1214
1215     // Other cases are autogenerated.
1216     break;
1217   case ISD::SHL: {
1218     unsigned Imm, SH, MB, ME;
1219     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1220         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1221       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1222                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1223       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1224     }
1225
1226     // Other cases are autogenerated.
1227     break;
1228   }
1229   case ISD::SRL: {
1230     unsigned Imm, SH, MB, ME;
1231     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1232         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1233       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1234                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1235       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1236     }
1237
1238     // Other cases are autogenerated.
1239     break;
1240   }
1241   // FIXME: Remove this once the ANDI glue bug is fixed:
1242   case PPCISD::ANDIo_1_EQ_BIT:
1243   case PPCISD::ANDIo_1_GT_BIT: {
1244     if (!ANDIGlueBug)
1245       break;
1246
1247     EVT InVT = N->getOperand(0).getValueType();
1248     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
1249            "Invalid input type for ANDIo_1_EQ_BIT");
1250
1251     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
1252     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
1253                                         N->getOperand(0),
1254                                         CurDAG->getTargetConstant(1, InVT)), 0);
1255     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
1256     SDValue SRIdxVal =
1257       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
1258                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
1259
1260     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
1261                                 CR0Reg, SRIdxVal,
1262                                 SDValue(AndI.getNode(), 1) /* glue */);
1263   }
1264   case ISD::SELECT_CC: {
1265     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1266     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1267     bool isPPC64 = (PtrVT == MVT::i64);
1268
1269     // If this is a select of i1 operands, we'll pattern match it.
1270     if (PPCSubTarget.useCRBits() &&
1271         N->getOperand(0).getValueType() == MVT::i1)
1272       break;
1273
1274     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1275     if (!isPPC64)
1276       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1277         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1278           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1279             if (N1C->isNullValue() && N3C->isNullValue() &&
1280                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1281                 // FIXME: Implement this optzn for PPC64.
1282                 N->getValueType(0) == MVT::i32) {
1283               SDNode *Tmp =
1284                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1285                                        N->getOperand(0), getI32Imm(~0U));
1286               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1287                                           SDValue(Tmp, 0), N->getOperand(0),
1288                                           SDValue(Tmp, 1));
1289             }
1290
1291     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1292
1293     if (N->getValueType(0) == MVT::i1) {
1294       // An i1 select is: (c & t) | (!c & f).
1295       bool Inv;
1296       unsigned Idx = getCRIdxForSetCC(CC, Inv);
1297
1298       unsigned SRI;
1299       switch (Idx) {
1300       default: llvm_unreachable("Invalid CC index");
1301       case 0: SRI = PPC::sub_lt; break;
1302       case 1: SRI = PPC::sub_gt; break;
1303       case 2: SRI = PPC::sub_eq; break;
1304       case 3: SRI = PPC::sub_un; break;
1305       }
1306
1307       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
1308
1309       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
1310                                               CCBit, CCBit), 0);
1311       SDValue C =    Inv ? NotCCBit : CCBit,
1312               NotC = Inv ? CCBit    : NotCCBit;
1313
1314       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1315                                            C, N->getOperand(2)), 0);
1316       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1317                                               NotC, N->getOperand(3)), 0);
1318
1319       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
1320     }
1321
1322     unsigned BROpc = getPredicateForSetCC(CC);
1323
1324     unsigned SelectCCOp;
1325     if (N->getValueType(0) == MVT::i32)
1326       SelectCCOp = PPC::SELECT_CC_I4;
1327     else if (N->getValueType(0) == MVT::i64)
1328       SelectCCOp = PPC::SELECT_CC_I8;
1329     else if (N->getValueType(0) == MVT::f32)
1330       SelectCCOp = PPC::SELECT_CC_F4;
1331     else if (N->getValueType(0) == MVT::f64)
1332       SelectCCOp = PPC::SELECT_CC_F8;
1333     else
1334       SelectCCOp = PPC::SELECT_CC_VRRC;
1335
1336     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1337                         getI32Imm(BROpc) };
1338     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1339   }
1340   case ISD::VSELECT:
1341     if (PPCSubTarget.hasVSX()) {
1342       SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
1343       return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops, 3);
1344     }
1345
1346     break;
1347   case ISD::VECTOR_SHUFFLE:
1348     if (PPCSubTarget.hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
1349                                   N->getValueType(0) == MVT::v2i64)) {
1350       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
1351       
1352       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
1353               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
1354       unsigned DM[2];
1355
1356       for (int i = 0; i < 2; ++i)
1357         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
1358           DM[i] = 0;
1359         else
1360           DM[i] = 1;
1361
1362       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
1363
1364       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
1365           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
1366           isa<LoadSDNode>(Op1.getOperand(0))) {
1367         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
1368         SDValue Base, Offset;
1369
1370         if (LD->isUnindexed() &&
1371             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
1372           SDValue Chain = LD->getChain();
1373           SDValue Ops[] = { Base, Offset, Chain };
1374           return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
1375                                       N->getValueType(0), Ops, 3);
1376         }
1377       }
1378
1379       SDValue Ops[] = { Op1, Op2, DMV };
1380       return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops, 3);
1381     }
1382
1383     break;
1384   case PPCISD::BDNZ:
1385   case PPCISD::BDZ: {
1386     bool IsPPC64 = PPCSubTarget.isPPC64();
1387     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
1388     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
1389                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1390                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
1391                                 MVT::Other, Ops, 2);
1392   }
1393   case PPCISD::COND_BRANCH: {
1394     // Op #0 is the Chain.
1395     // Op #1 is the PPC::PRED_* number.
1396     // Op #2 is the CR#
1397     // Op #3 is the Dest MBB
1398     // Op #4 is the Flag.
1399     // Prevent PPC::PRED_* from being selected into LI.
1400     SDValue Pred =
1401       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1402     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1403       N->getOperand(0), N->getOperand(4) };
1404     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1405   }
1406   case ISD::BR_CC: {
1407     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1408     unsigned PCC = getPredicateForSetCC(CC);
1409
1410     if (N->getOperand(2).getValueType() == MVT::i1) {
1411       unsigned Opc;
1412       bool Swap;
1413       switch (PCC) {
1414       default: llvm_unreachable("Unexpected Boolean-operand predicate");
1415       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
1416       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
1417       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
1418       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
1419       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
1420       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
1421       }
1422
1423       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
1424                                              N->getOperand(Swap ? 3 : 2),
1425                                              N->getOperand(Swap ? 2 : 3)), 0);
1426       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
1427                                   BitComp, N->getOperand(4), N->getOperand(0));
1428     }
1429
1430     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1431     SDValue Ops[] = { getI32Imm(PCC), CondCode,
1432                         N->getOperand(4), N->getOperand(0) };
1433     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1434   }
1435   case ISD::BRIND: {
1436     // FIXME: Should custom lower this.
1437     SDValue Chain = N->getOperand(0);
1438     SDValue Target = N->getOperand(1);
1439     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1440     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1441     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1442                                            Chain), 0);
1443     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1444   }
1445   case PPCISD::TOC_ENTRY: {
1446     assert (PPCSubTarget.isPPC64() && "Only supported for 64-bit ABI");
1447
1448     // For medium and large code model, we generate two instructions as
1449     // described below.  Otherwise we allow SelectCodeCommon to handle this,
1450     // selecting one of LDtoc, LDtocJTI, and LDtocCPT.
1451     CodeModel::Model CModel = TM.getCodeModel();
1452     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
1453       break;
1454
1455     // The first source operand is a TargetGlobalAddress or a
1456     // TargetJumpTable.  If it is an externally defined symbol, a symbol
1457     // with common linkage, a function address, or a jump table address,
1458     // or if we are generating code for large code model, we generate:
1459     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
1460     // Otherwise we generate:
1461     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
1462     SDValue GA = N->getOperand(0);
1463     SDValue TOCbase = N->getOperand(1);
1464     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
1465                                         TOCbase, GA);
1466
1467     if (isa<JumpTableSDNode>(GA) || CModel == CodeModel::Large)
1468       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1469                                     SDValue(Tmp, 0));
1470
1471     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
1472       const GlobalValue *GValue = G->getGlobal();
1473       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
1474       const GlobalValue *RealGValue =
1475           GAlias ? GAlias->getAliasedGlobal() : GValue;
1476       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
1477       assert((GVar || isa<Function>(RealGValue)) &&
1478              "Unexpected global value subclass!");
1479
1480       // An external variable is one without an initializer.  For these,
1481       // for variables with common linkage, and for Functions, generate
1482       // the LDtocL form.
1483       if (!GVar || !GVar->hasInitializer() || RealGValue->hasCommonLinkage() ||
1484           RealGValue->hasAvailableExternallyLinkage())
1485         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1486                                       SDValue(Tmp, 0));
1487     }
1488
1489     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
1490                                   SDValue(Tmp, 0), GA);
1491   }
1492   case PPCISD::VADD_SPLAT: {
1493     // This expands into one of three sequences, depending on whether
1494     // the first operand is odd or even, positive or negative.
1495     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
1496            isa<ConstantSDNode>(N->getOperand(1)) &&
1497            "Invalid operand on VADD_SPLAT!");
1498
1499     int Elt     = N->getConstantOperandVal(0);
1500     int EltSize = N->getConstantOperandVal(1);
1501     unsigned Opc1, Opc2, Opc3;
1502     EVT VT;
1503
1504     if (EltSize == 1) {
1505       Opc1 = PPC::VSPLTISB;
1506       Opc2 = PPC::VADDUBM;
1507       Opc3 = PPC::VSUBUBM;
1508       VT = MVT::v16i8;
1509     } else if (EltSize == 2) {
1510       Opc1 = PPC::VSPLTISH;
1511       Opc2 = PPC::VADDUHM;
1512       Opc3 = PPC::VSUBUHM;
1513       VT = MVT::v8i16;
1514     } else {
1515       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
1516       Opc1 = PPC::VSPLTISW;
1517       Opc2 = PPC::VADDUWM;
1518       Opc3 = PPC::VSUBUWM;
1519       VT = MVT::v4i32;
1520     }
1521
1522     if ((Elt & 1) == 0) {
1523       // Elt is even, in the range [-32,-18] + [16,30].
1524       //
1525       // Convert: VADD_SPLAT elt, size
1526       // Into:    tmp = VSPLTIS[BHW] elt
1527       //          VADDU[BHW]M tmp, tmp
1528       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
1529       SDValue EltVal = getI32Imm(Elt >> 1);
1530       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1531       SDValue TmpVal = SDValue(Tmp, 0);
1532       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
1533
1534     } else if (Elt > 0) {
1535       // Elt is odd and positive, in the range [17,31].
1536       //
1537       // Convert: VADD_SPLAT elt, size
1538       // Into:    tmp1 = VSPLTIS[BHW] elt-16
1539       //          tmp2 = VSPLTIS[BHW] -16
1540       //          VSUBU[BHW]M tmp1, tmp2
1541       SDValue EltVal = getI32Imm(Elt - 16);
1542       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1543       EltVal = getI32Imm(-16);
1544       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1545       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
1546                                     SDValue(Tmp2, 0));
1547
1548     } else {
1549       // Elt is odd and negative, in the range [-31,-17].
1550       //
1551       // Convert: VADD_SPLAT elt, size
1552       // Into:    tmp1 = VSPLTIS[BHW] elt+16
1553       //          tmp2 = VSPLTIS[BHW] -16
1554       //          VADDU[BHW]M tmp1, tmp2
1555       SDValue EltVal = getI32Imm(Elt + 16);
1556       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1557       EltVal = getI32Imm(-16);
1558       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1559       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
1560                                     SDValue(Tmp2, 0));
1561     }
1562   }
1563   }
1564
1565   return SelectCode(N);
1566 }
1567
1568 /// PostprocessISelDAG - Perform some late peephole optimizations
1569 /// on the DAG representation.
1570 void PPCDAGToDAGISel::PostprocessISelDAG() {
1571
1572   // Skip peepholes at -O0.
1573   if (TM.getOptLevel() == CodeGenOpt::None)
1574     return;
1575
1576   PeepholePPC64();
1577   PeepholdCROps();
1578 }
1579
1580 // Check if all users of this node will become isel where the second operand
1581 // is the constant zero. If this is so, and if we can negate the condition,
1582 // then we can flip the true and false operands. This will allow the zero to
1583 // be folded with the isel so that we don't need to materialize a register
1584 // containing zero.
1585 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
1586   // If we're not using isel, then this does not matter.
1587   if (!PPCSubTarget.hasISEL())
1588     return false;
1589
1590   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1591        UI != UE; ++UI) {
1592     SDNode *User = *UI;
1593     if (!User->isMachineOpcode())
1594       return false;
1595     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
1596         User->getMachineOpcode() != PPC::SELECT_I8)
1597       return false;
1598
1599     SDNode *Op2 = User->getOperand(2).getNode();
1600     if (!Op2->isMachineOpcode())
1601       return false;
1602
1603     if (Op2->getMachineOpcode() != PPC::LI &&
1604         Op2->getMachineOpcode() != PPC::LI8)
1605       return false;
1606
1607     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
1608     if (!C)
1609       return false;
1610
1611     if (!C->isNullValue())
1612       return false;
1613   }
1614
1615   return true;
1616 }
1617
1618 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
1619   SmallVector<SDNode *, 4> ToReplace;
1620   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1621        UI != UE; ++UI) {
1622     SDNode *User = *UI;
1623     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
1624             User->getMachineOpcode() == PPC::SELECT_I8) &&
1625            "Must have all select users");
1626     ToReplace.push_back(User);
1627   }
1628
1629   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
1630        UE = ToReplace.end(); UI != UE; ++UI) {
1631     SDNode *User = *UI;
1632     SDNode *ResNode =
1633       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
1634                              User->getValueType(0), User->getOperand(0),
1635                              User->getOperand(2),
1636                              User->getOperand(1));
1637
1638       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1639       DEBUG(User->dump(CurDAG));
1640       DEBUG(dbgs() << "\nNew: ");
1641       DEBUG(ResNode->dump(CurDAG));
1642       DEBUG(dbgs() << "\n");
1643
1644       ReplaceUses(User, ResNode);
1645   }
1646 }
1647
1648 void PPCDAGToDAGISel::PeepholdCROps() {
1649   bool IsModified;
1650   do {
1651     IsModified = false;
1652     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1653          E = CurDAG->allnodes_end(); I != E; ++I) {
1654       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1655       if (!MachineNode || MachineNode->use_empty())
1656         continue;
1657       SDNode *ResNode = MachineNode;
1658
1659       bool Op1Set   = false, Op1Unset = false,
1660            Op1Not   = false,
1661            Op2Set   = false, Op2Unset = false,
1662            Op2Not   = false;
1663
1664       unsigned Opcode = MachineNode->getMachineOpcode();
1665       switch (Opcode) {
1666       default: break;
1667       case PPC::CRAND:
1668       case PPC::CRNAND:
1669       case PPC::CROR:
1670       case PPC::CRXOR:
1671       case PPC::CRNOR:
1672       case PPC::CREQV:
1673       case PPC::CRANDC:
1674       case PPC::CRORC: {
1675         SDValue Op = MachineNode->getOperand(1);
1676         if (Op.isMachineOpcode()) {
1677           if (Op.getMachineOpcode() == PPC::CRSET)
1678             Op2Set = true;
1679           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1680             Op2Unset = true;
1681           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1682                    Op.getOperand(0) == Op.getOperand(1))
1683             Op2Not = true;
1684         }
1685         }  // fallthrough
1686       case PPC::BC:
1687       case PPC::BCn:
1688       case PPC::SELECT_I4:
1689       case PPC::SELECT_I8:
1690       case PPC::SELECT_F4:
1691       case PPC::SELECT_F8:
1692       case PPC::SELECT_VRRC: {
1693         SDValue Op = MachineNode->getOperand(0);
1694         if (Op.isMachineOpcode()) {
1695           if (Op.getMachineOpcode() == PPC::CRSET)
1696             Op1Set = true;
1697           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1698             Op1Unset = true;
1699           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1700                    Op.getOperand(0) == Op.getOperand(1))
1701             Op1Not = true;
1702         }
1703         }
1704         break;
1705       }
1706
1707       bool SelectSwap = false;
1708       switch (Opcode) {
1709       default: break;
1710       case PPC::CRAND:
1711         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1712           // x & x = x
1713           ResNode = MachineNode->getOperand(0).getNode();
1714         else if (Op1Set)
1715           // 1 & y = y
1716           ResNode = MachineNode->getOperand(1).getNode();
1717         else if (Op2Set)
1718           // x & 1 = x
1719           ResNode = MachineNode->getOperand(0).getNode();
1720         else if (Op1Unset || Op2Unset)
1721           // x & 0 = 0 & y = 0
1722           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1723                                            MVT::i1);
1724         else if (Op1Not)
1725           // ~x & y = andc(y, x)
1726           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1727                                            MVT::i1, MachineNode->getOperand(1),
1728                                            MachineNode->getOperand(0).
1729                                              getOperand(0));
1730         else if (Op2Not)
1731           // x & ~y = andc(x, y)
1732           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1733                                            MVT::i1, MachineNode->getOperand(0),
1734                                            MachineNode->getOperand(1).
1735                                              getOperand(0));
1736         else if (AllUsersSelectZero(MachineNode))
1737           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1738                                            MVT::i1, MachineNode->getOperand(0),
1739                                            MachineNode->getOperand(1)),
1740           SelectSwap = true;
1741         break;
1742       case PPC::CRNAND:
1743         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1744           // nand(x, x) -> nor(x, x)
1745           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1746                                            MVT::i1, MachineNode->getOperand(0),
1747                                            MachineNode->getOperand(0));
1748         else if (Op1Set)
1749           // nand(1, y) -> nor(y, y)
1750           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1751                                            MVT::i1, MachineNode->getOperand(1),
1752                                            MachineNode->getOperand(1));
1753         else if (Op2Set)
1754           // nand(x, 1) -> nor(x, x)
1755           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1756                                            MVT::i1, MachineNode->getOperand(0),
1757                                            MachineNode->getOperand(0));
1758         else if (Op1Unset || Op2Unset)
1759           // nand(x, 0) = nand(0, y) = 1
1760           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1761                                            MVT::i1);
1762         else if (Op1Not)
1763           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
1764           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1765                                            MVT::i1, MachineNode->getOperand(0).
1766                                                       getOperand(0),
1767                                            MachineNode->getOperand(1));
1768         else if (Op2Not)
1769           // nand(x, ~y) = ~x | y = orc(y, x)
1770           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1771                                            MVT::i1, MachineNode->getOperand(1).
1772                                                       getOperand(0),
1773                                            MachineNode->getOperand(0));
1774         else if (AllUsersSelectZero(MachineNode))
1775           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1776                                            MVT::i1, MachineNode->getOperand(0),
1777                                            MachineNode->getOperand(1)),
1778           SelectSwap = true;
1779         break;
1780       case PPC::CROR:
1781         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1782           // x | x = x
1783           ResNode = MachineNode->getOperand(0).getNode();
1784         else if (Op1Set || Op2Set)
1785           // x | 1 = 1 | y = 1
1786           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1787                                            MVT::i1);
1788         else if (Op1Unset)
1789           // 0 | y = y
1790           ResNode = MachineNode->getOperand(1).getNode();
1791         else if (Op2Unset)
1792           // x | 0 = x
1793           ResNode = MachineNode->getOperand(0).getNode();
1794         else if (Op1Not)
1795           // ~x | y = orc(y, x)
1796           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1797                                            MVT::i1, MachineNode->getOperand(1),
1798                                            MachineNode->getOperand(0).
1799                                              getOperand(0));
1800         else if (Op2Not)
1801           // x | ~y = orc(x, y)
1802           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1803                                            MVT::i1, MachineNode->getOperand(0),
1804                                            MachineNode->getOperand(1).
1805                                              getOperand(0));
1806         else if (AllUsersSelectZero(MachineNode))
1807           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1808                                            MVT::i1, MachineNode->getOperand(0),
1809                                            MachineNode->getOperand(1)),
1810           SelectSwap = true;
1811         break;
1812       case PPC::CRXOR:
1813         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1814           // xor(x, x) = 0
1815           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1816                                            MVT::i1);
1817         else if (Op1Set)
1818           // xor(1, y) -> nor(y, y)
1819           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1820                                            MVT::i1, MachineNode->getOperand(1),
1821                                            MachineNode->getOperand(1));
1822         else if (Op2Set)
1823           // xor(x, 1) -> nor(x, x)
1824           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1825                                            MVT::i1, MachineNode->getOperand(0),
1826                                            MachineNode->getOperand(0));
1827         else if (Op1Unset)
1828           // xor(0, y) = y
1829           ResNode = MachineNode->getOperand(1).getNode();
1830         else if (Op2Unset)
1831           // xor(x, 0) = x
1832           ResNode = MachineNode->getOperand(0).getNode();
1833         else if (Op1Not)
1834           // xor(~x, y) = eqv(x, y)
1835           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1836                                            MVT::i1, MachineNode->getOperand(0).
1837                                                       getOperand(0),
1838                                            MachineNode->getOperand(1));
1839         else if (Op2Not)
1840           // xor(x, ~y) = eqv(x, y)
1841           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1842                                            MVT::i1, MachineNode->getOperand(0),
1843                                            MachineNode->getOperand(1).
1844                                              getOperand(0));
1845         else if (AllUsersSelectZero(MachineNode))
1846           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1847                                            MVT::i1, MachineNode->getOperand(0),
1848                                            MachineNode->getOperand(1)),
1849           SelectSwap = true;
1850         break;
1851       case PPC::CRNOR:
1852         if (Op1Set || Op2Set)
1853           // nor(1, y) -> 0
1854           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1855                                            MVT::i1);
1856         else if (Op1Unset)
1857           // nor(0, y) = ~y -> nor(y, y)
1858           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1859                                            MVT::i1, MachineNode->getOperand(1),
1860                                            MachineNode->getOperand(1));
1861         else if (Op2Unset)
1862           // nor(x, 0) = ~x
1863           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1864                                            MVT::i1, MachineNode->getOperand(0),
1865                                            MachineNode->getOperand(0));
1866         else if (Op1Not)
1867           // nor(~x, y) = andc(x, y)
1868           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1869                                            MVT::i1, MachineNode->getOperand(0).
1870                                                       getOperand(0),
1871                                            MachineNode->getOperand(1));
1872         else if (Op2Not)
1873           // nor(x, ~y) = andc(y, x)
1874           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1875                                            MVT::i1, MachineNode->getOperand(1).
1876                                                       getOperand(0),
1877                                            MachineNode->getOperand(0));
1878         else if (AllUsersSelectZero(MachineNode))
1879           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1880                                            MVT::i1, MachineNode->getOperand(0),
1881                                            MachineNode->getOperand(1)),
1882           SelectSwap = true;
1883         break;
1884       case PPC::CREQV:
1885         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1886           // eqv(x, x) = 1
1887           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1888                                            MVT::i1);
1889         else if (Op1Set)
1890           // eqv(1, y) = y
1891           ResNode = MachineNode->getOperand(1).getNode();
1892         else if (Op2Set)
1893           // eqv(x, 1) = x
1894           ResNode = MachineNode->getOperand(0).getNode();
1895         else if (Op1Unset)
1896           // eqv(0, y) = ~y -> nor(y, y)
1897           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1898                                            MVT::i1, MachineNode->getOperand(1),
1899                                            MachineNode->getOperand(1));
1900         else if (Op2Unset)
1901           // eqv(x, 0) = ~x
1902           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1903                                            MVT::i1, MachineNode->getOperand(0),
1904                                            MachineNode->getOperand(0));
1905         else if (Op1Not)
1906           // eqv(~x, y) = xor(x, y)
1907           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1908                                            MVT::i1, MachineNode->getOperand(0).
1909                                                       getOperand(0),
1910                                            MachineNode->getOperand(1));
1911         else if (Op2Not)
1912           // eqv(x, ~y) = xor(x, y)
1913           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1914                                            MVT::i1, MachineNode->getOperand(0),
1915                                            MachineNode->getOperand(1).
1916                                              getOperand(0));
1917         else if (AllUsersSelectZero(MachineNode))
1918           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1919                                            MVT::i1, MachineNode->getOperand(0),
1920                                            MachineNode->getOperand(1)),
1921           SelectSwap = true;
1922         break;
1923       case PPC::CRANDC:
1924         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1925           // andc(x, x) = 0
1926           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1927                                            MVT::i1);
1928         else if (Op1Set)
1929           // andc(1, y) = ~y
1930           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1931                                            MVT::i1, MachineNode->getOperand(1),
1932                                            MachineNode->getOperand(1));
1933         else if (Op1Unset || Op2Set)
1934           // andc(0, y) = andc(x, 1) = 0
1935           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1936                                            MVT::i1);
1937         else if (Op2Unset)
1938           // andc(x, 0) = x
1939           ResNode = MachineNode->getOperand(0).getNode();
1940         else if (Op1Not)
1941           // andc(~x, y) = ~(x | y) = nor(x, y)
1942           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1943                                            MVT::i1, MachineNode->getOperand(0).
1944                                                       getOperand(0),
1945                                            MachineNode->getOperand(1));
1946         else if (Op2Not)
1947           // andc(x, ~y) = x & y
1948           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1949                                            MVT::i1, MachineNode->getOperand(0),
1950                                            MachineNode->getOperand(1).
1951                                              getOperand(0));
1952         else if (AllUsersSelectZero(MachineNode))
1953           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1954                                            MVT::i1, MachineNode->getOperand(1),
1955                                            MachineNode->getOperand(0)),
1956           SelectSwap = true;
1957         break;
1958       case PPC::CRORC:
1959         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1960           // orc(x, x) = 1
1961           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1962                                            MVT::i1);
1963         else if (Op1Set || Op2Unset)
1964           // orc(1, y) = orc(x, 0) = 1
1965           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1966                                            MVT::i1);
1967         else if (Op2Set)
1968           // orc(x, 1) = x
1969           ResNode = MachineNode->getOperand(0).getNode();
1970         else if (Op1Unset)
1971           // orc(0, y) = ~y
1972           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1973                                            MVT::i1, MachineNode->getOperand(1),
1974                                            MachineNode->getOperand(1));
1975         else if (Op1Not)
1976           // orc(~x, y) = ~(x & y) = nand(x, y)
1977           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1978                                            MVT::i1, MachineNode->getOperand(0).
1979                                                       getOperand(0),
1980                                            MachineNode->getOperand(1));
1981         else if (Op2Not)
1982           // orc(x, ~y) = x | y
1983           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1984                                            MVT::i1, MachineNode->getOperand(0),
1985                                            MachineNode->getOperand(1).
1986                                              getOperand(0));
1987         else if (AllUsersSelectZero(MachineNode))
1988           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1989                                            MVT::i1, MachineNode->getOperand(1),
1990                                            MachineNode->getOperand(0)),
1991           SelectSwap = true;
1992         break;
1993       case PPC::SELECT_I4:
1994       case PPC::SELECT_I8:
1995       case PPC::SELECT_F4:
1996       case PPC::SELECT_F8:
1997       case PPC::SELECT_VRRC:
1998         if (Op1Set)
1999           ResNode = MachineNode->getOperand(1).getNode();
2000         else if (Op1Unset)
2001           ResNode = MachineNode->getOperand(2).getNode();
2002         else if (Op1Not)
2003           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
2004                                            SDLoc(MachineNode),
2005                                            MachineNode->getValueType(0),
2006                                            MachineNode->getOperand(0).
2007                                              getOperand(0),
2008                                            MachineNode->getOperand(2),
2009                                            MachineNode->getOperand(1));
2010         break;
2011       case PPC::BC:
2012       case PPC::BCn:
2013         if (Op1Not)
2014           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
2015                                                                PPC::BC,
2016                                            SDLoc(MachineNode),
2017                                            MVT::Other,
2018                                            MachineNode->getOperand(0).
2019                                              getOperand(0),
2020                                            MachineNode->getOperand(1),
2021                                            MachineNode->getOperand(2));
2022         // FIXME: Handle Op1Set, Op1Unset here too.
2023         break;
2024       }
2025
2026       // If we're inverting this node because it is used only by selects that
2027       // we'd like to swap, then swap the selects before the node replacement.
2028       if (SelectSwap)
2029         SwapAllSelectUsers(MachineNode);
2030
2031       if (ResNode != MachineNode) {
2032         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
2033         DEBUG(MachineNode->dump(CurDAG));
2034         DEBUG(dbgs() << "\nNew: ");
2035         DEBUG(ResNode->dump(CurDAG));
2036         DEBUG(dbgs() << "\n");
2037
2038         ReplaceUses(MachineNode, ResNode);
2039         IsModified = true;
2040       }
2041     }
2042     if (IsModified)
2043       CurDAG->RemoveDeadNodes();
2044   } while (IsModified);
2045 }
2046
2047 void PPCDAGToDAGISel::PeepholePPC64() {
2048   // These optimizations are currently supported only for 64-bit SVR4.
2049   if (PPCSubTarget.isDarwin() || !PPCSubTarget.isPPC64())
2050     return;
2051
2052   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
2053   ++Position;
2054
2055   while (Position != CurDAG->allnodes_begin()) {
2056     SDNode *N = --Position;
2057     // Skip dead nodes and any non-machine opcodes.
2058     if (N->use_empty() || !N->isMachineOpcode())
2059       continue;
2060
2061     unsigned FirstOp;
2062     unsigned StorageOpcode = N->getMachineOpcode();
2063
2064     switch (StorageOpcode) {
2065     default: continue;
2066
2067     case PPC::LBZ:
2068     case PPC::LBZ8:
2069     case PPC::LD:
2070     case PPC::LFD:
2071     case PPC::LFS:
2072     case PPC::LHA:
2073     case PPC::LHA8:
2074     case PPC::LHZ:
2075     case PPC::LHZ8:
2076     case PPC::LWA:
2077     case PPC::LWZ:
2078     case PPC::LWZ8:
2079       FirstOp = 0;
2080       break;
2081
2082     case PPC::STB:
2083     case PPC::STB8:
2084     case PPC::STD:
2085     case PPC::STFD:
2086     case PPC::STFS:
2087     case PPC::STH:
2088     case PPC::STH8:
2089     case PPC::STW:
2090     case PPC::STW8:
2091       FirstOp = 1;
2092       break;
2093     }
2094
2095     // If this is a load or store with a zero offset, we may be able to
2096     // fold an add-immediate into the memory operation.
2097     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
2098         N->getConstantOperandVal(FirstOp) != 0)
2099       continue;
2100
2101     SDValue Base = N->getOperand(FirstOp + 1);
2102     if (!Base.isMachineOpcode())
2103       continue;
2104
2105     unsigned Flags = 0;
2106     bool ReplaceFlags = true;
2107
2108     // When the feeding operation is an add-immediate of some sort,
2109     // determine whether we need to add relocation information to the
2110     // target flags on the immediate operand when we fold it into the
2111     // load instruction.
2112     //
2113     // For something like ADDItocL, the relocation information is
2114     // inferred from the opcode; when we process it in the AsmPrinter,
2115     // we add the necessary relocation there.  A load, though, can receive
2116     // relocation from various flavors of ADDIxxx, so we need to carry
2117     // the relocation information in the target flags.
2118     switch (Base.getMachineOpcode()) {
2119     default: continue;
2120
2121     case PPC::ADDI8:
2122     case PPC::ADDI:
2123       // In some cases (such as TLS) the relocation information
2124       // is already in place on the operand, so copying the operand
2125       // is sufficient.
2126       ReplaceFlags = false;
2127       // For these cases, the immediate may not be divisible by 4, in
2128       // which case the fold is illegal for DS-form instructions.  (The
2129       // other cases provide aligned addresses and are always safe.)
2130       if ((StorageOpcode == PPC::LWA ||
2131            StorageOpcode == PPC::LD  ||
2132            StorageOpcode == PPC::STD) &&
2133           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
2134            Base.getConstantOperandVal(1) % 4 != 0))
2135         continue;
2136       break;
2137     case PPC::ADDIdtprelL:
2138       Flags = PPCII::MO_DTPREL_LO;
2139       break;
2140     case PPC::ADDItlsldL:
2141       Flags = PPCII::MO_TLSLD_LO;
2142       break;
2143     case PPC::ADDItocL:
2144       Flags = PPCII::MO_TOC_LO;
2145       break;
2146     }
2147
2148     // We found an opportunity.  Reverse the operands from the add
2149     // immediate and substitute them into the load or store.  If
2150     // needed, update the target flags for the immediate operand to
2151     // reflect the necessary relocation information.
2152     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
2153     DEBUG(Base->dump(CurDAG));
2154     DEBUG(dbgs() << "\nN: ");
2155     DEBUG(N->dump(CurDAG));
2156     DEBUG(dbgs() << "\n");
2157
2158     SDValue ImmOpnd = Base.getOperand(1);
2159
2160     // If the relocation information isn't already present on the
2161     // immediate operand, add it now.
2162     if (ReplaceFlags) {
2163       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
2164         SDLoc dl(GA);
2165         const GlobalValue *GV = GA->getGlobal();
2166         // We can't perform this optimization for data whose alignment
2167         // is insufficient for the instruction encoding.
2168         if (GV->getAlignment() < 4 &&
2169             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
2170              StorageOpcode == PPC::LWA)) {
2171           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
2172           continue;
2173         }
2174         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
2175       } else if (ConstantPoolSDNode *CP =
2176                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
2177         const Constant *C = CP->getConstVal();
2178         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
2179                                                 CP->getAlignment(),
2180                                                 0, Flags);
2181       }
2182     }
2183
2184     if (FirstOp == 1) // Store
2185       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
2186                                        Base.getOperand(0), N->getOperand(3));
2187     else // Load
2188       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
2189                                        N->getOperand(2));
2190
2191     // The add-immediate may now be dead, in which case remove it.
2192     if (Base.getNode()->use_empty())
2193       CurDAG->RemoveDeadNode(Base.getNode());
2194   }
2195 }
2196
2197
2198 /// createPPCISelDag - This pass converts a legalized DAG into a
2199 /// PowerPC-specific DAG, ready for instruction scheduling.
2200 ///
2201 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
2202   return new PPCDAGToDAGISel(TM);
2203 }
2204
2205 static void initializePassOnce(PassRegistry &Registry) {
2206   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
2207   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID, 0,
2208                               false, false);
2209   Registry.registerPass(*PI, true);
2210 }
2211
2212 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
2213   CALL_ONCE_INITIALIZATION(initializePassOnce);
2214 }
2215