[PowerPC] Materialize i64 constants using rotation
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "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 cl::opt<bool> UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
46   cl::desc("use aggressive ppc isel for bit permutations"), cl::Hidden);
47 cl::opt<bool> BPermRewriterNoMasking("ppc-bit-perm-rewriter-stress-rotates",
48   cl::desc("stress rotate selection in aggressive ppc isel for "
49            "bit permutations"), cl::Hidden);
50
51 namespace llvm {
52   void initializePPCDAGToDAGISelPass(PassRegistry&);
53 }
54
55 namespace {
56   //===--------------------------------------------------------------------===//
57   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
58   /// instructions for SelectionDAG operations.
59   ///
60   class PPCDAGToDAGISel : public SelectionDAGISel {
61     const PPCTargetMachine &TM;
62     const PPCTargetLowering *PPCLowering;
63     const PPCSubtarget *PPCSubTarget;
64     unsigned GlobalBaseReg;
65   public:
66     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
67         : SelectionDAGISel(tm), TM(tm),
68           PPCLowering(TM.getSubtargetImpl()->getTargetLowering()),
69           PPCSubTarget(TM.getSubtargetImpl()) {
70       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
71     }
72
73     bool runOnMachineFunction(MachineFunction &MF) override {
74       // Make sure we re-emit a set of the global base reg if necessary
75       GlobalBaseReg = 0;
76       PPCLowering = TM.getSubtargetImpl()->getTargetLowering();
77       PPCSubTarget = TM.getSubtargetImpl();
78       SelectionDAGISel::runOnMachineFunction(MF);
79
80       if (!PPCSubTarget->isSVR4ABI())
81         InsertVRSaveCode(MF);
82
83       return true;
84     }
85
86     void PreprocessISelDAG() override;
87     void PostprocessISelDAG() override;
88
89     /// getI32Imm - Return a target constant with the specified value, of type
90     /// i32.
91     inline SDValue getI32Imm(unsigned Imm) {
92       return CurDAG->getTargetConstant(Imm, MVT::i32);
93     }
94
95     /// getI64Imm - Return a target constant with the specified value, of type
96     /// i64.
97     inline SDValue getI64Imm(uint64_t Imm) {
98       return CurDAG->getTargetConstant(Imm, MVT::i64);
99     }
100
101     /// getSmallIPtrImm - Return a target constant of pointer type.
102     inline SDValue getSmallIPtrImm(unsigned Imm) {
103       return CurDAG->getTargetConstant(Imm, PPCLowering->getPointerTy());
104     }
105
106     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
107     /// with any number of 0s on either side.  The 1s are allowed to wrap from
108     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
109     /// 0x0F0F0000 is not, since all 1s are not contiguous.
110     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
111
112
113     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
114     /// rotate and mask opcode and mask operation.
115     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
116                                 unsigned &SH, unsigned &MB, unsigned &ME);
117
118     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
119     /// base register.  Return the virtual register that holds this value.
120     SDNode *getGlobalBaseReg();
121
122     SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
123
124     // Select - Convert the specified operand from a target-independent to a
125     // target-specific node if it hasn't already been changed.
126     SDNode *Select(SDNode *N) override;
127
128     SDNode *SelectBitfieldInsert(SDNode *N);
129     SDNode *SelectBitPermutation(SDNode *N);
130
131     /// SelectCC - Select a comparison of the specified values with the
132     /// specified condition code, returning the CR# of the expression.
133     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
134
135     /// SelectAddrImm - Returns true if the address N can be represented by
136     /// a base register plus a signed 16-bit displacement [r+imm].
137     bool SelectAddrImm(SDValue N, SDValue &Disp,
138                        SDValue &Base) {
139       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
140     }
141
142     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
143     /// immediate field.  Note that the operand at this point is already the
144     /// result of a prior SelectAddressRegImm call.
145     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
146       if (N.getOpcode() == ISD::TargetConstant ||
147           N.getOpcode() == ISD::TargetGlobalAddress) {
148         Out = N;
149         return true;
150       }
151
152       return false;
153     }
154
155     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
156     /// represented as an indexed [r+r] operation.  Returns false if it can
157     /// be represented by [r+imm], which are preferred.
158     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
159       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
160     }
161
162     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
163     /// represented as an indexed [r+r] operation.
164     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
165       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
166     }
167
168     /// SelectAddrImmX4 - Returns true if the address N can be represented by
169     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
170     /// Suitable for use by STD and friends.
171     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
172       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
173     }
174
175     // Select an address into a single register.
176     bool SelectAddr(SDValue N, SDValue &Base) {
177       Base = N;
178       return true;
179     }
180
181     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
182     /// inline asm expressions.  It is always correct to compute the value into
183     /// a register.  The case of adding a (possibly relocatable) constant to a
184     /// register can be improved, but it is wrong to substitute Reg+Reg for
185     /// Reg in an asm, because the load or store opcode would have to change.
186     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
187                                       char ConstraintCode,
188                                       std::vector<SDValue> &OutOps) override {
189       // We need to make sure that this one operand does not end up in r0
190       // (because we might end up lowering this as 0(%op)).
191       const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
192       const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
193       SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
194       SDValue NewOp =
195         SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
196                                        SDLoc(Op), Op.getValueType(),
197                                        Op, RC), 0);
198
199       OutOps.push_back(NewOp);
200       return false;
201     }
202
203     void InsertVRSaveCode(MachineFunction &MF);
204
205     const char *getPassName() const override {
206       return "PowerPC DAG->DAG Pattern Instruction Selection";
207     }
208
209 // Include the pieces autogenerated from the target description.
210 #include "PPCGenDAGISel.inc"
211
212 private:
213     SDNode *SelectSETCC(SDNode *N);
214
215     void PeepholePPC64();
216     void PeepholePPC64ZExt();
217     void PeepholeCROps();
218
219     SDValue combineToCMPB(SDNode *N);
220
221     bool AllUsersSelectZero(SDNode *N);
222     void SwapAllSelectUsers(SDNode *N);
223   };
224 }
225
226 /// InsertVRSaveCode - Once the entire function has been instruction selected,
227 /// all virtual registers are created and all machine instructions are built,
228 /// check to see if we need to save/restore VRSAVE.  If so, do it.
229 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
230   // Check to see if this function uses vector registers, which means we have to
231   // save and restore the VRSAVE register and update it with the regs we use.
232   //
233   // In this case, there will be virtual registers of vector type created
234   // by the scheduler.  Detect them now.
235   bool HasVectorVReg = false;
236   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
237     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
238     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
239       HasVectorVReg = true;
240       break;
241     }
242   }
243   if (!HasVectorVReg) return;  // nothing to do.
244
245   // If we have a vector register, we want to emit code into the entry and exit
246   // blocks to save and restore the VRSAVE register.  We do this here (instead
247   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
248   //
249   // 1. This (trivially) reduces the load on the register allocator, by not
250   //    having to represent the live range of the VRSAVE register.
251   // 2. This (more significantly) allows us to create a temporary virtual
252   //    register to hold the saved VRSAVE value, allowing this temporary to be
253   //    register allocated, instead of forcing it to be spilled to the stack.
254
255   // Create two vregs - one to hold the VRSAVE register that is live-in to the
256   // function and one for the value after having bits or'd into it.
257   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
258   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
259
260   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
261   MachineBasicBlock &EntryBB = *Fn.begin();
262   DebugLoc dl;
263   // Emit the following code into the entry block:
264   // InVRSAVE = MFVRSAVE
265   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
266   // MTVRSAVE UpdatedVRSAVE
267   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
268   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
269   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
270           UpdatedVRSAVE).addReg(InVRSAVE);
271   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
272
273   // Find all return blocks, outputting a restore in each epilog.
274   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
275     if (!BB->empty() && BB->back().isReturn()) {
276       IP = BB->end(); --IP;
277
278       // Skip over all terminator instructions, which are part of the return
279       // sequence.
280       MachineBasicBlock::iterator I2 = IP;
281       while (I2 != BB->begin() && (--I2)->isTerminator())
282         IP = I2;
283
284       // Emit: MTVRSAVE InVRSave
285       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
286     }
287   }
288 }
289
290
291 /// getGlobalBaseReg - Output the instructions required to put the
292 /// base address to use for accessing globals into a register.
293 ///
294 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
295   if (!GlobalBaseReg) {
296     const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
297     // Insert the set of GlobalBaseReg into the first MBB of the function
298     MachineBasicBlock &FirstMBB = MF->front();
299     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
300     const Module *M = MF->getFunction()->getParent();
301     DebugLoc dl;
302
303     if (PPCLowering->getPointerTy() == MVT::i32) {
304       if (PPCSubTarget->isTargetELF()) {
305         GlobalBaseReg = PPC::R30;
306         if (M->getPICLevel() == PICLevel::Small) {
307           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
308           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
309         } else {
310           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
311           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
312           unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
313           BuildMI(FirstMBB, MBBI, dl,
314                   TII.get(PPC::UpdateGBR)).addReg(GlobalBaseReg)
315                   .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
316           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
317         }
318       } else {
319         GlobalBaseReg =
320           RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
321         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
322         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
323       }
324     } else {
325       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
326       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
327       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
328     }
329   }
330   return CurDAG->getRegister(GlobalBaseReg,
331                              PPCLowering->getPointerTy()).getNode();
332 }
333
334 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
335 /// or 64-bit immediate, and if the value can be accurately represented as a
336 /// sign extension from a 16-bit value.  If so, this returns true and the
337 /// immediate.
338 static bool isIntS16Immediate(SDNode *N, short &Imm) {
339   if (N->getOpcode() != ISD::Constant)
340     return false;
341
342   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
343   if (N->getValueType(0) == MVT::i32)
344     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
345   else
346     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
347 }
348
349 static bool isIntS16Immediate(SDValue Op, short &Imm) {
350   return isIntS16Immediate(Op.getNode(), Imm);
351 }
352
353
354 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
355 /// operand. If so Imm will receive the 32-bit value.
356 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
357   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
358     Imm = cast<ConstantSDNode>(N)->getZExtValue();
359     return true;
360   }
361   return false;
362 }
363
364 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
365 /// operand.  If so Imm will receive the 64-bit value.
366 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
367   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
368     Imm = cast<ConstantSDNode>(N)->getZExtValue();
369     return true;
370   }
371   return false;
372 }
373
374 // isInt32Immediate - This method tests to see if a constant operand.
375 // If so Imm will receive the 32 bit value.
376 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
377   return isInt32Immediate(N.getNode(), Imm);
378 }
379
380
381 // isOpcWithIntImmediate - This method tests to see if the node is a specific
382 // opcode and that it has a immediate integer right operand.
383 // If so Imm will receive the 32 bit value.
384 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
385   return N->getOpcode() == Opc
386          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
387 }
388
389 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
390   SDLoc dl(SN);
391   int FI = cast<FrameIndexSDNode>(N)->getIndex();
392   SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
393   unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
394   if (SN->hasOneUse())
395     return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
396                                 getSmallIPtrImm(Offset));
397   return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
398                                 getSmallIPtrImm(Offset));
399 }
400
401 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
402   if (!Val)
403     return false;
404
405   if (isShiftedMask_32(Val)) {
406     // look for the first non-zero bit
407     MB = countLeadingZeros(Val);
408     // look for the first zero bit after the run of ones
409     ME = countLeadingZeros((Val - 1) ^ Val);
410     return true;
411   } else {
412     Val = ~Val; // invert mask
413     if (isShiftedMask_32(Val)) {
414       // effectively look for the first zero bit
415       ME = countLeadingZeros(Val) - 1;
416       // effectively look for the first one bit after the run of zeros
417       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
418       return true;
419     }
420   }
421   // no run present
422   return false;
423 }
424
425 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
426                                       bool isShiftMask, unsigned &SH,
427                                       unsigned &MB, unsigned &ME) {
428   // Don't even go down this path for i64, since different logic will be
429   // necessary for rldicl/rldicr/rldimi.
430   if (N->getValueType(0) != MVT::i32)
431     return false;
432
433   unsigned Shift  = 32;
434   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
435   unsigned Opcode = N->getOpcode();
436   if (N->getNumOperands() != 2 ||
437       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
438     return false;
439
440   if (Opcode == ISD::SHL) {
441     // apply shift left to mask if it comes first
442     if (isShiftMask) Mask = Mask << Shift;
443     // determine which bits are made indeterminant by shift
444     Indeterminant = ~(0xFFFFFFFFu << Shift);
445   } else if (Opcode == ISD::SRL) {
446     // apply shift right to mask if it comes first
447     if (isShiftMask) Mask = Mask >> Shift;
448     // determine which bits are made indeterminant by shift
449     Indeterminant = ~(0xFFFFFFFFu >> Shift);
450     // adjust for the left rotate
451     Shift = 32 - Shift;
452   } else if (Opcode == ISD::ROTL) {
453     Indeterminant = 0;
454   } else {
455     return false;
456   }
457
458   // if the mask doesn't intersect any Indeterminant bits
459   if (Mask && !(Mask & Indeterminant)) {
460     SH = Shift & 31;
461     // make sure the mask is still a mask (wrap arounds may not be)
462     return isRunOfOnes(Mask, MB, ME);
463   }
464   return false;
465 }
466
467 /// SelectBitfieldInsert - turn an or of two masked values into
468 /// the rotate left word immediate then mask insert (rlwimi) instruction.
469 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
470   SDValue Op0 = N->getOperand(0);
471   SDValue Op1 = N->getOperand(1);
472   SDLoc dl(N);
473
474   APInt LKZ, LKO, RKZ, RKO;
475   CurDAG->computeKnownBits(Op0, LKZ, LKO);
476   CurDAG->computeKnownBits(Op1, RKZ, RKO);
477
478   unsigned TargetMask = LKZ.getZExtValue();
479   unsigned InsertMask = RKZ.getZExtValue();
480
481   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
482     unsigned Op0Opc = Op0.getOpcode();
483     unsigned Op1Opc = Op1.getOpcode();
484     unsigned Value, SH = 0;
485     TargetMask = ~TargetMask;
486     InsertMask = ~InsertMask;
487
488     // If the LHS has a foldable shift and the RHS does not, then swap it to the
489     // RHS so that we can fold the shift into the insert.
490     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
491       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
492           Op0.getOperand(0).getOpcode() == ISD::SRL) {
493         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
494             Op1.getOperand(0).getOpcode() != ISD::SRL) {
495           std::swap(Op0, Op1);
496           std::swap(Op0Opc, Op1Opc);
497           std::swap(TargetMask, InsertMask);
498         }
499       }
500     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
501       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
502           Op1.getOperand(0).getOpcode() != ISD::SRL) {
503         std::swap(Op0, Op1);
504         std::swap(Op0Opc, Op1Opc);
505         std::swap(TargetMask, InsertMask);
506       }
507     }
508
509     unsigned MB, ME;
510     if (isRunOfOnes(InsertMask, MB, ME)) {
511       SDValue Tmp1, Tmp2;
512
513       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
514           isInt32Immediate(Op1.getOperand(1), Value)) {
515         Op1 = Op1.getOperand(0);
516         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
517       }
518       if (Op1Opc == ISD::AND) {
519        // The AND mask might not be a constant, and we need to make sure that
520        // if we're going to fold the masking with the insert, all bits not
521        // know to be zero in the mask are known to be one.
522         APInt MKZ, MKO;
523         CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
524         bool CanFoldMask = InsertMask == MKO.getZExtValue();
525
526         unsigned SHOpc = Op1.getOperand(0).getOpcode();
527         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
528             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
529           // Note that Value must be in range here (less than 32) because
530           // otherwise there would not be any bits set in InsertMask.
531           Op1 = Op1.getOperand(0).getOperand(0);
532           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
533         }
534       }
535
536       SH &= 31;
537       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
538                           getI32Imm(ME) };
539       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
540     }
541   }
542   return nullptr;
543 }
544
545 // Predict the number of instructions that would be generated by calling
546 // SelectInt64(N).
547 static unsigned SelectInt64CountDirect(int64_t Imm) {
548   // Assume no remaining bits.
549   unsigned Remainder = 0;
550   // Assume no shift required.
551   unsigned Shift = 0;
552
553   // If it can't be represented as a 32 bit value.
554   if (!isInt<32>(Imm)) {
555     Shift = countTrailingZeros<uint64_t>(Imm);
556     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
557
558     // If the shifted value fits 32 bits.
559     if (isInt<32>(ImmSh)) {
560       // Go with the shifted value.
561       Imm = ImmSh;
562     } else {
563       // Still stuck with a 64 bit value.
564       Remainder = Imm;
565       Shift = 32;
566       Imm >>= 32;
567     }
568   }
569
570   // Intermediate operand.
571   unsigned Result = 0;
572
573   // Handle first 32 bits.
574   unsigned Lo = Imm & 0xFFFF;
575   unsigned Hi = (Imm >> 16) & 0xFFFF;
576
577   // Simple value.
578   if (isInt<16>(Imm)) {
579     // Just the Lo bits.
580     ++Result;
581   } else if (Lo) {
582     // Handle the Hi bits and Lo bits.
583     Result += 2;
584   } else {
585     // Just the Hi bits.
586     ++Result;
587   }
588
589   // If no shift, we're done.
590   if (!Shift) return Result;
591
592   // Shift for next step if the upper 32-bits were not zero.
593   if (Imm)
594     ++Result;
595
596   // Add in the last bits as required.
597   if ((Hi = (Remainder >> 16) & 0xFFFF))
598     ++Result;
599   if ((Lo = Remainder & 0xFFFF))
600     ++Result;
601
602   return Result;
603 }
604
605 static uint64_t Rot64(uint64_t Imm, unsigned R) {
606   return (Imm << R) | (Imm >> (64 - R));
607 }
608
609 static unsigned SelectInt64Count(int64_t Imm) {
610   unsigned Count = SelectInt64CountDirect(Imm);
611
612   for (unsigned r = 1; r < 63; ++r) {
613     unsigned RCount = SelectInt64CountDirect(Rot64(Imm, r)) + 1;
614     Count = std::min(Count, RCount);
615   }
616
617   return Count;
618 }
619
620 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
621 // (above) needs to be kept in sync with this function.
622 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
623   // Assume no remaining bits.
624   unsigned Remainder = 0;
625   // Assume no shift required.
626   unsigned Shift = 0;
627
628   // If it can't be represented as a 32 bit value.
629   if (!isInt<32>(Imm)) {
630     Shift = countTrailingZeros<uint64_t>(Imm);
631     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
632
633     // If the shifted value fits 32 bits.
634     if (isInt<32>(ImmSh)) {
635       // Go with the shifted value.
636       Imm = ImmSh;
637     } else {
638       // Still stuck with a 64 bit value.
639       Remainder = Imm;
640       Shift = 32;
641       Imm >>= 32;
642     }
643   }
644
645   // Intermediate operand.
646   SDNode *Result;
647
648   // Handle first 32 bits.
649   unsigned Lo = Imm & 0xFFFF;
650   unsigned Hi = (Imm >> 16) & 0xFFFF;
651
652   auto getI32Imm = [CurDAG](unsigned Imm) {
653       return CurDAG->getTargetConstant(Imm, MVT::i32);
654   };
655
656   // Simple value.
657   if (isInt<16>(Imm)) {
658     // Just the Lo bits.
659     Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
660   } else if (Lo) {
661     // Handle the Hi bits.
662     unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
663     Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
664     // And Lo bits.
665     Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
666                                     SDValue(Result, 0), getI32Imm(Lo));
667   } else {
668     // Just the Hi bits.
669     Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
670   }
671
672   // If no shift, we're done.
673   if (!Shift) return Result;
674
675   // Shift for next step if the upper 32-bits were not zero.
676   if (Imm) {
677     Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
678                                     SDValue(Result, 0),
679                                     getI32Imm(Shift),
680                                     getI32Imm(63 - Shift));
681   }
682
683   // Add in the last bits as required.
684   if ((Hi = (Remainder >> 16) & 0xFFFF)) {
685     Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
686                                     SDValue(Result, 0), getI32Imm(Hi));
687   }
688   if ((Lo = Remainder & 0xFFFF)) {
689     Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
690                                     SDValue(Result, 0), getI32Imm(Lo));
691   }
692
693   return Result;
694 }
695
696 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
697   unsigned Count = SelectInt64CountDirect(Imm);
698   unsigned RMin = 0;
699
700   for (unsigned r = 1; r < 63; ++r) {
701     unsigned RCount = SelectInt64CountDirect(Rot64(Imm, r)) + 1;
702     if (RCount < Count) {
703       Count = RCount;
704       RMin = r;
705     }
706   }
707
708   if (!RMin)
709     return SelectInt64Direct(CurDAG, dl, Imm);
710
711   auto getI32Imm = [CurDAG](unsigned Imm) {
712       return CurDAG->getTargetConstant(Imm, MVT::i32);
713   };
714
715   SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, Rot64(Imm, RMin)), 0);
716   return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Val,
717                                 getI32Imm(64 - RMin), getI32Imm(0));
718 }
719
720 // Select a 64-bit constant.
721 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
722   SDLoc dl(N);
723
724   // Get 64 bit value.
725   int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
726   return SelectInt64(CurDAG, dl, Imm);
727 }
728
729 namespace {
730 class BitPermutationSelector {
731   struct ValueBit {
732     SDValue V;
733
734     // The bit number in the value, using a convention where bit 0 is the
735     // lowest-order bit.
736     unsigned Idx;
737
738     enum Kind {
739       ConstZero,
740       Variable
741     } K;
742
743     ValueBit(SDValue V, unsigned I, Kind K = Variable)
744       : V(V), Idx(I), K(K) {}
745     ValueBit(Kind K = Variable)
746       : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
747
748     bool isZero() const {
749       return K == ConstZero;
750     }
751
752     bool hasValue() const {
753       return K == Variable;
754     }
755
756     SDValue getValue() const {
757       assert(hasValue() && "Cannot get the value of a constant bit");
758       return V;
759     }
760
761     unsigned getValueBitIndex() const {
762       assert(hasValue() && "Cannot get the value bit index of a constant bit");
763       return Idx;
764     }
765   };
766
767   // A bit group has the same underlying value and the same rotate factor.
768   struct BitGroup {
769     SDValue V;
770     unsigned RLAmt;
771     unsigned StartIdx, EndIdx;
772
773     // This rotation amount assumes that the lower 32 bits of the quantity are
774     // replicated in the high 32 bits by the rotation operator (which is done
775     // by rlwinm and friends in 64-bit mode).
776     bool Repl32;
777     // Did converting to Repl32 == true change the rotation factor? If it did,
778     // it decreased it by 32.
779     bool Repl32CR;
780     // Was this group coalesced after setting Repl32 to true?
781     bool Repl32Coalesced;
782
783     BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
784       : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
785         Repl32Coalesced(false) {
786       DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
787                       " [" << S << ", " << E << "]\n");
788     }
789   };
790
791   // Information on each (Value, RLAmt) pair (like the number of groups
792   // associated with each) used to choose the lowering method.
793   struct ValueRotInfo {
794     SDValue V;
795     unsigned RLAmt;
796     unsigned NumGroups;
797     unsigned FirstGroupStartIdx;
798     bool Repl32;
799
800     ValueRotInfo()
801       : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
802         Repl32(false) {}
803
804     // For sorting (in reverse order) by NumGroups, and then by
805     // FirstGroupStartIdx.
806     bool operator < (const ValueRotInfo &Other) const {
807       // We need to sort so that the non-Repl32 come first because, when we're
808       // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
809       // masking operation.
810       if (Repl32 < Other.Repl32)
811         return true;
812       else if (Repl32 > Other.Repl32)
813         return false;
814       else if (NumGroups > Other.NumGroups)
815         return true;
816       else if (NumGroups < Other.NumGroups)
817         return false;
818       else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
819         return true;
820       return false;
821     }
822   };
823
824   // Return true if something interesting was deduced, return false if we're
825   // providing only a generic representation of V (or something else likewise
826   // uninteresting for instruction selection).
827   bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
828     switch (V.getOpcode()) {
829     default: break;
830     case ISD::ROTL:
831       if (isa<ConstantSDNode>(V.getOperand(1))) {
832         unsigned RotAmt = V.getConstantOperandVal(1);
833
834         SmallVector<ValueBit, 64> LHSBits(Bits.size());
835         getValueBits(V.getOperand(0), LHSBits);
836
837         for (unsigned i = 0; i < Bits.size(); ++i)
838           Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
839
840         return true;
841       }
842       break;
843     case ISD::SHL:
844       if (isa<ConstantSDNode>(V.getOperand(1))) {
845         unsigned ShiftAmt = V.getConstantOperandVal(1);
846
847         SmallVector<ValueBit, 64> LHSBits(Bits.size());
848         getValueBits(V.getOperand(0), LHSBits);
849
850         for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
851           Bits[i] = LHSBits[i - ShiftAmt];
852
853         for (unsigned i = 0; i < ShiftAmt; ++i)
854           Bits[i] = ValueBit(ValueBit::ConstZero);
855
856         return true;
857       }
858       break;
859     case ISD::SRL:
860       if (isa<ConstantSDNode>(V.getOperand(1))) {
861         unsigned ShiftAmt = V.getConstantOperandVal(1);
862
863         SmallVector<ValueBit, 64> LHSBits(Bits.size());
864         getValueBits(V.getOperand(0), LHSBits);
865
866         for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
867           Bits[i] = LHSBits[i + ShiftAmt];
868
869         for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
870           Bits[i] = ValueBit(ValueBit::ConstZero);
871
872         return true;
873       }
874       break;
875     case ISD::AND:
876       if (isa<ConstantSDNode>(V.getOperand(1))) {
877         uint64_t Mask = V.getConstantOperandVal(1);
878
879         SmallVector<ValueBit, 64> LHSBits(Bits.size());
880         bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
881
882         for (unsigned i = 0; i < Bits.size(); ++i)
883           if (((Mask >> i) & 1) == 1)
884             Bits[i] = LHSBits[i];
885           else
886             Bits[i] = ValueBit(ValueBit::ConstZero);
887
888         // Mark this as interesting, only if the LHS was also interesting. This
889         // prevents the overall procedure from matching a single immediate 'and'
890         // (which is non-optimal because such an and might be folded with other
891         // things if we don't select it here).
892         return LHSTrivial;
893       }
894       break;
895     case ISD::OR: {
896       SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
897       getValueBits(V.getOperand(0), LHSBits);
898       getValueBits(V.getOperand(1), RHSBits);
899
900       bool AllDisjoint = true;
901       for (unsigned i = 0; i < Bits.size(); ++i)
902         if (LHSBits[i].isZero())
903           Bits[i] = RHSBits[i];
904         else if (RHSBits[i].isZero())
905           Bits[i] = LHSBits[i];
906         else {
907           AllDisjoint = false;
908           break;
909         }
910
911       if (!AllDisjoint)
912         break;
913
914       return true;
915     }
916     }
917
918     for (unsigned i = 0; i < Bits.size(); ++i)
919       Bits[i] = ValueBit(V, i);
920
921     return false;
922   }
923
924   // For each value (except the constant ones), compute the left-rotate amount
925   // to get it from its original to final position.
926   void computeRotationAmounts() {
927     HasZeros = false;
928     RLAmt.resize(Bits.size());
929     for (unsigned i = 0; i < Bits.size(); ++i)
930       if (Bits[i].hasValue()) {
931         unsigned VBI = Bits[i].getValueBitIndex();
932         if (i >= VBI)
933           RLAmt[i] = i - VBI;
934         else
935           RLAmt[i] = Bits.size() - (VBI - i);
936       } else if (Bits[i].isZero()) {
937         HasZeros = true;
938         RLAmt[i] = UINT32_MAX;
939       } else {
940         llvm_unreachable("Unknown value bit type");
941       }
942   }
943
944   // Collect groups of consecutive bits with the same underlying value and
945   // rotation factor. If we're doing late masking, we ignore zeros, otherwise
946   // they break up groups.
947   void collectBitGroups(bool LateMask) {
948     BitGroups.clear();
949
950     unsigned LastRLAmt = RLAmt[0];
951     SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
952     unsigned LastGroupStartIdx = 0;
953     for (unsigned i = 1; i < Bits.size(); ++i) {
954       unsigned ThisRLAmt = RLAmt[i];
955       SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
956       if (LateMask && !ThisValue) {
957         ThisValue = LastValue;
958         ThisRLAmt = LastRLAmt;
959         // If we're doing late masking, then the first bit group always starts
960         // at zero (even if the first bits were zero).
961         if (BitGroups.empty())
962           LastGroupStartIdx = 0;
963       }
964
965       // If this bit has the same underlying value and the same rotate factor as
966       // the last one, then they're part of the same group.
967       if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
968         continue;
969
970       if (LastValue.getNode())
971         BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
972                                      i-1));
973       LastRLAmt = ThisRLAmt;
974       LastValue = ThisValue;
975       LastGroupStartIdx = i;
976     }
977     if (LastValue.getNode())
978       BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
979                                    Bits.size()-1));
980
981     if (BitGroups.empty())
982       return;
983
984     // We might be able to combine the first and last groups.
985     if (BitGroups.size() > 1) {
986       // If the first and last groups are the same, then remove the first group
987       // in favor of the last group, making the ending index of the last group
988       // equal to the ending index of the to-be-removed first group.
989       if (BitGroups[0].StartIdx == 0 &&
990           BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
991           BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
992           BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
993         DEBUG(dbgs() << "\tcombining final bit group with inital one\n");
994         BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
995         BitGroups.erase(BitGroups.begin());
996       }
997     }
998   }
999
1000   // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1001   // associated with each. If there is a degeneracy, pick the one that occurs
1002   // first (in the final value).
1003   void collectValueRotInfo() {
1004     ValueRots.clear();
1005
1006     for (auto &BG : BitGroups) {
1007       unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1008       ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1009       VRI.V = BG.V;
1010       VRI.RLAmt = BG.RLAmt;
1011       VRI.Repl32 = BG.Repl32;
1012       VRI.NumGroups += 1;
1013       VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1014     }
1015
1016     // Now that we've collected the various ValueRotInfo instances, we need to
1017     // sort them.
1018     ValueRotsVec.clear();
1019     for (auto &I : ValueRots) {
1020       ValueRotsVec.push_back(I.second);
1021     }
1022     std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1023   }
1024
1025   // In 64-bit mode, rlwinm and friends have a rotation operator that
1026   // replicates the low-order 32 bits into the high-order 32-bits. The mask
1027   // indices of these instructions can only be in the lower 32 bits, so they
1028   // can only represent some 64-bit bit groups. However, when they can be used,
1029   // the 32-bit replication can be used to represent, as a single bit group,
1030   // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1031   // groups when possible. Returns true if any of the bit groups were
1032   // converted.
1033   void assignRepl32BitGroups() {
1034     // If we have bits like this:
1035     //
1036     // Indices:    15 14 13 12 11 10 9 8  7  6  5  4  3  2  1  0
1037     // V bits: ... 7  6  5  4  3  2  1 0 31 30 29 28 27 26 25 24
1038     // Groups:    |      RLAmt = 8      |      RLAmt = 40       |
1039     //
1040     // But, making use of a 32-bit operation that replicates the low-order 32
1041     // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1042     // of 8.
1043
1044     auto IsAllLow32 = [this](BitGroup & BG) {
1045       if (BG.StartIdx <= BG.EndIdx) {
1046         for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1047           if (!Bits[i].hasValue())
1048             continue;
1049           if (Bits[i].getValueBitIndex() >= 32)
1050             return false;
1051         }
1052       } else {
1053         for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1054           if (!Bits[i].hasValue())
1055             continue;
1056           if (Bits[i].getValueBitIndex() >= 32)
1057             return false;
1058         }
1059         for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1060           if (!Bits[i].hasValue())
1061             continue;
1062           if (Bits[i].getValueBitIndex() >= 32)
1063             return false;
1064         }
1065       }
1066
1067       return true;
1068     };
1069
1070     for (auto &BG : BitGroups) {
1071       if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1072         if (IsAllLow32(BG)) {
1073           if (BG.RLAmt >= 32) {
1074             BG.RLAmt -= 32;
1075             BG.Repl32CR = true;
1076           }
1077
1078           BG.Repl32 = true;
1079
1080           DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1081                           BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1082                           " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1083         }
1084       }
1085     }
1086
1087     // Now walk through the bit groups, consolidating where possible.
1088     for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1089       // We might want to remove this bit group by merging it with the previous
1090       // group (which might be the ending group).
1091       auto IP = (I == BitGroups.begin()) ?
1092                 std::prev(BitGroups.end()) : std::prev(I);
1093       if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1094           I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1095
1096         DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1097                         I->V.getNode() << " RLAmt = " << I->RLAmt <<
1098                         " [" << I->StartIdx << ", " << I->EndIdx <<
1099                         "] with group with range [" <<
1100                         IP->StartIdx << ", " << IP->EndIdx << "]\n");
1101
1102         IP->EndIdx = I->EndIdx;
1103         IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1104         IP->Repl32Coalesced = true;
1105         I = BitGroups.erase(I);
1106         continue;
1107       } else {
1108         // There is a special case worth handling: If there is a single group
1109         // covering the entire upper 32 bits, and it can be merged with both
1110         // the next and previous groups (which might be the same group), then
1111         // do so. If it is the same group (so there will be only one group in
1112         // total), then we need to reverse the order of the range so that it
1113         // covers the entire 64 bits.
1114         if (I->StartIdx == 32 && I->EndIdx == 63) {
1115           assert(std::next(I) == BitGroups.end() &&
1116                  "bit group ends at index 63 but there is another?");
1117           auto IN = BitGroups.begin();
1118
1119           if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V && 
1120               (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1121               IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1122               IsAllLow32(*I)) {
1123
1124             DEBUG(dbgs() << "\tcombining bit group for " <<
1125                             I->V.getNode() << " RLAmt = " << I->RLAmt <<
1126                             " [" << I->StartIdx << ", " << I->EndIdx <<
1127                             "] with 32-bit replicated groups with ranges [" <<
1128                             IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1129                             IN->StartIdx << ", " << IN->EndIdx << "]\n");
1130
1131             if (IP == IN) {
1132               // There is only one other group; change it to cover the whole
1133               // range (backward, so that it can still be Repl32 but cover the
1134               // whole 64-bit range).
1135               IP->StartIdx = 31;
1136               IP->EndIdx = 30;
1137               IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1138               IP->Repl32Coalesced = true;
1139               I = BitGroups.erase(I);
1140             } else {
1141               // There are two separate groups, one before this group and one
1142               // after us (at the beginning). We're going to remove this group,
1143               // but also the group at the very beginning.
1144               IP->EndIdx = IN->EndIdx;
1145               IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1146               IP->Repl32Coalesced = true;
1147               I = BitGroups.erase(I);
1148               BitGroups.erase(BitGroups.begin());
1149             }
1150
1151             // This must be the last group in the vector (and we might have
1152             // just invalidated the iterator above), so break here.
1153             break;
1154           }
1155         }
1156       }
1157
1158       ++I;
1159     }
1160   }
1161
1162   SDValue getI32Imm(unsigned Imm) {
1163     return CurDAG->getTargetConstant(Imm, MVT::i32);
1164   }
1165
1166   uint64_t getZerosMask() {
1167     uint64_t Mask = 0;
1168     for (unsigned i = 0; i < Bits.size(); ++i) {
1169       if (Bits[i].hasValue())
1170         continue;
1171       Mask |= (UINT64_C(1) << i);
1172     }
1173
1174     return ~Mask;
1175   }
1176
1177   // Depending on the number of groups for a particular value, it might be
1178   // better to rotate, mask explicitly (using andi/andis), and then or the
1179   // result. Select this part of the result first.
1180   void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1181     if (BPermRewriterNoMasking)
1182       return;
1183
1184     for (ValueRotInfo &VRI : ValueRotsVec) {
1185       unsigned Mask = 0;
1186       for (unsigned i = 0; i < Bits.size(); ++i) {
1187         if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1188           continue;
1189         if (RLAmt[i] != VRI.RLAmt)
1190           continue;
1191         Mask |= (1u << i);
1192       }
1193
1194       // Compute the masks for andi/andis that would be necessary.
1195       unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1196       assert((ANDIMask != 0 || ANDISMask != 0) &&
1197              "No set bits in mask for value bit groups");
1198       bool NeedsRotate = VRI.RLAmt != 0;
1199
1200       // We're trying to minimize the number of instructions. If we have one
1201       // group, using one of andi/andis can break even.  If we have three
1202       // groups, we can use both andi and andis and break even (to use both
1203       // andi and andis we also need to or the results together). We need four
1204       // groups if we also need to rotate. To use andi/andis we need to do more
1205       // than break even because rotate-and-mask instructions tend to be easier
1206       // to schedule.
1207
1208       // FIXME: We've biased here against using andi/andis, which is right for
1209       // POWER cores, but not optimal everywhere. For example, on the A2,
1210       // andi/andis have single-cycle latency whereas the rotate-and-mask
1211       // instructions take two cycles, and it would be better to bias toward
1212       // andi/andis in break-even cases.
1213
1214       unsigned NumAndInsts = (unsigned) NeedsRotate +
1215                              (unsigned) (ANDIMask != 0) +
1216                              (unsigned) (ANDISMask != 0) +
1217                              (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1218                              (unsigned) (bool) Res;
1219
1220       DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1221                       " RL: " << VRI.RLAmt << ":" <<
1222                       "\n\t\t\tisel using masking: " << NumAndInsts <<
1223                       " using rotates: " << VRI.NumGroups << "\n");
1224
1225       if (NumAndInsts >= VRI.NumGroups)
1226         continue;
1227
1228       DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1229
1230       if (InstCnt) *InstCnt += NumAndInsts;
1231
1232       SDValue VRot;
1233       if (VRI.RLAmt) {
1234         SDValue Ops[] =
1235           { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1236         VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1237                                               Ops), 0);
1238       } else {
1239         VRot = VRI.V;
1240       }
1241
1242       SDValue ANDIVal, ANDISVal;
1243       if (ANDIMask != 0)
1244         ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1245                             VRot, getI32Imm(ANDIMask)), 0);
1246       if (ANDISMask != 0)
1247         ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1248                              VRot, getI32Imm(ANDISMask)), 0);
1249
1250       SDValue TotalVal;
1251       if (!ANDIVal)
1252         TotalVal = ANDISVal;
1253       else if (!ANDISVal)
1254         TotalVal = ANDIVal;
1255       else
1256         TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1257                              ANDIVal, ANDISVal), 0);
1258
1259       if (!Res)
1260         Res = TotalVal;
1261       else
1262         Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1263                         Res, TotalVal), 0);
1264
1265       // Now, remove all groups with this underlying value and rotation
1266       // factor.
1267       for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1268         if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1269           I = BitGroups.erase(I);
1270         else
1271           ++I;
1272       }
1273     }
1274   }
1275
1276   // Instruction selection for the 32-bit case.
1277   SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1278     SDLoc dl(N);
1279     SDValue Res;
1280
1281     if (InstCnt) *InstCnt = 0;
1282
1283     // Take care of cases that should use andi/andis first.
1284     SelectAndParts32(dl, Res, InstCnt);
1285
1286     // If we've not yet selected a 'starting' instruction, and we have no zeros
1287     // to fill in, select the (Value, RLAmt) with the highest priority (largest
1288     // number of groups), and start with this rotated value.
1289     if ((!HasZeros || LateMask) && !Res) {
1290       ValueRotInfo &VRI = ValueRotsVec[0];
1291       if (VRI.RLAmt) {
1292         if (InstCnt) *InstCnt += 1;
1293         SDValue Ops[] =
1294           { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1295         Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1296       } else {
1297         Res = VRI.V;
1298       }
1299
1300       // Now, remove all groups with this underlying value and rotation factor.
1301       for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1302         if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1303           I = BitGroups.erase(I);
1304         else
1305           ++I;
1306       }
1307     }
1308
1309     if (InstCnt) *InstCnt += BitGroups.size();
1310
1311     // Insert the other groups (one at a time).
1312     for (auto &BG : BitGroups) {
1313       if (!Res) {
1314         SDValue Ops[] =
1315           { BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1316             getI32Imm(Bits.size() - BG.StartIdx - 1) };
1317         Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1318       } else {
1319         SDValue Ops[] =
1320           { Res, BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1321             getI32Imm(Bits.size() - BG.StartIdx - 1) };
1322         Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1323       }
1324     }
1325
1326     if (LateMask) {
1327       unsigned Mask = (unsigned) getZerosMask();
1328
1329       unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1330       assert((ANDIMask != 0 || ANDISMask != 0) &&
1331              "No set bits in zeros mask?");
1332
1333       if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1334                                (unsigned) (ANDISMask != 0) +
1335                                (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1336
1337       SDValue ANDIVal, ANDISVal;
1338       if (ANDIMask != 0)
1339         ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1340                             Res, getI32Imm(ANDIMask)), 0);
1341       if (ANDISMask != 0)
1342         ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1343                              Res, getI32Imm(ANDISMask)), 0);
1344
1345       if (!ANDIVal)
1346         Res = ANDISVal;
1347       else if (!ANDISVal)
1348         Res = ANDIVal;
1349       else
1350         Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1351                         ANDIVal, ANDISVal), 0);
1352     }
1353
1354     return Res.getNode();
1355   }
1356
1357   unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1358                                 unsigned MaskStart, unsigned MaskEnd,
1359                                 bool IsIns) {
1360     // In the notation used by the instructions, 'start' and 'end' are reversed
1361     // because bits are counted from high to low order.
1362     unsigned InstMaskStart = 64 - MaskEnd - 1,
1363              InstMaskEnd   = 64 - MaskStart - 1;
1364
1365     if (Repl32)
1366       return 1;
1367
1368     if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1369         InstMaskEnd == 63 - RLAmt)
1370       return 1;
1371
1372     return 2;
1373   }
1374
1375   // For 64-bit values, not all combinations of rotates and masks are
1376   // available. Produce one if it is available.
1377   SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1378                           unsigned MaskStart, unsigned MaskEnd,
1379                           unsigned *InstCnt = nullptr) {
1380     // In the notation used by the instructions, 'start' and 'end' are reversed
1381     // because bits are counted from high to low order.
1382     unsigned InstMaskStart = 64 - MaskEnd - 1,
1383              InstMaskEnd   = 64 - MaskStart - 1;
1384
1385     if (InstCnt) *InstCnt += 1;
1386
1387     if (Repl32) {
1388       // This rotation amount assumes that the lower 32 bits of the quantity
1389       // are replicated in the high 32 bits by the rotation operator (which is
1390       // done by rlwinm and friends).
1391       assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1392       assert(InstMaskEnd   >= 32 && "Mask cannot end out of range");
1393       SDValue Ops[] =
1394         { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1395           getI32Imm(InstMaskEnd - 32) };
1396       return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1397                                             Ops), 0);
1398     }
1399
1400     if (InstMaskEnd == 63) {
1401       SDValue Ops[] =
1402         { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1403       return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1404     }
1405
1406     if (InstMaskStart == 0) {
1407       SDValue Ops[] =
1408         { V, getI32Imm(RLAmt), getI32Imm(InstMaskEnd) };
1409       return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1410     }
1411
1412     if (InstMaskEnd == 63 - RLAmt) {
1413       SDValue Ops[] =
1414         { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1415       return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1416     }
1417
1418     // We cannot do this with a single instruction, so we'll use two. The
1419     // problem is that we're not free to choose both a rotation amount and mask
1420     // start and end independently. We can choose an arbitrary mask start and
1421     // end, but then the rotation amount is fixed. Rotation, however, can be
1422     // inverted, and so by applying an "inverse" rotation first, we can get the
1423     // desired result.
1424     if (InstCnt) *InstCnt += 1;
1425
1426     // The rotation mask for the second instruction must be MaskStart.
1427     unsigned RLAmt2 = MaskStart;
1428     // The first instruction must rotate V so that the overall rotation amount
1429     // is RLAmt.
1430     unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1431     if (RLAmt1)
1432       V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1433     return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1434   }
1435
1436   // For 64-bit values, not all combinations of rotates and masks are
1437   // available. Produce a rotate-mask-and-insert if one is available.
1438   SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1439                              bool Repl32, unsigned MaskStart,
1440                              unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1441     // In the notation used by the instructions, 'start' and 'end' are reversed
1442     // because bits are counted from high to low order.
1443     unsigned InstMaskStart = 64 - MaskEnd - 1,
1444              InstMaskEnd   = 64 - MaskStart - 1;
1445
1446     if (InstCnt) *InstCnt += 1;
1447
1448     if (Repl32) {
1449       // This rotation amount assumes that the lower 32 bits of the quantity
1450       // are replicated in the high 32 bits by the rotation operator (which is
1451       // done by rlwinm and friends).
1452       assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1453       assert(InstMaskEnd   >= 32 && "Mask cannot end out of range");
1454       SDValue Ops[] =
1455         { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1456           getI32Imm(InstMaskEnd - 32) };
1457       return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1458                                             Ops), 0);
1459     }
1460
1461     if (InstMaskEnd == 63 - RLAmt) {
1462       SDValue Ops[] =
1463         { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1464       return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1465     }
1466
1467     // We cannot do this with a single instruction, so we'll use two. The
1468     // problem is that we're not free to choose both a rotation amount and mask
1469     // start and end independently. We can choose an arbitrary mask start and
1470     // end, but then the rotation amount is fixed. Rotation, however, can be
1471     // inverted, and so by applying an "inverse" rotation first, we can get the
1472     // desired result.
1473     if (InstCnt) *InstCnt += 1;
1474
1475     // The rotation mask for the second instruction must be MaskStart.
1476     unsigned RLAmt2 = MaskStart;
1477     // The first instruction must rotate V so that the overall rotation amount
1478     // is RLAmt.
1479     unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1480     if (RLAmt1)
1481       V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1482     return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1483   }
1484
1485   void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1486     if (BPermRewriterNoMasking)
1487       return;
1488
1489     // The idea here is the same as in the 32-bit version, but with additional
1490     // complications from the fact that Repl32 might be true. Because we
1491     // aggressively convert bit groups to Repl32 form (which, for small
1492     // rotation factors, involves no other change), and then coalesce, it might
1493     // be the case that a single 64-bit masking operation could handle both
1494     // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1495     // form allowed coalescing, then we must use a 32-bit rotaton in order to
1496     // completely capture the new combined bit group.
1497
1498     for (ValueRotInfo &VRI : ValueRotsVec) {
1499       uint64_t Mask = 0;
1500
1501       // We need to add to the mask all bits from the associated bit groups.
1502       // If Repl32 is false, we need to add bits from bit groups that have
1503       // Repl32 true, but are trivially convertable to Repl32 false. Such a
1504       // group is trivially convertable if it overlaps only with the lower 32
1505       // bits, and the group has not been coalesced.
1506       auto MatchingBG = [VRI](BitGroup &BG) {
1507         if (VRI.V != BG.V)
1508           return false;
1509
1510         unsigned EffRLAmt = BG.RLAmt;
1511         if (!VRI.Repl32 && BG.Repl32) {
1512           if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1513               !BG.Repl32Coalesced) {
1514             if (BG.Repl32CR)
1515               EffRLAmt += 32;
1516           } else {
1517             return false;
1518           }
1519         } else if (VRI.Repl32 != BG.Repl32) {
1520           return false;
1521         }
1522
1523         if (VRI.RLAmt != EffRLAmt)
1524           return false;
1525
1526         return true;
1527       };
1528
1529       for (auto &BG : BitGroups) {
1530         if (!MatchingBG(BG))
1531           continue;
1532
1533         if (BG.StartIdx <= BG.EndIdx) {
1534           for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1535             Mask |= (UINT64_C(1) << i);
1536         } else {
1537           for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1538             Mask |= (UINT64_C(1) << i);
1539           for (unsigned i = 0; i <= BG.EndIdx; ++i)
1540             Mask |= (UINT64_C(1) << i);
1541         }
1542       }
1543
1544       // We can use the 32-bit andi/andis technique if the mask does not
1545       // require any higher-order bits. This can save an instruction compared
1546       // to always using the general 64-bit technique.
1547       bool Use32BitInsts = isUInt<32>(Mask);
1548       // Compute the masks for andi/andis that would be necessary.
1549       unsigned ANDIMask = (Mask & UINT16_MAX),
1550                ANDISMask = (Mask >> 16) & UINT16_MAX;
1551
1552       bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1553
1554       unsigned NumAndInsts = (unsigned) NeedsRotate +
1555                              (unsigned) (bool) Res;
1556       if (Use32BitInsts)
1557         NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1558                        (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1559       else
1560         NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1561
1562       unsigned NumRLInsts = 0;
1563       bool FirstBG = true;
1564       for (auto &BG : BitGroups) {
1565         if (!MatchingBG(BG))
1566           continue;
1567         NumRLInsts +=
1568           SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1569                                !FirstBG);
1570         FirstBG = false;
1571       }
1572
1573       DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1574                       " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1575                       "\n\t\t\tisel using masking: " << NumAndInsts <<
1576                       " using rotates: " << NumRLInsts << "\n");
1577
1578       // When we'd use andi/andis, we bias toward using the rotates (andi only
1579       // has a record form, and is cracked on POWER cores). However, when using
1580       // general 64-bit constant formation, bias toward the constant form,
1581       // because that exposes more opportunities for CSE.
1582       if (NumAndInsts > NumRLInsts)
1583         continue;
1584       if (Use32BitInsts && NumAndInsts == NumRLInsts)
1585         continue;
1586
1587       DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1588
1589       if (InstCnt) *InstCnt += NumAndInsts;
1590
1591       SDValue VRot;
1592       // We actually need to generate a rotation if we have a non-zero rotation
1593       // factor or, in the Repl32 case, if we care about any of the
1594       // higher-order replicated bits. In the latter case, we generate a mask
1595       // backward so that it actually includes the entire 64 bits.
1596       if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1597         VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1598                                VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1599       else
1600         VRot = VRI.V;
1601
1602       SDValue TotalVal;
1603       if (Use32BitInsts) {
1604         assert((ANDIMask != 0 || ANDISMask != 0) &&
1605                "No set bits in mask when using 32-bit ands for 64-bit value");
1606
1607         SDValue ANDIVal, ANDISVal;
1608         if (ANDIMask != 0)
1609           ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1610                               VRot, getI32Imm(ANDIMask)), 0);
1611         if (ANDISMask != 0)
1612           ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1613                                VRot, getI32Imm(ANDISMask)), 0);
1614
1615         if (!ANDIVal)
1616           TotalVal = ANDISVal;
1617         else if (!ANDISVal)
1618           TotalVal = ANDIVal;
1619         else
1620           TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1621                                ANDIVal, ANDISVal), 0);
1622       } else {
1623         TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1624         TotalVal =
1625           SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1626                                          VRot, TotalVal), 0);
1627      }
1628
1629       if (!Res)
1630         Res = TotalVal;
1631       else
1632         Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1633                                              Res, TotalVal), 0);
1634
1635       // Now, remove all groups with this underlying value and rotation
1636       // factor.
1637       for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1638         if (MatchingBG(*I))
1639           I = BitGroups.erase(I);
1640         else
1641           ++I;
1642       }
1643     }
1644   }
1645
1646   // Instruction selection for the 64-bit case.
1647   SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1648     SDLoc dl(N);
1649     SDValue Res;
1650
1651     if (InstCnt) *InstCnt = 0;
1652
1653     // Take care of cases that should use andi/andis first.
1654     SelectAndParts64(dl, Res, InstCnt);
1655
1656     // If we've not yet selected a 'starting' instruction, and we have no zeros
1657     // to fill in, select the (Value, RLAmt) with the highest priority (largest
1658     // number of groups), and start with this rotated value.
1659     if ((!HasZeros || LateMask) && !Res) {
1660       // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1661       // groups will come first, and so the VRI representing the largest number
1662       // of groups might not be first (it might be the first Repl32 groups).
1663       unsigned MaxGroupsIdx = 0;
1664       if (!ValueRotsVec[0].Repl32) {
1665         for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1666           if (ValueRotsVec[i].Repl32) {
1667             if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1668               MaxGroupsIdx = i;
1669             break;
1670           }
1671       }
1672
1673       ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1674       bool NeedsRotate = false;
1675       if (VRI.RLAmt) {
1676         NeedsRotate = true;
1677       } else if (VRI.Repl32) {
1678         for (auto &BG : BitGroups) {
1679           if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1680               BG.Repl32 != VRI.Repl32)
1681             continue;
1682
1683           // We don't need a rotate if the bit group is confined to the lower
1684           // 32 bits.
1685           if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1686             continue;
1687
1688           NeedsRotate = true;
1689           break;
1690         }
1691       }
1692
1693       if (NeedsRotate)
1694         Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1695                               VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1696                               InstCnt);
1697       else
1698         Res = VRI.V;
1699
1700       // Now, remove all groups with this underlying value and rotation factor.
1701       if (Res)
1702         for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1703           if (I->V == VRI.V && I->RLAmt == VRI.RLAmt && I->Repl32 == VRI.Repl32)
1704             I = BitGroups.erase(I);
1705           else
1706             ++I;
1707         }
1708     }
1709
1710     // Because 64-bit rotates are more flexible than inserts, we might have a
1711     // preference regarding which one we do first (to save one instruction).
1712     if (!Res)
1713       for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1714         if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1715                                 false) <
1716             SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1717                                 true)) {
1718           if (I != BitGroups.begin()) {
1719             BitGroup BG = *I;
1720             BitGroups.erase(I);
1721             BitGroups.insert(BitGroups.begin(), BG);
1722           }
1723
1724           break;
1725         }
1726       }
1727
1728     // Insert the other groups (one at a time).
1729     for (auto &BG : BitGroups) {
1730       if (!Res)
1731         Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1732                               BG.EndIdx, InstCnt);
1733       else
1734         Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1735                                  BG.StartIdx, BG.EndIdx, InstCnt);
1736     }
1737
1738     if (LateMask) {
1739       uint64_t Mask = getZerosMask();
1740
1741       // We can use the 32-bit andi/andis technique if the mask does not
1742       // require any higher-order bits. This can save an instruction compared
1743       // to always using the general 64-bit technique.
1744       bool Use32BitInsts = isUInt<32>(Mask);
1745       // Compute the masks for andi/andis that would be necessary.
1746       unsigned ANDIMask = (Mask & UINT16_MAX),
1747                ANDISMask = (Mask >> 16) & UINT16_MAX;
1748
1749       if (Use32BitInsts) {
1750         assert((ANDIMask != 0 || ANDISMask != 0) &&
1751                "No set bits in mask when using 32-bit ands for 64-bit value");
1752
1753         if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1754                                  (unsigned) (ANDISMask != 0) +
1755                                  (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1756
1757         SDValue ANDIVal, ANDISVal;
1758         if (ANDIMask != 0)
1759           ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1760                               Res, getI32Imm(ANDIMask)), 0);
1761         if (ANDISMask != 0)
1762           ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1763                                Res, getI32Imm(ANDISMask)), 0);
1764
1765         if (!ANDIVal)
1766           Res = ANDISVal;
1767         else if (!ANDISVal)
1768           Res = ANDIVal;
1769         else
1770           Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1771                           ANDIVal, ANDISVal), 0);
1772       } else {
1773         if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1774
1775         SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1776         Res =
1777           SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1778                                          Res, MaskVal), 0);
1779       }
1780     }
1781
1782     return Res.getNode();
1783   }
1784
1785   SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1786     // Fill in BitGroups.
1787     collectBitGroups(LateMask);
1788     if (BitGroups.empty())
1789       return nullptr;
1790
1791     // For 64-bit values, figure out when we can use 32-bit instructions.
1792     if (Bits.size() == 64)
1793       assignRepl32BitGroups();
1794
1795     // Fill in ValueRotsVec.
1796     collectValueRotInfo();
1797
1798     if (Bits.size() == 32) {
1799       return Select32(N, LateMask, InstCnt);
1800     } else {
1801       assert(Bits.size() == 64 && "Not 64 bits here?");
1802       return Select64(N, LateMask, InstCnt);
1803     }
1804
1805     return nullptr;
1806   }
1807
1808   SmallVector<ValueBit, 64> Bits;
1809
1810   bool HasZeros;
1811   SmallVector<unsigned, 64> RLAmt;
1812
1813   SmallVector<BitGroup, 16> BitGroups;
1814
1815   DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1816   SmallVector<ValueRotInfo, 16> ValueRotsVec;
1817
1818   SelectionDAG *CurDAG;
1819
1820 public:
1821   BitPermutationSelector(SelectionDAG *DAG)
1822     : CurDAG(DAG) {}
1823
1824   // Here we try to match complex bit permutations into a set of
1825   // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1826   // known to produce optimial code for common cases (like i32 byte swapping).
1827   SDNode *Select(SDNode *N) {
1828     Bits.resize(N->getValueType(0).getSizeInBits());
1829     if (!getValueBits(SDValue(N, 0), Bits))
1830       return nullptr;
1831
1832     DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1833                     " selection for:    ");
1834     DEBUG(N->dump(CurDAG));
1835
1836     // Fill it RLAmt and set HasZeros.
1837     computeRotationAmounts();
1838
1839     if (!HasZeros)
1840       return Select(N, false);
1841
1842     // We currently have two techniques for handling results with zeros: early
1843     // masking (the default) and late masking. Late masking is sometimes more
1844     // efficient, but because the structure of the bit groups is different, it
1845     // is hard to tell without generating both and comparing the results. With
1846     // late masking, we ignore zeros in the resulting value when inserting each
1847     // set of bit groups, and then mask in the zeros at the end. With early
1848     // masking, we only insert the non-zero parts of the result at every step.
1849
1850     unsigned InstCnt, InstCntLateMask;
1851     DEBUG(dbgs() << "\tEarly masking:\n");
1852     SDNode *RN = Select(N, false, &InstCnt);
1853     DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1854
1855     DEBUG(dbgs() << "\tLate masking:\n");
1856     SDNode *RNLM = Select(N, true, &InstCntLateMask);
1857     DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1858                     " instructions\n");
1859
1860     if (InstCnt <= InstCntLateMask) {
1861       DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1862       return RN;
1863     }
1864
1865     DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1866     return RNLM;
1867   }
1868 };
1869 } // anonymous namespace
1870
1871 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1872   if (N->getValueType(0) != MVT::i32 &&
1873       N->getValueType(0) != MVT::i64)
1874     return nullptr;
1875
1876   if (!UseBitPermRewriter)
1877     return nullptr;
1878
1879   switch (N->getOpcode()) {
1880   default: break;
1881   case ISD::ROTL:
1882   case ISD::SHL:
1883   case ISD::SRL:
1884   case ISD::AND:
1885   case ISD::OR: {
1886     BitPermutationSelector BPS(CurDAG);
1887     return BPS.Select(N);
1888   }
1889   }
1890
1891   return nullptr;
1892 }
1893
1894 /// SelectCC - Select a comparison of the specified values with the specified
1895 /// condition code, returning the CR# of the expression.
1896 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1897                                     ISD::CondCode CC, SDLoc dl) {
1898   // Always select the LHS.
1899   unsigned Opc;
1900
1901   if (LHS.getValueType() == MVT::i32) {
1902     unsigned Imm;
1903     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1904       if (isInt32Immediate(RHS, Imm)) {
1905         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1906         if (isUInt<16>(Imm))
1907           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1908                                                 getI32Imm(Imm & 0xFFFF)), 0);
1909         // If this is a 16-bit signed immediate, fold it.
1910         if (isInt<16>((int)Imm))
1911           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1912                                                 getI32Imm(Imm & 0xFFFF)), 0);
1913
1914         // For non-equality comparisons, the default code would materialize the
1915         // constant, then compare against it, like this:
1916         //   lis r2, 4660
1917         //   ori r2, r2, 22136
1918         //   cmpw cr0, r3, r2
1919         // Since we are just comparing for equality, we can emit this instead:
1920         //   xoris r0,r3,0x1234
1921         //   cmplwi cr0,r0,0x5678
1922         //   beq cr0,L6
1923         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
1924                                            getI32Imm(Imm >> 16)), 0);
1925         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1926                                               getI32Imm(Imm & 0xFFFF)), 0);
1927       }
1928       Opc = PPC::CMPLW;
1929     } else if (ISD::isUnsignedIntSetCC(CC)) {
1930       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
1931         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1932                                               getI32Imm(Imm & 0xFFFF)), 0);
1933       Opc = PPC::CMPLW;
1934     } else {
1935       short SImm;
1936       if (isIntS16Immediate(RHS, SImm))
1937         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1938                                               getI32Imm((int)SImm & 0xFFFF)),
1939                          0);
1940       Opc = PPC::CMPW;
1941     }
1942   } else if (LHS.getValueType() == MVT::i64) {
1943     uint64_t Imm;
1944     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1945       if (isInt64Immediate(RHS.getNode(), Imm)) {
1946         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1947         if (isUInt<16>(Imm))
1948           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
1949                                                 getI32Imm(Imm & 0xFFFF)), 0);
1950         // If this is a 16-bit signed immediate, fold it.
1951         if (isInt<16>(Imm))
1952           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1953                                                 getI32Imm(Imm & 0xFFFF)), 0);
1954
1955         // For non-equality comparisons, the default code would materialize the
1956         // constant, then compare against it, like this:
1957         //   lis r2, 4660
1958         //   ori r2, r2, 22136
1959         //   cmpd cr0, r3, r2
1960         // Since we are just comparing for equality, we can emit this instead:
1961         //   xoris r0,r3,0x1234
1962         //   cmpldi cr0,r0,0x5678
1963         //   beq cr0,L6
1964         if (isUInt<32>(Imm)) {
1965           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
1966                                              getI64Imm(Imm >> 16)), 0);
1967           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
1968                                                 getI64Imm(Imm & 0xFFFF)), 0);
1969         }
1970       }
1971       Opc = PPC::CMPLD;
1972     } else if (ISD::isUnsignedIntSetCC(CC)) {
1973       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
1974         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
1975                                               getI64Imm(Imm & 0xFFFF)), 0);
1976       Opc = PPC::CMPLD;
1977     } else {
1978       short SImm;
1979       if (isIntS16Immediate(RHS, SImm))
1980         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1981                                               getI64Imm(SImm & 0xFFFF)),
1982                          0);
1983       Opc = PPC::CMPD;
1984     }
1985   } else if (LHS.getValueType() == MVT::f32) {
1986     Opc = PPC::FCMPUS;
1987   } else {
1988     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
1989     Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
1990   }
1991   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
1992 }
1993
1994 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
1995   switch (CC) {
1996   case ISD::SETUEQ:
1997   case ISD::SETONE:
1998   case ISD::SETOLE:
1999   case ISD::SETOGE:
2000     llvm_unreachable("Should be lowered by legalize!");
2001   default: llvm_unreachable("Unknown condition!");
2002   case ISD::SETOEQ:
2003   case ISD::SETEQ:  return PPC::PRED_EQ;
2004   case ISD::SETUNE:
2005   case ISD::SETNE:  return PPC::PRED_NE;
2006   case ISD::SETOLT:
2007   case ISD::SETLT:  return PPC::PRED_LT;
2008   case ISD::SETULE:
2009   case ISD::SETLE:  return PPC::PRED_LE;
2010   case ISD::SETOGT:
2011   case ISD::SETGT:  return PPC::PRED_GT;
2012   case ISD::SETUGE:
2013   case ISD::SETGE:  return PPC::PRED_GE;
2014   case ISD::SETO:   return PPC::PRED_NU;
2015   case ISD::SETUO:  return PPC::PRED_UN;
2016     // These two are invalid for floating point.  Assume we have int.
2017   case ISD::SETULT: return PPC::PRED_LT;
2018   case ISD::SETUGT: return PPC::PRED_GT;
2019   }
2020 }
2021
2022 /// getCRIdxForSetCC - Return the index of the condition register field
2023 /// associated with the SetCC condition, and whether or not the field is
2024 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
2025 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2026   Invert = false;
2027   switch (CC) {
2028   default: llvm_unreachable("Unknown condition!");
2029   case ISD::SETOLT:
2030   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
2031   case ISD::SETOGT:
2032   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
2033   case ISD::SETOEQ:
2034   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
2035   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
2036   case ISD::SETUGE:
2037   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
2038   case ISD::SETULE:
2039   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
2040   case ISD::SETUNE:
2041   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
2042   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
2043   case ISD::SETUEQ:
2044   case ISD::SETOGE:
2045   case ISD::SETOLE:
2046   case ISD::SETONE:
2047     llvm_unreachable("Invalid branch code: should be expanded by legalize");
2048   // These are invalid for floating point.  Assume integer.
2049   case ISD::SETULT: return 0;
2050   case ISD::SETUGT: return 1;
2051   }
2052 }
2053
2054 // getVCmpInst: return the vector compare instruction for the specified
2055 // vector type and condition code. Since this is for altivec specific code,
2056 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
2057 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2058                                 bool HasVSX, bool &Swap, bool &Negate) {
2059   Swap = false;
2060   Negate = false;
2061
2062   if (VecVT.isFloatingPoint()) {
2063     /* Handle some cases by swapping input operands.  */
2064     switch (CC) {
2065       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2066       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2067       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2068       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2069       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2070       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2071       default: break;
2072     }
2073     /* Handle some cases by negating the result.  */
2074     switch (CC) {
2075       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2076       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2077       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2078       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2079       default: break;
2080     }
2081     /* We have instructions implementing the remaining cases.  */
2082     switch (CC) {
2083       case ISD::SETEQ:
2084       case ISD::SETOEQ:
2085         if (VecVT == MVT::v4f32)
2086           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2087         else if (VecVT == MVT::v2f64)
2088           return PPC::XVCMPEQDP;
2089         break;
2090       case ISD::SETGT:
2091       case ISD::SETOGT:
2092         if (VecVT == MVT::v4f32)
2093           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2094         else if (VecVT == MVT::v2f64)
2095           return PPC::XVCMPGTDP;
2096         break;
2097       case ISD::SETGE:
2098       case ISD::SETOGE:
2099         if (VecVT == MVT::v4f32)
2100           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2101         else if (VecVT == MVT::v2f64)
2102           return PPC::XVCMPGEDP;
2103         break;
2104       default:
2105         break;
2106     }
2107     llvm_unreachable("Invalid floating-point vector compare condition");
2108   } else {
2109     /* Handle some cases by swapping input operands.  */
2110     switch (CC) {
2111       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2112       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2113       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2114       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2115       default: break;
2116     }
2117     /* Handle some cases by negating the result.  */
2118     switch (CC) {
2119       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2120       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2121       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2122       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2123       default: break;
2124     }
2125     /* We have instructions implementing the remaining cases.  */
2126     switch (CC) {
2127       case ISD::SETEQ:
2128       case ISD::SETUEQ:
2129         if (VecVT == MVT::v16i8)
2130           return PPC::VCMPEQUB;
2131         else if (VecVT == MVT::v8i16)
2132           return PPC::VCMPEQUH;
2133         else if (VecVT == MVT::v4i32)
2134           return PPC::VCMPEQUW;
2135         break;
2136       case ISD::SETGT:
2137         if (VecVT == MVT::v16i8)
2138           return PPC::VCMPGTSB;
2139         else if (VecVT == MVT::v8i16)
2140           return PPC::VCMPGTSH;
2141         else if (VecVT == MVT::v4i32)
2142           return PPC::VCMPGTSW;
2143         break;
2144       case ISD::SETUGT:
2145         if (VecVT == MVT::v16i8)
2146           return PPC::VCMPGTUB;
2147         else if (VecVT == MVT::v8i16)
2148           return PPC::VCMPGTUH;
2149         else if (VecVT == MVT::v4i32)
2150           return PPC::VCMPGTUW;
2151         break;
2152       default:
2153         break;
2154     }
2155     llvm_unreachable("Invalid integer vector compare condition");
2156   }
2157 }
2158
2159 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2160   SDLoc dl(N);
2161   unsigned Imm;
2162   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2163   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2164   bool isPPC64 = (PtrVT == MVT::i64);
2165
2166   if (!PPCSubTarget->useCRBits() &&
2167       isInt32Immediate(N->getOperand(1), Imm)) {
2168     // We can codegen setcc op, imm very efficiently compared to a brcond.
2169     // Check for those cases here.
2170     // setcc op, 0
2171     if (Imm == 0) {
2172       SDValue Op = N->getOperand(0);
2173       switch (CC) {
2174       default: break;
2175       case ISD::SETEQ: {
2176         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2177         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
2178         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2179       }
2180       case ISD::SETNE: {
2181         if (isPPC64) break;
2182         SDValue AD =
2183           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2184                                          Op, getI32Imm(~0U)), 0);
2185         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2186                                     AD.getValue(1));
2187       }
2188       case ISD::SETLT: {
2189         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2190         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2191       }
2192       case ISD::SETGT: {
2193         SDValue T =
2194           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2195         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2196         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2197         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2198       }
2199       }
2200     } else if (Imm == ~0U) {        // setcc op, -1
2201       SDValue Op = N->getOperand(0);
2202       switch (CC) {
2203       default: break;
2204       case ISD::SETEQ:
2205         if (isPPC64) break;
2206         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2207                                             Op, getI32Imm(1)), 0);
2208         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2209                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2210                                                              MVT::i32,
2211                                                              getI32Imm(0)), 0),
2212                                       Op.getValue(1));
2213       case ISD::SETNE: {
2214         if (isPPC64) break;
2215         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2216         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2217                                             Op, getI32Imm(~0U));
2218         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2219                                     Op, SDValue(AD, 1));
2220       }
2221       case ISD::SETLT: {
2222         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2223                                                     getI32Imm(1)), 0);
2224         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2225                                                     Op), 0);
2226         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2227         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2228       }
2229       case ISD::SETGT: {
2230         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2231         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2232                      0);
2233         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2234                                     getI32Imm(1));
2235       }
2236       }
2237     }
2238   }
2239
2240   SDValue LHS = N->getOperand(0);
2241   SDValue RHS = N->getOperand(1);
2242
2243   // Altivec Vector compare instructions do not set any CR register by default and
2244   // vector compare operations return the same type as the operands.
2245   if (LHS.getValueType().isVector()) {
2246     EVT VecVT = LHS.getValueType();
2247     bool Swap, Negate;
2248     unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2249                                         PPCSubTarget->hasVSX(), Swap, Negate);
2250     if (Swap)
2251       std::swap(LHS, RHS);
2252
2253     if (Negate) {
2254       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2255       return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2256                                                               PPC::VNOR,
2257                                   VecVT, VCmp, VCmp);
2258     }
2259
2260     return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2261   }
2262
2263   if (PPCSubTarget->useCRBits())
2264     return nullptr;
2265
2266   bool Inv;
2267   unsigned Idx = getCRIdxForSetCC(CC, Inv);
2268   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2269   SDValue IntCR;
2270
2271   // Force the ccreg into CR7.
2272   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2273
2274   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
2275   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2276                                InFlag).getValue(1);
2277
2278   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2279                                          CCReg), 0);
2280
2281   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
2282                       getI32Imm(31), getI32Imm(31) };
2283   if (!Inv)
2284     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2285
2286   // Get the specified bit.
2287   SDValue Tmp =
2288     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2289   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
2290 }
2291
2292
2293 // Select - Convert the specified operand from a target-independent to a
2294 // target-specific node if it hasn't already been changed.
2295 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2296   SDLoc dl(N);
2297   if (N->isMachineOpcode()) {
2298     N->setNodeId(-1);
2299     return nullptr;   // Already selected.
2300   }
2301
2302   // In case any misguided DAG-level optimizations form an ADD with a
2303   // TargetConstant operand, crash here instead of miscompiling (by selecting
2304   // an r+r add instead of some kind of r+i add).
2305   if (N->getOpcode() == ISD::ADD &&
2306       N->getOperand(1).getOpcode() == ISD::TargetConstant)
2307     llvm_unreachable("Invalid ADD with TargetConstant operand");
2308
2309   // Try matching complex bit permutations before doing anything else.
2310   if (SDNode *NN = SelectBitPermutation(N))
2311     return NN;
2312
2313   switch (N->getOpcode()) {
2314   default: break;
2315
2316   case ISD::Constant: {
2317     if (N->getValueType(0) == MVT::i64)
2318       return SelectInt64(CurDAG, N);
2319     break;
2320   }
2321
2322   case ISD::SETCC: {
2323     SDNode *SN = SelectSETCC(N);
2324     if (SN)
2325       return SN;
2326     break;
2327   }
2328   case PPCISD::GlobalBaseReg:
2329     return getGlobalBaseReg();
2330
2331   case ISD::FrameIndex:
2332     return getFrameIndex(N, N);
2333
2334   case PPCISD::MFOCRF: {
2335     SDValue InFlag = N->getOperand(1);
2336     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2337                                   N->getOperand(0), InFlag);
2338   }
2339
2340   case PPCISD::READ_TIME_BASE: {
2341     return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2342                                   MVT::Other, N->getOperand(0));
2343   }
2344
2345   case PPCISD::SRA_ADDZE: {
2346     SDValue N0 = N->getOperand(0);
2347     SDValue ShiftAmt =
2348       CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2349                                   getConstantIntValue(), N->getValueType(0));
2350     if (N->getValueType(0) == MVT::i64) {
2351       SDNode *Op =
2352         CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2353                                N0, ShiftAmt);
2354       return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2355                                   SDValue(Op, 0), SDValue(Op, 1));
2356     } else {
2357       assert(N->getValueType(0) == MVT::i32 &&
2358              "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2359       SDNode *Op =
2360         CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2361                                N0, ShiftAmt);
2362       return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2363                                   SDValue(Op, 0), SDValue(Op, 1));
2364     }
2365   }
2366
2367   case ISD::LOAD: {
2368     // Handle preincrement loads.
2369     LoadSDNode *LD = cast<LoadSDNode>(N);
2370     EVT LoadedVT = LD->getMemoryVT();
2371
2372     // Normal loads are handled by code generated from the .td file.
2373     if (LD->getAddressingMode() != ISD::PRE_INC)
2374       break;
2375
2376     SDValue Offset = LD->getOffset();
2377     if (Offset.getOpcode() == ISD::TargetConstant ||
2378         Offset.getOpcode() == ISD::TargetGlobalAddress) {
2379
2380       unsigned Opcode;
2381       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2382       if (LD->getValueType(0) != MVT::i64) {
2383         // Handle PPC32 integer and normal FP loads.
2384         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2385         switch (LoadedVT.getSimpleVT().SimpleTy) {
2386           default: llvm_unreachable("Invalid PPC load type!");
2387           case MVT::f64: Opcode = PPC::LFDU; break;
2388           case MVT::f32: Opcode = PPC::LFSU; break;
2389           case MVT::i32: Opcode = PPC::LWZU; break;
2390           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2391           case MVT::i1:
2392           case MVT::i8:  Opcode = PPC::LBZU; break;
2393         }
2394       } else {
2395         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2396         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2397         switch (LoadedVT.getSimpleVT().SimpleTy) {
2398           default: llvm_unreachable("Invalid PPC load type!");
2399           case MVT::i64: Opcode = PPC::LDU; break;
2400           case MVT::i32: Opcode = PPC::LWZU8; break;
2401           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2402           case MVT::i1:
2403           case MVT::i8:  Opcode = PPC::LBZU8; break;
2404         }
2405       }
2406
2407       SDValue Chain = LD->getChain();
2408       SDValue Base = LD->getBasePtr();
2409       SDValue Ops[] = { Offset, Base, Chain };
2410       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
2411                                     PPCLowering->getPointerTy(),
2412                                     MVT::Other, Ops);
2413     } else {
2414       unsigned Opcode;
2415       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2416       if (LD->getValueType(0) != MVT::i64) {
2417         // Handle PPC32 integer and normal FP loads.
2418         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2419         switch (LoadedVT.getSimpleVT().SimpleTy) {
2420           default: llvm_unreachable("Invalid PPC load type!");
2421           case MVT::f64: Opcode = PPC::LFDUX; break;
2422           case MVT::f32: Opcode = PPC::LFSUX; break;
2423           case MVT::i32: Opcode = PPC::LWZUX; break;
2424           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2425           case MVT::i1:
2426           case MVT::i8:  Opcode = PPC::LBZUX; break;
2427         }
2428       } else {
2429         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2430         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2431                "Invalid sext update load");
2432         switch (LoadedVT.getSimpleVT().SimpleTy) {
2433           default: llvm_unreachable("Invalid PPC load type!");
2434           case MVT::i64: Opcode = PPC::LDUX; break;
2435           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
2436           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2437           case MVT::i1:
2438           case MVT::i8:  Opcode = PPC::LBZUX8; break;
2439         }
2440       }
2441
2442       SDValue Chain = LD->getChain();
2443       SDValue Base = LD->getBasePtr();
2444       SDValue Ops[] = { Base, Offset, Chain };
2445       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
2446                                     PPCLowering->getPointerTy(),
2447                                     MVT::Other, Ops);
2448     }
2449   }
2450
2451   case ISD::AND: {
2452     unsigned Imm, Imm2, SH, MB, ME;
2453     uint64_t Imm64;
2454
2455     // If this is an and of a value rotated between 0 and 31 bits and then and'd
2456     // with a mask, emit rlwinm
2457     if (isInt32Immediate(N->getOperand(1), Imm) &&
2458         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2459       SDValue Val = N->getOperand(0).getOperand(0);
2460       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2461       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2462     }
2463     // If this is just a masked value where the input is not handled above, and
2464     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2465     if (isInt32Immediate(N->getOperand(1), Imm) &&
2466         isRunOfOnes(Imm, MB, ME) &&
2467         N->getOperand(0).getOpcode() != ISD::ROTL) {
2468       SDValue Val = N->getOperand(0);
2469       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
2470       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2471     }
2472     // If this is a 64-bit zero-extension mask, emit rldicl.
2473     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2474         isMask_64(Imm64)) {
2475       SDValue Val = N->getOperand(0);
2476       MB = 64 - CountTrailingOnes_64(Imm64);
2477       SH = 0;
2478
2479       // If the operand is a logical right shift, we can fold it into this
2480       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2481       // for n <= mb. The right shift is really a left rotate followed by a
2482       // mask, and this mask is a more-restrictive sub-mask of the mask implied
2483       // by the shift.
2484       if (Val.getOpcode() == ISD::SRL &&
2485           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2486         assert(Imm < 64 && "Illegal shift amount");
2487         Val = Val.getOperand(0);
2488         SH = 64 - Imm;
2489       }
2490
2491       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
2492       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2493     }
2494     // AND X, 0 -> 0, not "rlwinm 32".
2495     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2496       ReplaceUses(SDValue(N, 0), N->getOperand(1));
2497       return nullptr;
2498     }
2499     // ISD::OR doesn't get all the bitfield insertion fun.
2500     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2501     if (isInt32Immediate(N->getOperand(1), Imm) &&
2502         N->getOperand(0).getOpcode() == ISD::OR &&
2503         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2504       unsigned MB, ME;
2505       Imm = ~(Imm^Imm2);
2506       if (isRunOfOnes(Imm, MB, ME)) {
2507         SDValue Ops[] = { N->getOperand(0).getOperand(0),
2508                             N->getOperand(0).getOperand(1),
2509                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
2510         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2511       }
2512     }
2513
2514     // Other cases are autogenerated.
2515     break;
2516   }
2517   case ISD::OR: {
2518     if (N->getValueType(0) == MVT::i32)
2519       if (SDNode *I = SelectBitfieldInsert(N))
2520         return I;
2521
2522     short Imm;
2523     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2524         isIntS16Immediate(N->getOperand(1), Imm)) {
2525       APInt LHSKnownZero, LHSKnownOne;
2526       CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2527
2528       // If this is equivalent to an add, then we can fold it with the
2529       // FrameIndex calculation.
2530       if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2531         return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2532     }
2533
2534     // Other cases are autogenerated.
2535     break;
2536   }
2537   case ISD::ADD: {
2538     short Imm;
2539     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2540         isIntS16Immediate(N->getOperand(1), Imm))
2541       return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2542
2543     break;
2544   }
2545   case ISD::SHL: {
2546     unsigned Imm, SH, MB, ME;
2547     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2548         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2549       SDValue Ops[] = { N->getOperand(0).getOperand(0),
2550                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2551       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2552     }
2553
2554     // Other cases are autogenerated.
2555     break;
2556   }
2557   case ISD::SRL: {
2558     unsigned Imm, SH, MB, ME;
2559     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2560         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2561       SDValue Ops[] = { N->getOperand(0).getOperand(0),
2562                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2563       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2564     }
2565
2566     // Other cases are autogenerated.
2567     break;
2568   }
2569   // FIXME: Remove this once the ANDI glue bug is fixed:
2570   case PPCISD::ANDIo_1_EQ_BIT:
2571   case PPCISD::ANDIo_1_GT_BIT: {
2572     if (!ANDIGlueBug)
2573       break;
2574
2575     EVT InVT = N->getOperand(0).getValueType();
2576     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2577            "Invalid input type for ANDIo_1_EQ_BIT");
2578
2579     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2580     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2581                                         N->getOperand(0),
2582                                         CurDAG->getTargetConstant(1, InVT)), 0);
2583     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2584     SDValue SRIdxVal =
2585       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2586                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
2587
2588     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2589                                 CR0Reg, SRIdxVal,
2590                                 SDValue(AndI.getNode(), 1) /* glue */);
2591   }
2592   case ISD::SELECT_CC: {
2593     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2594     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2595     bool isPPC64 = (PtrVT == MVT::i64);
2596
2597     // If this is a select of i1 operands, we'll pattern match it.
2598     if (PPCSubTarget->useCRBits() &&
2599         N->getOperand(0).getValueType() == MVT::i1)
2600       break;
2601
2602     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
2603     if (!isPPC64)
2604       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2605         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2606           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2607             if (N1C->isNullValue() && N3C->isNullValue() &&
2608                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2609                 // FIXME: Implement this optzn for PPC64.
2610                 N->getValueType(0) == MVT::i32) {
2611               SDNode *Tmp =
2612                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2613                                        N->getOperand(0), getI32Imm(~0U));
2614               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2615                                           SDValue(Tmp, 0), N->getOperand(0),
2616                                           SDValue(Tmp, 1));
2617             }
2618
2619     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2620
2621     if (N->getValueType(0) == MVT::i1) {
2622       // An i1 select is: (c & t) | (!c & f).
2623       bool Inv;
2624       unsigned Idx = getCRIdxForSetCC(CC, Inv);
2625
2626       unsigned SRI;
2627       switch (Idx) {
2628       default: llvm_unreachable("Invalid CC index");
2629       case 0: SRI = PPC::sub_lt; break;
2630       case 1: SRI = PPC::sub_gt; break;
2631       case 2: SRI = PPC::sub_eq; break;
2632       case 3: SRI = PPC::sub_un; break;
2633       }
2634
2635       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2636
2637       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2638                                               CCBit, CCBit), 0);
2639       SDValue C =    Inv ? NotCCBit : CCBit,
2640               NotC = Inv ? CCBit    : NotCCBit;
2641
2642       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2643                                            C, N->getOperand(2)), 0);
2644       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2645                                               NotC, N->getOperand(3)), 0);
2646
2647       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2648     }
2649
2650     unsigned BROpc = getPredicateForSetCC(CC);
2651
2652     unsigned SelectCCOp;
2653     if (N->getValueType(0) == MVT::i32)
2654       SelectCCOp = PPC::SELECT_CC_I4;
2655     else if (N->getValueType(0) == MVT::i64)
2656       SelectCCOp = PPC::SELECT_CC_I8;
2657     else if (N->getValueType(0) == MVT::f32)
2658       SelectCCOp = PPC::SELECT_CC_F4;
2659     else if (N->getValueType(0) == MVT::f64)
2660       if (PPCSubTarget->hasVSX())
2661         SelectCCOp = PPC::SELECT_CC_VSFRC;
2662       else
2663         SelectCCOp = PPC::SELECT_CC_F8;
2664     else if (N->getValueType(0) == MVT::v2f64 ||
2665              N->getValueType(0) == MVT::v2i64)
2666       SelectCCOp = PPC::SELECT_CC_VSRC;
2667     else
2668       SelectCCOp = PPC::SELECT_CC_VRRC;
2669
2670     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2671                         getI32Imm(BROpc) };
2672     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2673   }
2674   case ISD::VSELECT:
2675     if (PPCSubTarget->hasVSX()) {
2676       SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2677       return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2678     }
2679
2680     break;
2681   case ISD::VECTOR_SHUFFLE:
2682     if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2683                                   N->getValueType(0) == MVT::v2i64)) {
2684       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2685       
2686       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2687               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2688       unsigned DM[2];
2689
2690       for (int i = 0; i < 2; ++i)
2691         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2692           DM[i] = 0;
2693         else
2694           DM[i] = 1;
2695
2696       // For little endian, we must swap the input operands and adjust
2697       // the mask elements (reverse and invert them).
2698       if (PPCSubTarget->isLittleEndian()) {
2699         std::swap(Op1, Op2);
2700         unsigned tmp = DM[0];
2701         DM[0] = 1 - DM[1];
2702         DM[1] = 1 - tmp;
2703       }
2704
2705       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
2706
2707       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2708           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2709           isa<LoadSDNode>(Op1.getOperand(0))) {
2710         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2711         SDValue Base, Offset;
2712
2713         if (LD->isUnindexed() &&
2714             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2715           SDValue Chain = LD->getChain();
2716           SDValue Ops[] = { Base, Offset, Chain };
2717           return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2718                                       N->getValueType(0), Ops);
2719         }
2720       }
2721
2722       SDValue Ops[] = { Op1, Op2, DMV };
2723       return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2724     }
2725
2726     break;
2727   case PPCISD::BDNZ:
2728   case PPCISD::BDZ: {
2729     bool IsPPC64 = PPCSubTarget->isPPC64();
2730     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2731     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2732                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2733                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2734                                 MVT::Other, Ops);
2735   }
2736   case PPCISD::COND_BRANCH: {
2737     // Op #0 is the Chain.
2738     // Op #1 is the PPC::PRED_* number.
2739     // Op #2 is the CR#
2740     // Op #3 is the Dest MBB
2741     // Op #4 is the Flag.
2742     // Prevent PPC::PRED_* from being selected into LI.
2743     SDValue Pred =
2744       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
2745     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2746       N->getOperand(0), N->getOperand(4) };
2747     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2748   }
2749   case ISD::BR_CC: {
2750     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2751     unsigned PCC = getPredicateForSetCC(CC);
2752
2753     if (N->getOperand(2).getValueType() == MVT::i1) {
2754       unsigned Opc;
2755       bool Swap;
2756       switch (PCC) {
2757       default: llvm_unreachable("Unexpected Boolean-operand predicate");
2758       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
2759       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
2760       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
2761       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
2762       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2763       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
2764       }
2765
2766       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2767                                              N->getOperand(Swap ? 3 : 2),
2768                                              N->getOperand(Swap ? 2 : 3)), 0);
2769       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2770                                   BitComp, N->getOperand(4), N->getOperand(0));
2771     }
2772
2773     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2774     SDValue Ops[] = { getI32Imm(PCC), CondCode,
2775                         N->getOperand(4), N->getOperand(0) };
2776     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2777   }
2778   case ISD::BRIND: {
2779     // FIXME: Should custom lower this.
2780     SDValue Chain = N->getOperand(0);
2781     SDValue Target = N->getOperand(1);
2782     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2783     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2784     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2785                                            Chain), 0);
2786     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2787   }
2788   case PPCISD::TOC_ENTRY: {
2789     assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2790             "Only supported for 64-bit ABI and 32-bit SVR4");
2791     if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2792       SDValue GA = N->getOperand(0);
2793       return CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
2794                                     N->getOperand(1));
2795     }
2796
2797     // For medium and large code model, we generate two instructions as
2798     // described below.  Otherwise we allow SelectCodeCommon to handle this,
2799     // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2800     CodeModel::Model CModel = TM.getCodeModel();
2801     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2802       break;
2803
2804     // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2805     // If it is an externally defined symbol, a symbol with common linkage,
2806     // a non-local function address, or a jump table address, or if we are
2807     // generating code for large code model, we generate:
2808     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2809     // Otherwise we generate:
2810     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2811     SDValue GA = N->getOperand(0);
2812     SDValue TOCbase = N->getOperand(1);
2813     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2814                                         TOCbase, GA);
2815
2816     if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2817         CModel == CodeModel::Large)
2818       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
2819                                     SDValue(Tmp, 0));
2820
2821     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2822       const GlobalValue *GValue = G->getGlobal();
2823       if ((GValue->getType()->getElementType()->isFunctionTy() &&
2824            (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2825           GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2826           GValue->hasAvailableExternallyLinkage())
2827         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
2828                                       SDValue(Tmp, 0));
2829     }
2830
2831     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2832                                   SDValue(Tmp, 0), GA);
2833   }
2834   case PPCISD::PPC32_PICGOT: {
2835     // Generate a PIC-safe GOT reference.
2836     assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2837       "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2838     return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(),  MVT::i32);
2839   }
2840   case PPCISD::VADD_SPLAT: {
2841     // This expands into one of three sequences, depending on whether
2842     // the first operand is odd or even, positive or negative.
2843     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2844            isa<ConstantSDNode>(N->getOperand(1)) &&
2845            "Invalid operand on VADD_SPLAT!");
2846
2847     int Elt     = N->getConstantOperandVal(0);
2848     int EltSize = N->getConstantOperandVal(1);
2849     unsigned Opc1, Opc2, Opc3;
2850     EVT VT;
2851
2852     if (EltSize == 1) {
2853       Opc1 = PPC::VSPLTISB;
2854       Opc2 = PPC::VADDUBM;
2855       Opc3 = PPC::VSUBUBM;
2856       VT = MVT::v16i8;
2857     } else if (EltSize == 2) {
2858       Opc1 = PPC::VSPLTISH;
2859       Opc2 = PPC::VADDUHM;
2860       Opc3 = PPC::VSUBUHM;
2861       VT = MVT::v8i16;
2862     } else {
2863       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2864       Opc1 = PPC::VSPLTISW;
2865       Opc2 = PPC::VADDUWM;
2866       Opc3 = PPC::VSUBUWM;
2867       VT = MVT::v4i32;
2868     }
2869
2870     if ((Elt & 1) == 0) {
2871       // Elt is even, in the range [-32,-18] + [16,30].
2872       //
2873       // Convert: VADD_SPLAT elt, size
2874       // Into:    tmp = VSPLTIS[BHW] elt
2875       //          VADDU[BHW]M tmp, tmp
2876       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
2877       SDValue EltVal = getI32Imm(Elt >> 1);
2878       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2879       SDValue TmpVal = SDValue(Tmp, 0);
2880       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2881
2882     } else if (Elt > 0) {
2883       // Elt is odd and positive, in the range [17,31].
2884       //
2885       // Convert: VADD_SPLAT elt, size
2886       // Into:    tmp1 = VSPLTIS[BHW] elt-16
2887       //          tmp2 = VSPLTIS[BHW] -16
2888       //          VSUBU[BHW]M tmp1, tmp2
2889       SDValue EltVal = getI32Imm(Elt - 16);
2890       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2891       EltVal = getI32Imm(-16);
2892       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2893       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2894                                     SDValue(Tmp2, 0));
2895
2896     } else {
2897       // Elt is odd and negative, in the range [-31,-17].
2898       //
2899       // Convert: VADD_SPLAT elt, size
2900       // Into:    tmp1 = VSPLTIS[BHW] elt+16
2901       //          tmp2 = VSPLTIS[BHW] -16
2902       //          VADDU[BHW]M tmp1, tmp2
2903       SDValue EltVal = getI32Imm(Elt + 16);
2904       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2905       EltVal = getI32Imm(-16);
2906       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2907       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
2908                                     SDValue(Tmp2, 0));
2909     }
2910   }
2911   }
2912
2913   return SelectCode(N);
2914 }
2915
2916 // If the target supports the cmpb instruction, do the idiom recognition here.
2917 // We don't do this as a DAG combine because we don't want to do it as nodes
2918 // are being combined (because we might miss part of the eventual idiom). We
2919 // don't want to do it during instruction selection because we want to reuse
2920 // the logic for lowering the masking operations already part of the
2921 // instruction selector.
2922 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
2923   SDLoc dl(N);
2924
2925   assert(N->getOpcode() == ISD::OR &&
2926          "Only OR nodes are supported for CMPB");
2927
2928   SDValue Res;
2929   if (!PPCSubTarget->hasCMPB())
2930     return Res;
2931
2932   if (N->getValueType(0) != MVT::i32 &&
2933       N->getValueType(0) != MVT::i64)
2934     return Res;
2935
2936   EVT VT = N->getValueType(0);
2937
2938   SDValue RHS, LHS;
2939   bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
2940   uint64_t Mask = 0, Alt = 0;
2941
2942   auto IsByteSelectCC = [this](SDValue O, unsigned &b,
2943                                uint64_t &Mask, uint64_t &Alt,
2944                                SDValue &LHS, SDValue &RHS) {
2945     if (O.getOpcode() != ISD::SELECT_CC)
2946       return false;
2947     ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
2948
2949     if (!isa<ConstantSDNode>(O.getOperand(2)) ||
2950         !isa<ConstantSDNode>(O.getOperand(3)))
2951       return false;
2952
2953     uint64_t PM = O.getConstantOperandVal(2);
2954     uint64_t PAlt = O.getConstantOperandVal(3);
2955     for (b = 0; b < 8; ++b) {
2956       uint64_t Mask = UINT64_C(0xFF) << (8*b);
2957       if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
2958         break;
2959     }
2960
2961     if (b == 8)
2962       return false;
2963     Mask |= PM;
2964     Alt  |= PAlt;
2965
2966     if (!isa<ConstantSDNode>(O.getOperand(1)) ||
2967         O.getConstantOperandVal(1) != 0) {
2968       SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
2969       if (Op0.getOpcode() == ISD::TRUNCATE)
2970         Op0 = Op0.getOperand(0);
2971       if (Op1.getOpcode() == ISD::TRUNCATE)
2972         Op1 = Op1.getOperand(0);
2973
2974       if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
2975           Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
2976           isa<ConstantSDNode>(Op0.getOperand(1))) {
2977
2978         unsigned Bits = Op0.getValueType().getSizeInBits();
2979         if (b != Bits/8-1)
2980           return false;
2981         if (Op0.getConstantOperandVal(1) != Bits-8)
2982           return false;
2983
2984         LHS = Op0.getOperand(0);
2985         RHS = Op1.getOperand(0);
2986         return true;
2987       }
2988
2989       // When we have small integers (i16 to be specific), the form present
2990       // post-legalization uses SETULT in the SELECT_CC for the
2991       // higher-order byte, depending on the fact that the
2992       // even-higher-order bytes are known to all be zero, for example:
2993       //   select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
2994       // (so when the second byte is the same, because all higher-order
2995       // bits from bytes 3 and 4 are known to be zero, the result of the
2996       // xor can be at most 255)
2997       if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
2998           isa<ConstantSDNode>(O.getOperand(1))) {
2999
3000         uint64_t ULim = O.getConstantOperandVal(1);
3001         if (ULim != (UINT64_C(1) << b*8))
3002           return false;
3003
3004         // Now we need to make sure that the upper bytes are known to be
3005         // zero.
3006         unsigned Bits = Op0.getValueType().getSizeInBits();
3007         if (!CurDAG->MaskedValueIsZero(Op0,
3008               APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3009           return false;
3010         
3011         LHS = Op0.getOperand(0);
3012         RHS = Op0.getOperand(1);
3013         return true;
3014       }
3015
3016       return false;
3017     }
3018
3019     if (CC != ISD::SETEQ)
3020       return false;
3021
3022     SDValue Op = O.getOperand(0);
3023     if (Op.getOpcode() == ISD::AND) {
3024       if (!isa<ConstantSDNode>(Op.getOperand(1)))
3025         return false;
3026       if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3027         return false;
3028
3029       SDValue XOR = Op.getOperand(0);
3030       if (XOR.getOpcode() == ISD::TRUNCATE)
3031         XOR = XOR.getOperand(0);
3032       if (XOR.getOpcode() != ISD::XOR)
3033         return false;
3034
3035       LHS = XOR.getOperand(0);
3036       RHS = XOR.getOperand(1);
3037       return true;
3038     } else if (Op.getOpcode() == ISD::SRL) {
3039       if (!isa<ConstantSDNode>(Op.getOperand(1)))
3040         return false;
3041       unsigned Bits = Op.getValueType().getSizeInBits();
3042       if (b != Bits/8-1)
3043         return false;
3044       if (Op.getConstantOperandVal(1) != Bits-8)
3045         return false;
3046
3047       SDValue XOR = Op.getOperand(0);
3048       if (XOR.getOpcode() == ISD::TRUNCATE)
3049         XOR = XOR.getOperand(0);
3050       if (XOR.getOpcode() != ISD::XOR)
3051         return false;
3052
3053       LHS = XOR.getOperand(0);
3054       RHS = XOR.getOperand(1);
3055       return true;
3056     }
3057
3058     return false;
3059   };
3060
3061   SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3062   while (!Queue.empty()) {
3063     SDValue V = Queue.pop_back_val();
3064
3065     for (const SDValue &O : V.getNode()->ops()) {
3066       unsigned b;
3067       uint64_t M = 0, A = 0;
3068       SDValue OLHS, ORHS;
3069       if (O.getOpcode() == ISD::OR) {
3070         Queue.push_back(O);
3071       } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3072         if (!LHS) {
3073           LHS = OLHS;
3074           RHS = ORHS;
3075           BytesFound[b] = true;
3076           Mask |= M;
3077           Alt  |= A;
3078         } else if ((LHS == ORHS && RHS == OLHS) ||
3079                    (RHS == ORHS && LHS == OLHS)) {
3080           BytesFound[b] = true;
3081           Mask |= M;
3082           Alt  |= A;
3083         } else {
3084           return Res;
3085         }
3086       } else {
3087         return Res;
3088       }
3089     }
3090   }
3091
3092   unsigned LastB = 0, BCnt = 0;
3093   for (unsigned i = 0; i < 8; ++i)
3094     if (BytesFound[LastB]) {
3095       ++BCnt;
3096       LastB = i;
3097     }
3098
3099   if (!LastB || BCnt < 2)
3100     return Res;
3101
3102   // Because we'll be zero-extending the output anyway if don't have a specific
3103   // value for each input byte (via the Mask), we can 'anyext' the inputs.
3104   if (LHS.getValueType() != VT) {
3105     LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3106     RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3107   }
3108
3109   Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3110
3111   bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3112   if (NonTrivialMask && !Alt) {
3113     // Res = Mask & CMPB
3114     Res = CurDAG->getNode(ISD::AND, dl, VT, Res, CurDAG->getConstant(Mask, VT));
3115   } else if (Alt) {
3116     // Res = (CMPB & Mask) | (~CMPB & Alt)
3117     // Which, as suggested here:
3118     //   https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3119     // can be written as:
3120     // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3121     // useful because the (Alt ^ Mask) can be pre-computed.
3122     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3123                           CurDAG->getConstant(Mask ^ Alt, VT));
3124     Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, CurDAG->getConstant(Alt, VT));
3125   }
3126
3127   return Res;
3128 }
3129
3130 void PPCDAGToDAGISel::PreprocessISelDAG() {
3131   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3132   ++Position;
3133
3134   bool MadeChange = false;
3135   while (Position != CurDAG->allnodes_begin()) {
3136     SDNode *N = --Position;
3137     if (N->use_empty())
3138       continue;
3139
3140     SDValue Res;
3141     switch (N->getOpcode()) {
3142     default: break;
3143     case ISD::OR:
3144       Res = combineToCMPB(N);
3145       break;
3146     }
3147
3148     if (Res) {
3149       DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld:    ");
3150       DEBUG(N->dump(CurDAG));
3151       DEBUG(dbgs() << "\nNew: ");
3152       DEBUG(Res.getNode()->dump(CurDAG));
3153       DEBUG(dbgs() << "\n");
3154
3155       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3156       MadeChange = true;
3157     }
3158   }
3159
3160   if (MadeChange)
3161     CurDAG->RemoveDeadNodes();
3162 }
3163
3164 /// PostprocessISelDAG - Perform some late peephole optimizations
3165 /// on the DAG representation.
3166 void PPCDAGToDAGISel::PostprocessISelDAG() {
3167
3168   // Skip peepholes at -O0.
3169   if (TM.getOptLevel() == CodeGenOpt::None)
3170     return;
3171
3172   PeepholePPC64();
3173   PeepholeCROps();
3174   PeepholePPC64ZExt();
3175 }
3176
3177 // Check if all users of this node will become isel where the second operand
3178 // is the constant zero. If this is so, and if we can negate the condition,
3179 // then we can flip the true and false operands. This will allow the zero to
3180 // be folded with the isel so that we don't need to materialize a register
3181 // containing zero.
3182 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3183   // If we're not using isel, then this does not matter.
3184   if (!PPCSubTarget->hasISEL())
3185     return false;
3186
3187   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3188        UI != UE; ++UI) {
3189     SDNode *User = *UI;
3190     if (!User->isMachineOpcode())
3191       return false;
3192     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3193         User->getMachineOpcode() != PPC::SELECT_I8)
3194       return false;
3195
3196     SDNode *Op2 = User->getOperand(2).getNode();
3197     if (!Op2->isMachineOpcode())
3198       return false;
3199
3200     if (Op2->getMachineOpcode() != PPC::LI &&
3201         Op2->getMachineOpcode() != PPC::LI8)
3202       return false;
3203
3204     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3205     if (!C)
3206       return false;
3207
3208     if (!C->isNullValue())
3209       return false;
3210   }
3211
3212   return true;
3213 }
3214
3215 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3216   SmallVector<SDNode *, 4> ToReplace;
3217   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3218        UI != UE; ++UI) {
3219     SDNode *User = *UI;
3220     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3221             User->getMachineOpcode() == PPC::SELECT_I8) &&
3222            "Must have all select users");
3223     ToReplace.push_back(User);
3224   }
3225
3226   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3227        UE = ToReplace.end(); UI != UE; ++UI) {
3228     SDNode *User = *UI;
3229     SDNode *ResNode =
3230       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3231                              User->getValueType(0), User->getOperand(0),
3232                              User->getOperand(2),
3233                              User->getOperand(1));
3234
3235       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
3236       DEBUG(User->dump(CurDAG));
3237       DEBUG(dbgs() << "\nNew: ");
3238       DEBUG(ResNode->dump(CurDAG));
3239       DEBUG(dbgs() << "\n");
3240
3241       ReplaceUses(User, ResNode);
3242   }
3243 }
3244
3245 void PPCDAGToDAGISel::PeepholeCROps() {
3246   bool IsModified;
3247   do {
3248     IsModified = false;
3249     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3250          E = CurDAG->allnodes_end(); I != E; ++I) {
3251       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3252       if (!MachineNode || MachineNode->use_empty())
3253         continue;
3254       SDNode *ResNode = MachineNode;
3255
3256       bool Op1Set   = false, Op1Unset = false,
3257            Op1Not   = false,
3258            Op2Set   = false, Op2Unset = false,
3259            Op2Not   = false;
3260
3261       unsigned Opcode = MachineNode->getMachineOpcode();
3262       switch (Opcode) {
3263       default: break;
3264       case PPC::CRAND:
3265       case PPC::CRNAND:
3266       case PPC::CROR:
3267       case PPC::CRXOR:
3268       case PPC::CRNOR:
3269       case PPC::CREQV:
3270       case PPC::CRANDC:
3271       case PPC::CRORC: {
3272         SDValue Op = MachineNode->getOperand(1);
3273         if (Op.isMachineOpcode()) {
3274           if (Op.getMachineOpcode() == PPC::CRSET)
3275             Op2Set = true;
3276           else if (Op.getMachineOpcode() == PPC::CRUNSET)
3277             Op2Unset = true;
3278           else if (Op.getMachineOpcode() == PPC::CRNOR &&
3279                    Op.getOperand(0) == Op.getOperand(1))
3280             Op2Not = true;
3281         }
3282         }  // fallthrough
3283       case PPC::BC:
3284       case PPC::BCn:
3285       case PPC::SELECT_I4:
3286       case PPC::SELECT_I8:
3287       case PPC::SELECT_F4:
3288       case PPC::SELECT_F8:
3289       case PPC::SELECT_VRRC:
3290       case PPC::SELECT_VSFRC:
3291       case PPC::SELECT_VSRC: {
3292         SDValue Op = MachineNode->getOperand(0);
3293         if (Op.isMachineOpcode()) {
3294           if (Op.getMachineOpcode() == PPC::CRSET)
3295             Op1Set = true;
3296           else if (Op.getMachineOpcode() == PPC::CRUNSET)
3297             Op1Unset = true;
3298           else if (Op.getMachineOpcode() == PPC::CRNOR &&
3299                    Op.getOperand(0) == Op.getOperand(1))
3300             Op1Not = true;
3301         }
3302         }
3303         break;
3304       }
3305
3306       bool SelectSwap = false;
3307       switch (Opcode) {
3308       default: break;
3309       case PPC::CRAND:
3310         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3311           // x & x = x
3312           ResNode = MachineNode->getOperand(0).getNode();
3313         else if (Op1Set)
3314           // 1 & y = y
3315           ResNode = MachineNode->getOperand(1).getNode();
3316         else if (Op2Set)
3317           // x & 1 = x
3318           ResNode = MachineNode->getOperand(0).getNode();
3319         else if (Op1Unset || Op2Unset)
3320           // x & 0 = 0 & y = 0
3321           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3322                                            MVT::i1);
3323         else if (Op1Not)
3324           // ~x & y = andc(y, x)
3325           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3326                                            MVT::i1, MachineNode->getOperand(1),
3327                                            MachineNode->getOperand(0).
3328                                              getOperand(0));
3329         else if (Op2Not)
3330           // x & ~y = andc(x, y)
3331           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3332                                            MVT::i1, MachineNode->getOperand(0),
3333                                            MachineNode->getOperand(1).
3334                                              getOperand(0));
3335         else if (AllUsersSelectZero(MachineNode))
3336           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3337                                            MVT::i1, MachineNode->getOperand(0),
3338                                            MachineNode->getOperand(1)),
3339           SelectSwap = true;
3340         break;
3341       case PPC::CRNAND:
3342         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3343           // nand(x, x) -> nor(x, x)
3344           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3345                                            MVT::i1, MachineNode->getOperand(0),
3346                                            MachineNode->getOperand(0));
3347         else if (Op1Set)
3348           // nand(1, y) -> nor(y, y)
3349           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3350                                            MVT::i1, MachineNode->getOperand(1),
3351                                            MachineNode->getOperand(1));
3352         else if (Op2Set)
3353           // nand(x, 1) -> nor(x, x)
3354           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3355                                            MVT::i1, MachineNode->getOperand(0),
3356                                            MachineNode->getOperand(0));
3357         else if (Op1Unset || Op2Unset)
3358           // nand(x, 0) = nand(0, y) = 1
3359           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3360                                            MVT::i1);
3361         else if (Op1Not)
3362           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3363           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3364                                            MVT::i1, MachineNode->getOperand(0).
3365                                                       getOperand(0),
3366                                            MachineNode->getOperand(1));
3367         else if (Op2Not)
3368           // nand(x, ~y) = ~x | y = orc(y, x)
3369           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3370                                            MVT::i1, MachineNode->getOperand(1).
3371                                                       getOperand(0),
3372                                            MachineNode->getOperand(0));
3373         else if (AllUsersSelectZero(MachineNode))
3374           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3375                                            MVT::i1, MachineNode->getOperand(0),
3376                                            MachineNode->getOperand(1)),
3377           SelectSwap = true;
3378         break;
3379       case PPC::CROR:
3380         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3381           // x | x = x
3382           ResNode = MachineNode->getOperand(0).getNode();
3383         else if (Op1Set || Op2Set)
3384           // x | 1 = 1 | y = 1
3385           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3386                                            MVT::i1);
3387         else if (Op1Unset)
3388           // 0 | y = y
3389           ResNode = MachineNode->getOperand(1).getNode();
3390         else if (Op2Unset)
3391           // x | 0 = x
3392           ResNode = MachineNode->getOperand(0).getNode();
3393         else if (Op1Not)
3394           // ~x | y = orc(y, x)
3395           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3396                                            MVT::i1, MachineNode->getOperand(1),
3397                                            MachineNode->getOperand(0).
3398                                              getOperand(0));
3399         else if (Op2Not)
3400           // x | ~y = orc(x, y)
3401           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3402                                            MVT::i1, MachineNode->getOperand(0),
3403                                            MachineNode->getOperand(1).
3404                                              getOperand(0));
3405         else if (AllUsersSelectZero(MachineNode))
3406           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3407                                            MVT::i1, MachineNode->getOperand(0),
3408                                            MachineNode->getOperand(1)),
3409           SelectSwap = true;
3410         break;
3411       case PPC::CRXOR:
3412         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3413           // xor(x, x) = 0
3414           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3415                                            MVT::i1);
3416         else if (Op1Set)
3417           // xor(1, y) -> nor(y, y)
3418           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3419                                            MVT::i1, MachineNode->getOperand(1),
3420                                            MachineNode->getOperand(1));
3421         else if (Op2Set)
3422           // xor(x, 1) -> nor(x, x)
3423           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3424                                            MVT::i1, MachineNode->getOperand(0),
3425                                            MachineNode->getOperand(0));
3426         else if (Op1Unset)
3427           // xor(0, y) = y
3428           ResNode = MachineNode->getOperand(1).getNode();
3429         else if (Op2Unset)
3430           // xor(x, 0) = x
3431           ResNode = MachineNode->getOperand(0).getNode();
3432         else if (Op1Not)
3433           // xor(~x, y) = eqv(x, y)
3434           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3435                                            MVT::i1, MachineNode->getOperand(0).
3436                                                       getOperand(0),
3437                                            MachineNode->getOperand(1));
3438         else if (Op2Not)
3439           // xor(x, ~y) = eqv(x, y)
3440           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3441                                            MVT::i1, MachineNode->getOperand(0),
3442                                            MachineNode->getOperand(1).
3443                                              getOperand(0));
3444         else if (AllUsersSelectZero(MachineNode))
3445           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3446                                            MVT::i1, MachineNode->getOperand(0),
3447                                            MachineNode->getOperand(1)),
3448           SelectSwap = true;
3449         break;
3450       case PPC::CRNOR:
3451         if (Op1Set || Op2Set)
3452           // nor(1, y) -> 0
3453           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3454                                            MVT::i1);
3455         else if (Op1Unset)
3456           // nor(0, y) = ~y -> nor(y, y)
3457           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3458                                            MVT::i1, MachineNode->getOperand(1),
3459                                            MachineNode->getOperand(1));
3460         else if (Op2Unset)
3461           // nor(x, 0) = ~x
3462           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3463                                            MVT::i1, MachineNode->getOperand(0),
3464                                            MachineNode->getOperand(0));
3465         else if (Op1Not)
3466           // nor(~x, y) = andc(x, y)
3467           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3468                                            MVT::i1, MachineNode->getOperand(0).
3469                                                       getOperand(0),
3470                                            MachineNode->getOperand(1));
3471         else if (Op2Not)
3472           // nor(x, ~y) = andc(y, x)
3473           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3474                                            MVT::i1, MachineNode->getOperand(1).
3475                                                       getOperand(0),
3476                                            MachineNode->getOperand(0));
3477         else if (AllUsersSelectZero(MachineNode))
3478           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3479                                            MVT::i1, MachineNode->getOperand(0),
3480                                            MachineNode->getOperand(1)),
3481           SelectSwap = true;
3482         break;
3483       case PPC::CREQV:
3484         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3485           // eqv(x, x) = 1
3486           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3487                                            MVT::i1);
3488         else if (Op1Set)
3489           // eqv(1, y) = y
3490           ResNode = MachineNode->getOperand(1).getNode();
3491         else if (Op2Set)
3492           // eqv(x, 1) = x
3493           ResNode = MachineNode->getOperand(0).getNode();
3494         else if (Op1Unset)
3495           // eqv(0, y) = ~y -> nor(y, y)
3496           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3497                                            MVT::i1, MachineNode->getOperand(1),
3498                                            MachineNode->getOperand(1));
3499         else if (Op2Unset)
3500           // eqv(x, 0) = ~x
3501           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3502                                            MVT::i1, MachineNode->getOperand(0),
3503                                            MachineNode->getOperand(0));
3504         else if (Op1Not)
3505           // eqv(~x, y) = xor(x, y)
3506           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3507                                            MVT::i1, MachineNode->getOperand(0).
3508                                                       getOperand(0),
3509                                            MachineNode->getOperand(1));
3510         else if (Op2Not)
3511           // eqv(x, ~y) = xor(x, y)
3512           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3513                                            MVT::i1, MachineNode->getOperand(0),
3514                                            MachineNode->getOperand(1).
3515                                              getOperand(0));
3516         else if (AllUsersSelectZero(MachineNode))
3517           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3518                                            MVT::i1, MachineNode->getOperand(0),
3519                                            MachineNode->getOperand(1)),
3520           SelectSwap = true;
3521         break;
3522       case PPC::CRANDC:
3523         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3524           // andc(x, x) = 0
3525           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3526                                            MVT::i1);
3527         else if (Op1Set)
3528           // andc(1, y) = ~y
3529           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3530                                            MVT::i1, MachineNode->getOperand(1),
3531                                            MachineNode->getOperand(1));
3532         else if (Op1Unset || Op2Set)
3533           // andc(0, y) = andc(x, 1) = 0
3534           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3535                                            MVT::i1);
3536         else if (Op2Unset)
3537           // andc(x, 0) = x
3538           ResNode = MachineNode->getOperand(0).getNode();
3539         else if (Op1Not)
3540           // andc(~x, y) = ~(x | y) = nor(x, y)
3541           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3542                                            MVT::i1, MachineNode->getOperand(0).
3543                                                       getOperand(0),
3544                                            MachineNode->getOperand(1));
3545         else if (Op2Not)
3546           // andc(x, ~y) = x & y
3547           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3548                                            MVT::i1, MachineNode->getOperand(0),
3549                                            MachineNode->getOperand(1).
3550                                              getOperand(0));
3551         else if (AllUsersSelectZero(MachineNode))
3552           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3553                                            MVT::i1, MachineNode->getOperand(1),
3554                                            MachineNode->getOperand(0)),
3555           SelectSwap = true;
3556         break;
3557       case PPC::CRORC:
3558         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3559           // orc(x, x) = 1
3560           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3561                                            MVT::i1);
3562         else if (Op1Set || Op2Unset)
3563           // orc(1, y) = orc(x, 0) = 1
3564           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3565                                            MVT::i1);
3566         else if (Op2Set)
3567           // orc(x, 1) = x
3568           ResNode = MachineNode->getOperand(0).getNode();
3569         else if (Op1Unset)
3570           // orc(0, y) = ~y
3571           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3572                                            MVT::i1, MachineNode->getOperand(1),
3573                                            MachineNode->getOperand(1));
3574         else if (Op1Not)
3575           // orc(~x, y) = ~(x & y) = nand(x, y)
3576           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3577                                            MVT::i1, MachineNode->getOperand(0).
3578                                                       getOperand(0),
3579                                            MachineNode->getOperand(1));
3580         else if (Op2Not)
3581           // orc(x, ~y) = x | y
3582           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3583                                            MVT::i1, MachineNode->getOperand(0),
3584                                            MachineNode->getOperand(1).
3585                                              getOperand(0));
3586         else if (AllUsersSelectZero(MachineNode))
3587           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3588                                            MVT::i1, MachineNode->getOperand(1),
3589                                            MachineNode->getOperand(0)),
3590           SelectSwap = true;
3591         break;
3592       case PPC::SELECT_I4:
3593       case PPC::SELECT_I8:
3594       case PPC::SELECT_F4:
3595       case PPC::SELECT_F8:
3596       case PPC::SELECT_VRRC:
3597       case PPC::SELECT_VSFRC:
3598       case PPC::SELECT_VSRC:
3599         if (Op1Set)
3600           ResNode = MachineNode->getOperand(1).getNode();
3601         else if (Op1Unset)
3602           ResNode = MachineNode->getOperand(2).getNode();
3603         else if (Op1Not)
3604           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3605                                            SDLoc(MachineNode),
3606                                            MachineNode->getValueType(0),
3607                                            MachineNode->getOperand(0).
3608                                              getOperand(0),
3609                                            MachineNode->getOperand(2),
3610                                            MachineNode->getOperand(1));
3611         break;
3612       case PPC::BC:
3613       case PPC::BCn:
3614         if (Op1Not)
3615           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3616                                                                PPC::BC,
3617                                            SDLoc(MachineNode),
3618                                            MVT::Other,
3619                                            MachineNode->getOperand(0).
3620                                              getOperand(0),
3621                                            MachineNode->getOperand(1),
3622                                            MachineNode->getOperand(2));
3623         // FIXME: Handle Op1Set, Op1Unset here too.
3624         break;
3625       }
3626
3627       // If we're inverting this node because it is used only by selects that
3628       // we'd like to swap, then swap the selects before the node replacement.
3629       if (SelectSwap)
3630         SwapAllSelectUsers(MachineNode);
3631
3632       if (ResNode != MachineNode) {
3633         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
3634         DEBUG(MachineNode->dump(CurDAG));
3635         DEBUG(dbgs() << "\nNew: ");
3636         DEBUG(ResNode->dump(CurDAG));
3637         DEBUG(dbgs() << "\n");
3638
3639         ReplaceUses(MachineNode, ResNode);
3640         IsModified = true;
3641       }
3642     }
3643     if (IsModified)
3644       CurDAG->RemoveDeadNodes();
3645   } while (IsModified);
3646 }
3647
3648 // Gather the set of 32-bit operations that are known to have their
3649 // higher-order 32 bits zero, where ToPromote contains all such operations.
3650 static bool PeepholePPC64ZExtGather(SDValue Op32,
3651                                     SmallPtrSetImpl<SDNode *> &ToPromote) {
3652   if (!Op32.isMachineOpcode())
3653     return false;
3654
3655   // First, check for the "frontier" instructions (those that will clear the
3656   // higher-order 32 bits.
3657
3658   // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3659   // around. If it does not, then these instructions will clear the
3660   // higher-order bits.
3661   if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3662        Op32.getMachineOpcode() == PPC::RLWNM) &&
3663       Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3664     ToPromote.insert(Op32.getNode());
3665     return true;
3666   }
3667
3668   // SLW and SRW always clear the higher-order bits.
3669   if (Op32.getMachineOpcode() == PPC::SLW ||
3670       Op32.getMachineOpcode() == PPC::SRW) {
3671     ToPromote.insert(Op32.getNode());
3672     return true;
3673   }
3674
3675   // For LI and LIS, we need the immediate to be positive (so that it is not
3676   // sign extended).
3677   if (Op32.getMachineOpcode() == PPC::LI ||
3678       Op32.getMachineOpcode() == PPC::LIS) {
3679     if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3680       return false;
3681
3682     ToPromote.insert(Op32.getNode());
3683     return true;
3684   }
3685
3686   // Next, check for those instructions we can look through.
3687
3688   // Assuming the mask does not wrap around, then the higher-order bits are
3689   // taken directly from the first operand.
3690   if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3691       Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3692     SmallPtrSet<SDNode *, 16> ToPromote1;
3693     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3694       return false;
3695
3696     ToPromote.insert(Op32.getNode());
3697     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3698     return true;
3699   }
3700
3701   // For OR, the higher-order bits are zero if that is true for both operands.
3702   // For SELECT_I4, the same is true (but the relevant operand numbers are
3703   // shifted by 1).
3704   if (Op32.getMachineOpcode() == PPC::OR ||
3705       Op32.getMachineOpcode() == PPC::SELECT_I4) {
3706     unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3707     SmallPtrSet<SDNode *, 16> ToPromote1;
3708     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3709       return false;
3710     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3711       return false;
3712
3713     ToPromote.insert(Op32.getNode());
3714     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3715     return true;
3716   }
3717
3718   // For ORI and ORIS, we need the higher-order bits of the first operand to be
3719   // zero, and also for the constant to be positive (so that it is not sign
3720   // extended).
3721   if (Op32.getMachineOpcode() == PPC::ORI ||
3722       Op32.getMachineOpcode() == PPC::ORIS) {
3723     SmallPtrSet<SDNode *, 16> ToPromote1;
3724     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3725       return false;
3726     if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3727       return false;
3728
3729     ToPromote.insert(Op32.getNode());
3730     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3731     return true;
3732   }
3733
3734   // The higher-order bits of AND are zero if that is true for at least one of
3735   // the operands.
3736   if (Op32.getMachineOpcode() == PPC::AND) {
3737     SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3738     bool Op0OK =
3739       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3740     bool Op1OK =
3741       PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3742     if (!Op0OK && !Op1OK)
3743       return false;
3744
3745     ToPromote.insert(Op32.getNode());
3746
3747     if (Op0OK)
3748       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3749
3750     if (Op1OK)
3751       ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3752
3753     return true;
3754   }
3755
3756   // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3757   // of the first operand, or if the second operand is positive (so that it is
3758   // not sign extended).
3759   if (Op32.getMachineOpcode() == PPC::ANDIo ||
3760       Op32.getMachineOpcode() == PPC::ANDISo) {
3761     SmallPtrSet<SDNode *, 16> ToPromote1;
3762     bool Op0OK =
3763       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3764     bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3765     if (!Op0OK && !Op1OK)
3766       return false;
3767
3768     ToPromote.insert(Op32.getNode());
3769
3770     if (Op0OK)
3771       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3772
3773     return true;
3774   }
3775
3776   return false;
3777 }
3778
3779 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3780   if (!PPCSubTarget->isPPC64())
3781     return;
3782
3783   // When we zero-extend from i32 to i64, we use a pattern like this:
3784   // def : Pat<(i64 (zext i32:$in)),
3785   //           (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3786   //                   0, 32)>;
3787   // There are several 32-bit shift/rotate instructions, however, that will
3788   // clear the higher-order bits of their output, rendering the RLDICL
3789   // unnecessary. When that happens, we remove it here, and redefine the
3790   // relevant 32-bit operation to be a 64-bit operation.
3791
3792   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3793   ++Position;
3794
3795   bool MadeChange = false;
3796   while (Position != CurDAG->allnodes_begin()) {
3797     SDNode *N = --Position;
3798     // Skip dead nodes and any non-machine opcodes.
3799     if (N->use_empty() || !N->isMachineOpcode())
3800       continue;
3801
3802     if (N->getMachineOpcode() != PPC::RLDICL)
3803       continue;
3804
3805     if (N->getConstantOperandVal(1) != 0 ||
3806         N->getConstantOperandVal(2) != 32)
3807       continue;
3808
3809     SDValue ISR = N->getOperand(0);
3810     if (!ISR.isMachineOpcode() ||
3811         ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3812       continue;
3813
3814     if (!ISR.hasOneUse())
3815       continue;
3816
3817     if (ISR.getConstantOperandVal(2) != PPC::sub_32)
3818       continue;
3819
3820     SDValue IDef = ISR.getOperand(0);
3821     if (!IDef.isMachineOpcode() ||
3822         IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
3823       continue;
3824
3825     // We now know that we're looking at a canonical i32 -> i64 zext. See if we
3826     // can get rid of it.
3827
3828     SDValue Op32 = ISR->getOperand(1);
3829     if (!Op32.isMachineOpcode())
3830       continue;
3831
3832     // There are some 32-bit instructions that always clear the high-order 32
3833     // bits, there are also some instructions (like AND) that we can look
3834     // through.
3835     SmallPtrSet<SDNode *, 16> ToPromote;
3836     if (!PeepholePPC64ZExtGather(Op32, ToPromote))
3837       continue;
3838
3839     // If the ToPromote set contains nodes that have uses outside of the set
3840     // (except for the original INSERT_SUBREG), then abort the transformation.
3841     bool OutsideUse = false;
3842     for (SDNode *PN : ToPromote) {
3843       for (SDNode *UN : PN->uses()) {
3844         if (!ToPromote.count(UN) && UN != ISR.getNode()) {
3845           OutsideUse = true;
3846           break;
3847         }
3848       }
3849
3850       if (OutsideUse)
3851         break;
3852     }
3853     if (OutsideUse)
3854       continue;
3855
3856     MadeChange = true;
3857
3858     // We now know that this zero extension can be removed by promoting to
3859     // nodes in ToPromote to 64-bit operations, where for operations in the
3860     // frontier of the set, we need to insert INSERT_SUBREGs for their
3861     // operands.
3862     for (SDNode *PN : ToPromote) {
3863       unsigned NewOpcode;
3864       switch (PN->getMachineOpcode()) {
3865       default:
3866         llvm_unreachable("Don't know the 64-bit variant of this instruction");
3867       case PPC::RLWINM:    NewOpcode = PPC::RLWINM8; break;
3868       case PPC::RLWNM:     NewOpcode = PPC::RLWNM8; break;
3869       case PPC::SLW:       NewOpcode = PPC::SLW8; break;
3870       case PPC::SRW:       NewOpcode = PPC::SRW8; break;
3871       case PPC::LI:        NewOpcode = PPC::LI8; break;
3872       case PPC::LIS:       NewOpcode = PPC::LIS8; break;
3873       case PPC::RLWIMI:    NewOpcode = PPC::RLWIMI8; break;
3874       case PPC::OR:        NewOpcode = PPC::OR8; break;
3875       case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
3876       case PPC::ORI:       NewOpcode = PPC::ORI8; break;
3877       case PPC::ORIS:      NewOpcode = PPC::ORIS8; break;
3878       case PPC::AND:       NewOpcode = PPC::AND8; break;
3879       case PPC::ANDIo:     NewOpcode = PPC::ANDIo8; break;
3880       case PPC::ANDISo:    NewOpcode = PPC::ANDISo8; break;
3881       }
3882
3883       // Note: During the replacement process, the nodes will be in an
3884       // inconsistent state (some instructions will have operands with values
3885       // of the wrong type). Once done, however, everything should be right
3886       // again.
3887
3888       SmallVector<SDValue, 4> Ops;
3889       for (const SDValue &V : PN->ops()) {
3890         if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
3891             !isa<ConstantSDNode>(V)) {
3892           SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
3893           SDNode *ReplOp =
3894             CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
3895                                    ISR.getNode()->getVTList(), ReplOpOps);
3896           Ops.push_back(SDValue(ReplOp, 0));
3897         } else {
3898           Ops.push_back(V);
3899         }
3900       }
3901
3902       // Because all to-be-promoted nodes only have users that are other
3903       // promoted nodes (or the original INSERT_SUBREG), we can safely replace
3904       // the i32 result value type with i64.
3905
3906       SmallVector<EVT, 2> NewVTs;
3907       SDVTList VTs = PN->getVTList();
3908       for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
3909         if (VTs.VTs[i] == MVT::i32)
3910           NewVTs.push_back(MVT::i64);
3911         else
3912           NewVTs.push_back(VTs.VTs[i]);
3913
3914       DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld:    ");
3915       DEBUG(PN->dump(CurDAG));
3916
3917       CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
3918
3919       DEBUG(dbgs() << "\nNew: ");
3920       DEBUG(PN->dump(CurDAG));
3921       DEBUG(dbgs() << "\n");
3922     }
3923
3924     // Now we replace the original zero extend and its associated INSERT_SUBREG
3925     // with the value feeding the INSERT_SUBREG (which has now been promoted to
3926     // return an i64).
3927
3928     DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld:    ");
3929     DEBUG(N->dump(CurDAG));
3930     DEBUG(dbgs() << "\nNew: ");
3931     DEBUG(Op32.getNode()->dump(CurDAG));
3932     DEBUG(dbgs() << "\n");
3933
3934     ReplaceUses(N, Op32.getNode());
3935   }
3936
3937   if (MadeChange)
3938     CurDAG->RemoveDeadNodes();
3939 }
3940
3941 void PPCDAGToDAGISel::PeepholePPC64() {
3942   // These optimizations are currently supported only for 64-bit SVR4.
3943   if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
3944     return;
3945
3946   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3947   ++Position;
3948
3949   while (Position != CurDAG->allnodes_begin()) {
3950     SDNode *N = --Position;
3951     // Skip dead nodes and any non-machine opcodes.
3952     if (N->use_empty() || !N->isMachineOpcode())
3953       continue;
3954
3955     unsigned FirstOp;
3956     unsigned StorageOpcode = N->getMachineOpcode();
3957
3958     switch (StorageOpcode) {
3959     default: continue;
3960
3961     case PPC::LBZ:
3962     case PPC::LBZ8:
3963     case PPC::LD:
3964     case PPC::LFD:
3965     case PPC::LFS:
3966     case PPC::LHA:
3967     case PPC::LHA8:
3968     case PPC::LHZ:
3969     case PPC::LHZ8:
3970     case PPC::LWA:
3971     case PPC::LWZ:
3972     case PPC::LWZ8:
3973       FirstOp = 0;
3974       break;
3975
3976     case PPC::STB:
3977     case PPC::STB8:
3978     case PPC::STD:
3979     case PPC::STFD:
3980     case PPC::STFS:
3981     case PPC::STH:
3982     case PPC::STH8:
3983     case PPC::STW:
3984     case PPC::STW8:
3985       FirstOp = 1;
3986       break;
3987     }
3988
3989     // If this is a load or store with a zero offset, we may be able to
3990     // fold an add-immediate into the memory operation.
3991     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
3992         N->getConstantOperandVal(FirstOp) != 0)
3993       continue;
3994
3995     SDValue Base = N->getOperand(FirstOp + 1);
3996     if (!Base.isMachineOpcode())
3997       continue;
3998
3999     unsigned Flags = 0;
4000     bool ReplaceFlags = true;
4001
4002     // When the feeding operation is an add-immediate of some sort,
4003     // determine whether we need to add relocation information to the
4004     // target flags on the immediate operand when we fold it into the
4005     // load instruction.
4006     //
4007     // For something like ADDItocL, the relocation information is
4008     // inferred from the opcode; when we process it in the AsmPrinter,
4009     // we add the necessary relocation there.  A load, though, can receive
4010     // relocation from various flavors of ADDIxxx, so we need to carry
4011     // the relocation information in the target flags.
4012     switch (Base.getMachineOpcode()) {
4013     default: continue;
4014
4015     case PPC::ADDI8:
4016     case PPC::ADDI:
4017       // In some cases (such as TLS) the relocation information
4018       // is already in place on the operand, so copying the operand
4019       // is sufficient.
4020       ReplaceFlags = false;
4021       // For these cases, the immediate may not be divisible by 4, in
4022       // which case the fold is illegal for DS-form instructions.  (The
4023       // other cases provide aligned addresses and are always safe.)
4024       if ((StorageOpcode == PPC::LWA ||
4025            StorageOpcode == PPC::LD  ||
4026            StorageOpcode == PPC::STD) &&
4027           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4028            Base.getConstantOperandVal(1) % 4 != 0))
4029         continue;
4030       break;
4031     case PPC::ADDIdtprelL:
4032       Flags = PPCII::MO_DTPREL_LO;
4033       break;
4034     case PPC::ADDItlsldL:
4035       Flags = PPCII::MO_TLSLD_LO;
4036       break;
4037     case PPC::ADDItocL:
4038       Flags = PPCII::MO_TOC_LO;
4039       break;
4040     }
4041
4042     // We found an opportunity.  Reverse the operands from the add
4043     // immediate and substitute them into the load or store.  If
4044     // needed, update the target flags for the immediate operand to
4045     // reflect the necessary relocation information.
4046     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
4047     DEBUG(Base->dump(CurDAG));
4048     DEBUG(dbgs() << "\nN: ");
4049     DEBUG(N->dump(CurDAG));
4050     DEBUG(dbgs() << "\n");
4051
4052     SDValue ImmOpnd = Base.getOperand(1);
4053
4054     // If the relocation information isn't already present on the
4055     // immediate operand, add it now.
4056     if (ReplaceFlags) {
4057       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4058         SDLoc dl(GA);
4059         const GlobalValue *GV = GA->getGlobal();
4060         // We can't perform this optimization for data whose alignment
4061         // is insufficient for the instruction encoding.
4062         if (GV->getAlignment() < 4 &&
4063             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4064              StorageOpcode == PPC::LWA)) {
4065           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4066           continue;
4067         }
4068         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4069       } else if (ConstantPoolSDNode *CP =
4070                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4071         const Constant *C = CP->getConstVal();
4072         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4073                                                 CP->getAlignment(),
4074                                                 0, Flags);
4075       }
4076     }
4077
4078     if (FirstOp == 1) // Store
4079       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4080                                        Base.getOperand(0), N->getOperand(3));
4081     else // Load
4082       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4083                                        N->getOperand(2));
4084
4085     // The add-immediate may now be dead, in which case remove it.
4086     if (Base.getNode()->use_empty())
4087       CurDAG->RemoveDeadNode(Base.getNode());
4088   }
4089 }
4090
4091
4092 /// createPPCISelDag - This pass converts a legalized DAG into a
4093 /// PowerPC-specific DAG, ready for instruction scheduling.
4094 ///
4095 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4096   return new PPCDAGToDAGISel(TM);
4097 }
4098
4099 static void initializePassOnce(PassRegistry &Registry) {
4100   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4101   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4102                               nullptr, false, false);
4103   Registry.registerPass(*PI, true);
4104 }
4105
4106 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4107   CALL_ONCE_INITIALIZATION(initializePassOnce);
4108 }
4109