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