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