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