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