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