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