xref: /freebsd/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp (revision dd41de95a84d979615a2ef11df6850622bf6184e)
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a pattern matching instruction selector for PowerPC,
10 // converting from a legalized dag to a PPC dag.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/PPCMCTargetDesc.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCISelLowering.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/CodeGen/FunctionLoweringInfo.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SelectionDAGISel.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/KnownBits.h"
54 #include "llvm/Support/MachineValueType.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstdint>
60 #include <iterator>
61 #include <limits>
62 #include <memory>
63 #include <new>
64 #include <tuple>
65 #include <utility>
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "ppc-codegen"
70 
71 STATISTIC(NumSextSetcc,
72           "Number of (sext(setcc)) nodes expanded into GPR sequence.");
73 STATISTIC(NumZextSetcc,
74           "Number of (zext(setcc)) nodes expanded into GPR sequence.");
75 STATISTIC(SignExtensionsAdded,
76           "Number of sign extensions for compare inputs added.");
77 STATISTIC(ZeroExtensionsAdded,
78           "Number of zero extensions for compare inputs added.");
79 STATISTIC(NumLogicOpsOnComparison,
80           "Number of logical ops on i1 values calculated in GPR.");
81 STATISTIC(OmittedForNonExtendUses,
82           "Number of compares not eliminated as they have non-extending uses.");
83 STATISTIC(NumP9Setb,
84           "Number of compares lowered to setb.");
85 
86 // FIXME: Remove this once the bug has been fixed!
87 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
88 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
89 
90 static cl::opt<bool>
91     UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
92                        cl::desc("use aggressive ppc isel for bit permutations"),
93                        cl::Hidden);
94 static cl::opt<bool> BPermRewriterNoMasking(
95     "ppc-bit-perm-rewriter-stress-rotates",
96     cl::desc("stress rotate selection in aggressive ppc isel for "
97              "bit permutations"),
98     cl::Hidden);
99 
100 static cl::opt<bool> EnableBranchHint(
101   "ppc-use-branch-hint", cl::init(true),
102     cl::desc("Enable static hinting of branches on ppc"),
103     cl::Hidden);
104 
105 static cl::opt<bool> EnableTLSOpt(
106   "ppc-tls-opt", cl::init(true),
107     cl::desc("Enable tls optimization peephole"),
108     cl::Hidden);
109 
110 enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64,
111   ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32,
112   ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 };
113 
114 static cl::opt<ICmpInGPRType> CmpInGPR(
115   "ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All),
116   cl::desc("Specify the types of comparisons to emit GPR-only code for."),
117   cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."),
118              clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."),
119              clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."),
120              clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."),
121              clEnumValN(ICGPR_NonExtIn, "nonextin",
122                         "Only comparisons where inputs don't need [sz]ext."),
123              clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."),
124              clEnumValN(ICGPR_ZextI32, "zexti32",
125                         "Only i32 comparisons with zext result."),
126              clEnumValN(ICGPR_ZextI64, "zexti64",
127                         "Only i64 comparisons with zext result."),
128              clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."),
129              clEnumValN(ICGPR_SextI32, "sexti32",
130                         "Only i32 comparisons with sext result."),
131              clEnumValN(ICGPR_SextI64, "sexti64",
132                         "Only i64 comparisons with sext result.")));
133 namespace {
134 
135   //===--------------------------------------------------------------------===//
136   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
137   /// instructions for SelectionDAG operations.
138   ///
139   class PPCDAGToDAGISel : public SelectionDAGISel {
140     const PPCTargetMachine &TM;
141     const PPCSubtarget *PPCSubTarget = nullptr;
142     const PPCSubtarget *Subtarget = nullptr;
143     const PPCTargetLowering *PPCLowering = nullptr;
144     unsigned GlobalBaseReg = 0;
145 
146   public:
147     explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
148         : SelectionDAGISel(tm, OptLevel), TM(tm) {}
149 
150     bool runOnMachineFunction(MachineFunction &MF) override {
151       // Make sure we re-emit a set of the global base reg if necessary
152       GlobalBaseReg = 0;
153       PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
154       Subtarget = &MF.getSubtarget<PPCSubtarget>();
155       PPCLowering = Subtarget->getTargetLowering();
156       SelectionDAGISel::runOnMachineFunction(MF);
157 
158       if (!Subtarget->isSVR4ABI())
159         InsertVRSaveCode(MF);
160 
161       return true;
162     }
163 
164     void PreprocessISelDAG() override;
165     void PostprocessISelDAG() override;
166 
167     /// getI16Imm - Return a target constant with the specified value, of type
168     /// i16.
169     inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) {
170       return CurDAG->getTargetConstant(Imm, dl, MVT::i16);
171     }
172 
173     /// getI32Imm - Return a target constant with the specified value, of type
174     /// i32.
175     inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
176       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
177     }
178 
179     /// getI64Imm - Return a target constant with the specified value, of type
180     /// i64.
181     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
182       return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
183     }
184 
185     /// getSmallIPtrImm - Return a target constant of pointer type.
186     inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
187       return CurDAG->getTargetConstant(
188           Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
189     }
190 
191     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
192     /// rotate and mask opcode and mask operation.
193     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
194                                 unsigned &SH, unsigned &MB, unsigned &ME);
195 
196     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
197     /// base register.  Return the virtual register that holds this value.
198     SDNode *getGlobalBaseReg();
199 
200     void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
201 
202     // Select - Convert the specified operand from a target-independent to a
203     // target-specific node if it hasn't already been changed.
204     void Select(SDNode *N) override;
205 
206     bool tryBitfieldInsert(SDNode *N);
207     bool tryBitPermutation(SDNode *N);
208     bool tryIntCompareInGPR(SDNode *N);
209 
210     // tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into
211     // an X-Form load instruction with the offset being a relocation coming from
212     // the PPCISD::ADD_TLS.
213     bool tryTLSXFormLoad(LoadSDNode *N);
214     // tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into
215     // an X-Form store instruction with the offset being a relocation coming from
216     // the PPCISD::ADD_TLS.
217     bool tryTLSXFormStore(StoreSDNode *N);
218     /// SelectCC - Select a comparison of the specified values with the
219     /// specified condition code, returning the CR# of the expression.
220     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
221                      const SDLoc &dl);
222 
223     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
224     /// immediate field.  Note that the operand at this point is already the
225     /// result of a prior SelectAddressRegImm call.
226     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
227       if (N.getOpcode() == ISD::TargetConstant ||
228           N.getOpcode() == ISD::TargetGlobalAddress) {
229         Out = N;
230         return true;
231       }
232 
233       return false;
234     }
235 
236     /// SelectAddrIdx - Given the specified address, check to see if it can be
237     /// represented as an indexed [r+r] operation.
238     /// This is for xform instructions whose associated displacement form is D.
239     /// The last parameter \p 0 means associated D form has no requirment for 16
240     /// bit signed displacement.
241     /// Returns false if it can be represented by [r+imm], which are preferred.
242     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
243       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG, None);
244     }
245 
246     /// SelectAddrIdx4 - Given the specified address, check to see if it can be
247     /// represented as an indexed [r+r] operation.
248     /// This is for xform instructions whose associated displacement form is DS.
249     /// The last parameter \p 4 means associated DS form 16 bit signed
250     /// displacement must be a multiple of 4.
251     /// Returns false if it can be represented by [r+imm], which are preferred.
252     bool SelectAddrIdxX4(SDValue N, SDValue &Base, SDValue &Index) {
253       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
254                                               Align(4));
255     }
256 
257     /// SelectAddrIdx16 - Given the specified address, check to see if it can be
258     /// represented as an indexed [r+r] operation.
259     /// This is for xform instructions whose associated displacement form is DQ.
260     /// The last parameter \p 16 means associated DQ form 16 bit signed
261     /// displacement must be a multiple of 16.
262     /// Returns false if it can be represented by [r+imm], which are preferred.
263     bool SelectAddrIdxX16(SDValue N, SDValue &Base, SDValue &Index) {
264       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
265                                               Align(16));
266     }
267 
268     /// SelectAddrIdxOnly - Given the specified address, force it to be
269     /// represented as an indexed [r+r] operation.
270     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
271       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
272     }
273 
274     /// SelectAddrImm - Returns true if the address N can be represented by
275     /// a base register plus a signed 16-bit displacement [r+imm].
276     /// The last parameter \p 0 means D form has no requirment for 16 bit signed
277     /// displacement.
278     bool SelectAddrImm(SDValue N, SDValue &Disp,
279                        SDValue &Base) {
280       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, None);
281     }
282 
283     /// SelectAddrImmX4 - Returns true if the address N can be represented by
284     /// a base register plus a signed 16-bit displacement that is a multiple of
285     /// 4 (last parameter). Suitable for use by STD and friends.
286     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
287       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, Align(4));
288     }
289 
290     /// SelectAddrImmX16 - Returns true if the address N can be represented by
291     /// a base register plus a signed 16-bit displacement that is a multiple of
292     /// 16(last parameter). Suitable for use by STXV and friends.
293     bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
294       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG,
295                                               Align(16));
296     }
297 
298     // Select an address into a single register.
299     bool SelectAddr(SDValue N, SDValue &Base) {
300       Base = N;
301       return true;
302     }
303 
304     bool SelectAddrPCRel(SDValue N, SDValue &Base) {
305       return PPCLowering->SelectAddressPCRel(N, Base);
306     }
307 
308     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
309     /// inline asm expressions.  It is always correct to compute the value into
310     /// a register.  The case of adding a (possibly relocatable) constant to a
311     /// register can be improved, but it is wrong to substitute Reg+Reg for
312     /// Reg in an asm, because the load or store opcode would have to change.
313     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
314                                       unsigned ConstraintID,
315                                       std::vector<SDValue> &OutOps) override {
316       switch(ConstraintID) {
317       default:
318         errs() << "ConstraintID: " << ConstraintID << "\n";
319         llvm_unreachable("Unexpected asm memory constraint");
320       case InlineAsm::Constraint_es:
321       case InlineAsm::Constraint_m:
322       case InlineAsm::Constraint_o:
323       case InlineAsm::Constraint_Q:
324       case InlineAsm::Constraint_Z:
325       case InlineAsm::Constraint_Zy:
326         // We need to make sure that this one operand does not end up in r0
327         // (because we might end up lowering this as 0(%op)).
328         const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
329         const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
330         SDLoc dl(Op);
331         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
332         SDValue NewOp =
333           SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
334                                          dl, Op.getValueType(),
335                                          Op, RC), 0);
336 
337         OutOps.push_back(NewOp);
338         return false;
339       }
340       return true;
341     }
342 
343     void InsertVRSaveCode(MachineFunction &MF);
344 
345     StringRef getPassName() const override {
346       return "PowerPC DAG->DAG Pattern Instruction Selection";
347     }
348 
349 // Include the pieces autogenerated from the target description.
350 #include "PPCGenDAGISel.inc"
351 
352 private:
353     bool trySETCC(SDNode *N);
354     bool tryAsSingleRLDICL(SDNode *N);
355     bool tryAsSingleRLDICR(SDNode *N);
356     bool tryAsSingleRLWINM(SDNode *N);
357     bool tryAsSingleRLWINM8(SDNode *N);
358     bool tryAsSingleRLWIMI(SDNode *N);
359     bool tryAsPairOfRLDICL(SDNode *N);
360     bool tryAsSingleRLDIMI(SDNode *N);
361 
362     void PeepholePPC64();
363     void PeepholePPC64ZExt();
364     void PeepholeCROps();
365 
366     SDValue combineToCMPB(SDNode *N);
367     void foldBoolExts(SDValue &Res, SDNode *&N);
368 
369     bool AllUsersSelectZero(SDNode *N);
370     void SwapAllSelectUsers(SDNode *N);
371 
372     bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
373     void transferMemOperands(SDNode *N, SDNode *Result);
374   };
375 
376 } // end anonymous namespace
377 
378 /// InsertVRSaveCode - Once the entire function has been instruction selected,
379 /// all virtual registers are created and all machine instructions are built,
380 /// check to see if we need to save/restore VRSAVE.  If so, do it.
381 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
382   // Check to see if this function uses vector registers, which means we have to
383   // save and restore the VRSAVE register and update it with the regs we use.
384   //
385   // In this case, there will be virtual registers of vector type created
386   // by the scheduler.  Detect them now.
387   bool HasVectorVReg = false;
388   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
389     unsigned Reg = Register::index2VirtReg(i);
390     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
391       HasVectorVReg = true;
392       break;
393     }
394   }
395   if (!HasVectorVReg) return;  // nothing to do.
396 
397   // If we have a vector register, we want to emit code into the entry and exit
398   // blocks to save and restore the VRSAVE register.  We do this here (instead
399   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
400   //
401   // 1. This (trivially) reduces the load on the register allocator, by not
402   //    having to represent the live range of the VRSAVE register.
403   // 2. This (more significantly) allows us to create a temporary virtual
404   //    register to hold the saved VRSAVE value, allowing this temporary to be
405   //    register allocated, instead of forcing it to be spilled to the stack.
406 
407   // Create two vregs - one to hold the VRSAVE register that is live-in to the
408   // function and one for the value after having bits or'd into it.
409   Register InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
410   Register UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
411 
412   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
413   MachineBasicBlock &EntryBB = *Fn.begin();
414   DebugLoc dl;
415   // Emit the following code into the entry block:
416   // InVRSAVE = MFVRSAVE
417   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
418   // MTVRSAVE UpdatedVRSAVE
419   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
420   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
421   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
422           UpdatedVRSAVE).addReg(InVRSAVE);
423   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
424 
425   // Find all return blocks, outputting a restore in each epilog.
426   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
427     if (BB->isReturnBlock()) {
428       IP = BB->end(); --IP;
429 
430       // Skip over all terminator instructions, which are part of the return
431       // sequence.
432       MachineBasicBlock::iterator I2 = IP;
433       while (I2 != BB->begin() && (--I2)->isTerminator())
434         IP = I2;
435 
436       // Emit: MTVRSAVE InVRSave
437       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
438     }
439   }
440 }
441 
442 /// getGlobalBaseReg - Output the instructions required to put the
443 /// base address to use for accessing globals into a register.
444 ///
445 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
446   if (!GlobalBaseReg) {
447     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
448     // Insert the set of GlobalBaseReg into the first MBB of the function
449     MachineBasicBlock &FirstMBB = MF->front();
450     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
451     const Module *M = MF->getFunction().getParent();
452     DebugLoc dl;
453 
454     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
455       if (Subtarget->isTargetELF()) {
456         GlobalBaseReg = PPC::R30;
457         if (!Subtarget->isSecurePlt() &&
458             M->getPICLevel() == PICLevel::SmallPIC) {
459           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
460           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
461           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
462         } else {
463           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
464           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
465           Register TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
466           BuildMI(FirstMBB, MBBI, dl,
467                   TII.get(PPC::UpdateGBR), GlobalBaseReg)
468                   .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
469           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
470         }
471       } else {
472         GlobalBaseReg =
473           RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
474         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
475         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
476       }
477     } else {
478       // We must ensure that this sequence is dominated by the prologue.
479       // FIXME: This is a bit of a big hammer since we don't get the benefits
480       // of shrink-wrapping whenever we emit this instruction. Considering
481       // this is used in any function where we emit a jump table, this may be
482       // a significant limitation. We should consider inserting this in the
483       // block where it is used and then commoning this sequence up if it
484       // appears in multiple places.
485       // Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of
486       // MovePCtoLR8.
487       MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true);
488       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
489       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
490       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
491     }
492   }
493   return CurDAG->getRegister(GlobalBaseReg,
494                              PPCLowering->getPointerTy(CurDAG->getDataLayout()))
495       .getNode();
496 }
497 
498 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
499 /// operand. If so Imm will receive the 32-bit value.
500 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
501   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
502     Imm = cast<ConstantSDNode>(N)->getZExtValue();
503     return true;
504   }
505   return false;
506 }
507 
508 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
509 /// operand.  If so Imm will receive the 64-bit value.
510 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
511   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
512     Imm = cast<ConstantSDNode>(N)->getZExtValue();
513     return true;
514   }
515   return false;
516 }
517 
518 // isInt32Immediate - This method tests to see if a constant operand.
519 // If so Imm will receive the 32 bit value.
520 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
521   return isInt32Immediate(N.getNode(), Imm);
522 }
523 
524 /// isInt64Immediate - This method tests to see if the value is a 64-bit
525 /// constant operand. If so Imm will receive the 64-bit value.
526 static bool isInt64Immediate(SDValue N, uint64_t &Imm) {
527   return isInt64Immediate(N.getNode(), Imm);
528 }
529 
530 static unsigned getBranchHint(unsigned PCC,
531                               const FunctionLoweringInfo &FuncInfo,
532                               const SDValue &DestMBB) {
533   assert(isa<BasicBlockSDNode>(DestMBB));
534 
535   if (!FuncInfo.BPI) return PPC::BR_NO_HINT;
536 
537   const BasicBlock *BB = FuncInfo.MBB->getBasicBlock();
538   const Instruction *BBTerm = BB->getTerminator();
539 
540   if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
541 
542   const BasicBlock *TBB = BBTerm->getSuccessor(0);
543   const BasicBlock *FBB = BBTerm->getSuccessor(1);
544 
545   auto TProb = FuncInfo.BPI->getEdgeProbability(BB, TBB);
546   auto FProb = FuncInfo.BPI->getEdgeProbability(BB, FBB);
547 
548   // We only want to handle cases which are easy to predict at static time, e.g.
549   // C++ throw statement, that is very likely not taken, or calling never
550   // returned function, e.g. stdlib exit(). So we set Threshold to filter
551   // unwanted cases.
552   //
553   // Below is LLVM branch weight table, we only want to handle case 1, 2
554   //
555   // Case                  Taken:Nontaken  Example
556   // 1. Unreachable        1048575:1       C++ throw, stdlib exit(),
557   // 2. Invoke-terminating 1:1048575
558   // 3. Coldblock          4:64            __builtin_expect
559   // 4. Loop Branch        124:4           For loop
560   // 5. PH/ZH/FPH          20:12
561   const uint32_t Threshold = 10000;
562 
563   if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
564     return PPC::BR_NO_HINT;
565 
566   LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo.Fn->getName()
567                     << "::" << BB->getName() << "'\n"
568                     << " -> " << TBB->getName() << ": " << TProb << "\n"
569                     << " -> " << FBB->getName() << ": " << FProb << "\n");
570 
571   const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
572 
573   // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
574   // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
575   if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
576     std::swap(TProb, FProb);
577 
578   return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
579 }
580 
581 // isOpcWithIntImmediate - This method tests to see if the node is a specific
582 // opcode and that it has a immediate integer right operand.
583 // If so Imm will receive the 32 bit value.
584 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
585   return N->getOpcode() == Opc
586          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
587 }
588 
589 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
590   SDLoc dl(SN);
591   int FI = cast<FrameIndexSDNode>(N)->getIndex();
592   SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
593   unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
594   if (SN->hasOneUse())
595     CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
596                          getSmallIPtrImm(Offset, dl));
597   else
598     ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
599                                            getSmallIPtrImm(Offset, dl)));
600 }
601 
602 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
603                                       bool isShiftMask, unsigned &SH,
604                                       unsigned &MB, unsigned &ME) {
605   // Don't even go down this path for i64, since different logic will be
606   // necessary for rldicl/rldicr/rldimi.
607   if (N->getValueType(0) != MVT::i32)
608     return false;
609 
610   unsigned Shift  = 32;
611   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
612   unsigned Opcode = N->getOpcode();
613   if (N->getNumOperands() != 2 ||
614       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
615     return false;
616 
617   if (Opcode == ISD::SHL) {
618     // apply shift left to mask if it comes first
619     if (isShiftMask) Mask = Mask << Shift;
620     // determine which bits are made indeterminant by shift
621     Indeterminant = ~(0xFFFFFFFFu << Shift);
622   } else if (Opcode == ISD::SRL) {
623     // apply shift right to mask if it comes first
624     if (isShiftMask) Mask = Mask >> Shift;
625     // determine which bits are made indeterminant by shift
626     Indeterminant = ~(0xFFFFFFFFu >> Shift);
627     // adjust for the left rotate
628     Shift = 32 - Shift;
629   } else if (Opcode == ISD::ROTL) {
630     Indeterminant = 0;
631   } else {
632     return false;
633   }
634 
635   // if the mask doesn't intersect any Indeterminant bits
636   if (Mask && !(Mask & Indeterminant)) {
637     SH = Shift & 31;
638     // make sure the mask is still a mask (wrap arounds may not be)
639     return isRunOfOnes(Mask, MB, ME);
640   }
641   return false;
642 }
643 
644 bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) {
645   SDValue Base = ST->getBasePtr();
646   if (Base.getOpcode() != PPCISD::ADD_TLS)
647     return false;
648   SDValue Offset = ST->getOffset();
649   if (!Offset.isUndef())
650     return false;
651 
652   SDLoc dl(ST);
653   EVT MemVT = ST->getMemoryVT();
654   EVT RegVT = ST->getValue().getValueType();
655 
656   unsigned Opcode;
657   switch (MemVT.getSimpleVT().SimpleTy) {
658     default:
659       return false;
660     case MVT::i8: {
661       Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS;
662       break;
663     }
664     case MVT::i16: {
665       Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS;
666       break;
667     }
668     case MVT::i32: {
669       Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS;
670       break;
671     }
672     case MVT::i64: {
673       Opcode = PPC::STDXTLS;
674       break;
675     }
676   }
677   SDValue Chain = ST->getChain();
678   SDVTList VTs = ST->getVTList();
679   SDValue Ops[] = {ST->getValue(), Base.getOperand(0), Base.getOperand(1),
680                    Chain};
681   SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
682   transferMemOperands(ST, MN);
683   ReplaceNode(ST, MN);
684   return true;
685 }
686 
687 bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) {
688   SDValue Base = LD->getBasePtr();
689   if (Base.getOpcode() != PPCISD::ADD_TLS)
690     return false;
691   SDValue Offset = LD->getOffset();
692   if (!Offset.isUndef())
693     return false;
694 
695   SDLoc dl(LD);
696   EVT MemVT = LD->getMemoryVT();
697   EVT RegVT = LD->getValueType(0);
698   unsigned Opcode;
699   switch (MemVT.getSimpleVT().SimpleTy) {
700     default:
701       return false;
702     case MVT::i8: {
703       Opcode = (RegVT == MVT::i32) ? PPC::LBZXTLS_32 : PPC::LBZXTLS;
704       break;
705     }
706     case MVT::i16: {
707       Opcode = (RegVT == MVT::i32) ? PPC::LHZXTLS_32 : PPC::LHZXTLS;
708       break;
709     }
710     case MVT::i32: {
711       Opcode = (RegVT == MVT::i32) ? PPC::LWZXTLS_32 : PPC::LWZXTLS;
712       break;
713     }
714     case MVT::i64: {
715       Opcode = PPC::LDXTLS;
716       break;
717     }
718   }
719   SDValue Chain = LD->getChain();
720   SDVTList VTs = LD->getVTList();
721   SDValue Ops[] = {Base.getOperand(0), Base.getOperand(1), Chain};
722   SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
723   transferMemOperands(LD, MN);
724   ReplaceNode(LD, MN);
725   return true;
726 }
727 
728 /// Turn an or of two masked values into the rotate left word immediate then
729 /// mask insert (rlwimi) instruction.
730 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
731   SDValue Op0 = N->getOperand(0);
732   SDValue Op1 = N->getOperand(1);
733   SDLoc dl(N);
734 
735   KnownBits LKnown = CurDAG->computeKnownBits(Op0);
736   KnownBits RKnown = CurDAG->computeKnownBits(Op1);
737 
738   unsigned TargetMask = LKnown.Zero.getZExtValue();
739   unsigned InsertMask = RKnown.Zero.getZExtValue();
740 
741   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
742     unsigned Op0Opc = Op0.getOpcode();
743     unsigned Op1Opc = Op1.getOpcode();
744     unsigned Value, SH = 0;
745     TargetMask = ~TargetMask;
746     InsertMask = ~InsertMask;
747 
748     // If the LHS has a foldable shift and the RHS does not, then swap it to the
749     // RHS so that we can fold the shift into the insert.
750     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
751       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
752           Op0.getOperand(0).getOpcode() == ISD::SRL) {
753         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
754             Op1.getOperand(0).getOpcode() != ISD::SRL) {
755           std::swap(Op0, Op1);
756           std::swap(Op0Opc, Op1Opc);
757           std::swap(TargetMask, InsertMask);
758         }
759       }
760     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
761       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
762           Op1.getOperand(0).getOpcode() != ISD::SRL) {
763         std::swap(Op0, Op1);
764         std::swap(Op0Opc, Op1Opc);
765         std::swap(TargetMask, InsertMask);
766       }
767     }
768 
769     unsigned MB, ME;
770     if (isRunOfOnes(InsertMask, MB, ME)) {
771       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
772           isInt32Immediate(Op1.getOperand(1), Value)) {
773         Op1 = Op1.getOperand(0);
774         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
775       }
776       if (Op1Opc == ISD::AND) {
777        // The AND mask might not be a constant, and we need to make sure that
778        // if we're going to fold the masking with the insert, all bits not
779        // know to be zero in the mask are known to be one.
780         KnownBits MKnown = CurDAG->computeKnownBits(Op1.getOperand(1));
781         bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
782 
783         unsigned SHOpc = Op1.getOperand(0).getOpcode();
784         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
785             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
786           // Note that Value must be in range here (less than 32) because
787           // otherwise there would not be any bits set in InsertMask.
788           Op1 = Op1.getOperand(0).getOperand(0);
789           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
790         }
791       }
792 
793       SH &= 31;
794       SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
795                           getI32Imm(ME, dl) };
796       ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
797       return true;
798     }
799   }
800   return false;
801 }
802 
803 // Predict the number of instructions that would be generated by calling
804 // selectI64Imm(N).
805 static unsigned selectI64ImmInstrCountDirect(int64_t Imm) {
806   // Assume no remaining bits.
807   unsigned Remainder = 0;
808   // Assume no shift required.
809   unsigned Shift = 0;
810 
811   // If it can't be represented as a 32 bit value.
812   if (!isInt<32>(Imm)) {
813     Shift = countTrailingZeros<uint64_t>(Imm);
814     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
815 
816     // If the shifted value fits 32 bits.
817     if (isInt<32>(ImmSh)) {
818       // Go with the shifted value.
819       Imm = ImmSh;
820     } else {
821       // Still stuck with a 64 bit value.
822       Remainder = Imm;
823       Shift = 32;
824       Imm >>= 32;
825     }
826   }
827 
828   // Intermediate operand.
829   unsigned Result = 0;
830 
831   // Handle first 32 bits.
832   unsigned Lo = Imm & 0xFFFF;
833 
834   // Simple value.
835   if (isInt<16>(Imm)) {
836     // Just the Lo bits.
837     ++Result;
838   } else if (Lo) {
839     // Handle the Hi bits and Lo bits.
840     Result += 2;
841   } else {
842     // Just the Hi bits.
843     ++Result;
844   }
845 
846   // If no shift, we're done.
847   if (!Shift) return Result;
848 
849   // If Hi word == Lo word,
850   // we can use rldimi to insert the Lo word into Hi word.
851   if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
852     ++Result;
853     return Result;
854   }
855 
856   // Shift for next step if the upper 32-bits were not zero.
857   if (Imm)
858     ++Result;
859 
860   // Add in the last bits as required.
861   if ((Remainder >> 16) & 0xFFFF)
862     ++Result;
863   if (Remainder & 0xFFFF)
864     ++Result;
865 
866   return Result;
867 }
868 
869 static uint64_t Rot64(uint64_t Imm, unsigned R) {
870   return (Imm << R) | (Imm >> (64 - R));
871 }
872 
873 static unsigned selectI64ImmInstrCount(int64_t Imm) {
874   unsigned Count = selectI64ImmInstrCountDirect(Imm);
875 
876   // If the instruction count is 1 or 2, we do not need further analysis
877   // since rotate + load constant requires at least 2 instructions.
878   if (Count <= 2)
879     return Count;
880 
881   for (unsigned r = 1; r < 63; ++r) {
882     uint64_t RImm = Rot64(Imm, r);
883     unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1;
884     Count = std::min(Count, RCount);
885 
886     // See comments in selectI64Imm for an explanation of the logic below.
887     unsigned LS = findLastSet(RImm);
888     if (LS != r-1)
889       continue;
890 
891     uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
892     uint64_t RImmWithOnes = RImm | OnesMask;
893 
894     RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1;
895     Count = std::min(Count, RCount);
896   }
897 
898   return Count;
899 }
900 
901 // Select a 64-bit constant. For cost-modeling purposes, selectI64ImmInstrCount
902 // (above) needs to be kept in sync with this function.
903 static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl,
904                                   int64_t Imm) {
905   // Assume no remaining bits.
906   unsigned Remainder = 0;
907   // Assume no shift required.
908   unsigned Shift = 0;
909 
910   // If it can't be represented as a 32 bit value.
911   if (!isInt<32>(Imm)) {
912     Shift = countTrailingZeros<uint64_t>(Imm);
913     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
914 
915     // If the shifted value fits 32 bits.
916     if (isInt<32>(ImmSh)) {
917       // Go with the shifted value.
918       Imm = ImmSh;
919     } else {
920       // Still stuck with a 64 bit value.
921       Remainder = Imm;
922       Shift = 32;
923       Imm >>= 32;
924     }
925   }
926 
927   // Intermediate operand.
928   SDNode *Result;
929 
930   // Handle first 32 bits.
931   unsigned Lo = Imm & 0xFFFF;
932   unsigned Hi = (Imm >> 16) & 0xFFFF;
933 
934   auto getI32Imm = [CurDAG, dl](unsigned Imm) {
935       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
936   };
937 
938   // Simple value.
939   if (isInt<16>(Imm)) {
940     uint64_t SextImm = SignExtend64(Lo, 16);
941     SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
942     // Just the Lo bits.
943     Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);
944   } else if (Lo) {
945     // Handle the Hi bits.
946     unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
947     Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
948     // And Lo bits.
949     Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
950                                     SDValue(Result, 0), getI32Imm(Lo));
951   } else {
952     // Just the Hi bits.
953     Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
954   }
955 
956   // If no shift, we're done.
957   if (!Shift) return Result;
958 
959   // If Hi word == Lo word,
960   // we can use rldimi to insert the Lo word into Hi word.
961   if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
962     SDValue Ops[] =
963       { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
964     return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
965   }
966 
967   // Shift for next step if the upper 32-bits were not zero.
968   if (Imm) {
969     Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
970                                     SDValue(Result, 0),
971                                     getI32Imm(Shift),
972                                     getI32Imm(63 - Shift));
973   }
974 
975   // Add in the last bits as required.
976   if ((Hi = (Remainder >> 16) & 0xFFFF)) {
977     Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
978                                     SDValue(Result, 0), getI32Imm(Hi));
979   }
980   if ((Lo = Remainder & 0xFFFF)) {
981     Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
982                                     SDValue(Result, 0), getI32Imm(Lo));
983   }
984 
985   return Result;
986 }
987 
988 static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl,
989                             int64_t Imm) {
990   unsigned Count = selectI64ImmInstrCountDirect(Imm);
991 
992   // If the instruction count is 1 or 2, we do not need further analysis
993   // since rotate + load constant requires at least 2 instructions.
994   if (Count <= 2)
995     return selectI64ImmDirect(CurDAG, dl, Imm);
996 
997   unsigned RMin = 0;
998 
999   int64_t MatImm;
1000   unsigned MaskEnd;
1001 
1002   for (unsigned r = 1; r < 63; ++r) {
1003     uint64_t RImm = Rot64(Imm, r);
1004     unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1;
1005     if (RCount < Count) {
1006       Count = RCount;
1007       RMin = r;
1008       MatImm = RImm;
1009       MaskEnd = 63;
1010     }
1011 
1012     // If the immediate to generate has many trailing zeros, it might be
1013     // worthwhile to generate a rotated value with too many leading ones
1014     // (because that's free with li/lis's sign-extension semantics), and then
1015     // mask them off after rotation.
1016 
1017     unsigned LS = findLastSet(RImm);
1018     // We're adding (63-LS) higher-order ones, and we expect to mask them off
1019     // after performing the inverse rotation by (64-r). So we need that:
1020     //   63-LS == 64-r => LS == r-1
1021     if (LS != r-1)
1022       continue;
1023 
1024     uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
1025     uint64_t RImmWithOnes = RImm | OnesMask;
1026 
1027     RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1;
1028     if (RCount < Count) {
1029       Count = RCount;
1030       RMin = r;
1031       MatImm = RImmWithOnes;
1032       MaskEnd = LS;
1033     }
1034   }
1035 
1036   if (!RMin)
1037     return selectI64ImmDirect(CurDAG, dl, Imm);
1038 
1039   auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1040       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1041   };
1042 
1043   SDValue Val = SDValue(selectI64ImmDirect(CurDAG, dl, MatImm), 0);
1044   return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
1045                                 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
1046 }
1047 
1048 static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) {
1049   unsigned MaxTruncation = 0;
1050   // Cannot use range-based for loop here as we need the actual use (i.e. we
1051   // need the operand number corresponding to the use). A range-based for
1052   // will unbox the use and provide an SDNode*.
1053   for (SDNode::use_iterator Use = N->use_begin(), UseEnd = N->use_end();
1054        Use != UseEnd; ++Use) {
1055     unsigned Opc =
1056       Use->isMachineOpcode() ? Use->getMachineOpcode() : Use->getOpcode();
1057     switch (Opc) {
1058     default: return 0;
1059     case ISD::TRUNCATE:
1060       if (Use->isMachineOpcode())
1061         return 0;
1062       MaxTruncation =
1063         std::max(MaxTruncation, (unsigned)Use->getValueType(0).getSizeInBits());
1064       continue;
1065     case ISD::STORE: {
1066       if (Use->isMachineOpcode())
1067         return 0;
1068       StoreSDNode *STN = cast<StoreSDNode>(*Use);
1069       unsigned MemVTSize = STN->getMemoryVT().getSizeInBits();
1070       if (MemVTSize == 64 || Use.getOperandNo() != 0)
1071         return 0;
1072       MaxTruncation = std::max(MaxTruncation, MemVTSize);
1073       continue;
1074     }
1075     case PPC::STW8:
1076     case PPC::STWX8:
1077     case PPC::STWU8:
1078     case PPC::STWUX8:
1079       if (Use.getOperandNo() != 0)
1080         return 0;
1081       MaxTruncation = std::max(MaxTruncation, 32u);
1082       continue;
1083     case PPC::STH8:
1084     case PPC::STHX8:
1085     case PPC::STHU8:
1086     case PPC::STHUX8:
1087       if (Use.getOperandNo() != 0)
1088         return 0;
1089       MaxTruncation = std::max(MaxTruncation, 16u);
1090       continue;
1091     case PPC::STB8:
1092     case PPC::STBX8:
1093     case PPC::STBU8:
1094     case PPC::STBUX8:
1095       if (Use.getOperandNo() != 0)
1096         return 0;
1097       MaxTruncation = std::max(MaxTruncation, 8u);
1098       continue;
1099     }
1100   }
1101   return MaxTruncation;
1102 }
1103 
1104 // Select a 64-bit constant.
1105 static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) {
1106   SDLoc dl(N);
1107 
1108   // Get 64 bit value.
1109   int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
1110   if (unsigned MinSize = allUsesTruncate(CurDAG, N)) {
1111     uint64_t SextImm = SignExtend64(Imm, MinSize);
1112     SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
1113     if (isInt<16>(SextImm))
1114       return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);
1115   }
1116   return selectI64Imm(CurDAG, dl, Imm);
1117 }
1118 
1119 namespace {
1120 
1121 class BitPermutationSelector {
1122   struct ValueBit {
1123     SDValue V;
1124 
1125     // The bit number in the value, using a convention where bit 0 is the
1126     // lowest-order bit.
1127     unsigned Idx;
1128 
1129     // ConstZero means a bit we need to mask off.
1130     // Variable is a bit comes from an input variable.
1131     // VariableKnownToBeZero is also a bit comes from an input variable,
1132     // but it is known to be already zero. So we do not need to mask them.
1133     enum Kind {
1134       ConstZero,
1135       Variable,
1136       VariableKnownToBeZero
1137     } K;
1138 
1139     ValueBit(SDValue V, unsigned I, Kind K = Variable)
1140       : V(V), Idx(I), K(K) {}
1141     ValueBit(Kind K = Variable)
1142       : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
1143 
1144     bool isZero() const {
1145       return K == ConstZero || K == VariableKnownToBeZero;
1146     }
1147 
1148     bool hasValue() const {
1149       return K == Variable || K == VariableKnownToBeZero;
1150     }
1151 
1152     SDValue getValue() const {
1153       assert(hasValue() && "Cannot get the value of a constant bit");
1154       return V;
1155     }
1156 
1157     unsigned getValueBitIndex() const {
1158       assert(hasValue() && "Cannot get the value bit index of a constant bit");
1159       return Idx;
1160     }
1161   };
1162 
1163   // A bit group has the same underlying value and the same rotate factor.
1164   struct BitGroup {
1165     SDValue V;
1166     unsigned RLAmt;
1167     unsigned StartIdx, EndIdx;
1168 
1169     // This rotation amount assumes that the lower 32 bits of the quantity are
1170     // replicated in the high 32 bits by the rotation operator (which is done
1171     // by rlwinm and friends in 64-bit mode).
1172     bool Repl32;
1173     // Did converting to Repl32 == true change the rotation factor? If it did,
1174     // it decreased it by 32.
1175     bool Repl32CR;
1176     // Was this group coalesced after setting Repl32 to true?
1177     bool Repl32Coalesced;
1178 
1179     BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
1180       : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
1181         Repl32Coalesced(false) {
1182       LLVM_DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R
1183                         << " [" << S << ", " << E << "]\n");
1184     }
1185   };
1186 
1187   // Information on each (Value, RLAmt) pair (like the number of groups
1188   // associated with each) used to choose the lowering method.
1189   struct ValueRotInfo {
1190     SDValue V;
1191     unsigned RLAmt = std::numeric_limits<unsigned>::max();
1192     unsigned NumGroups = 0;
1193     unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
1194     bool Repl32 = false;
1195 
1196     ValueRotInfo() = default;
1197 
1198     // For sorting (in reverse order) by NumGroups, and then by
1199     // FirstGroupStartIdx.
1200     bool operator < (const ValueRotInfo &Other) const {
1201       // We need to sort so that the non-Repl32 come first because, when we're
1202       // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
1203       // masking operation.
1204       if (Repl32 < Other.Repl32)
1205         return true;
1206       else if (Repl32 > Other.Repl32)
1207         return false;
1208       else if (NumGroups > Other.NumGroups)
1209         return true;
1210       else if (NumGroups < Other.NumGroups)
1211         return false;
1212       else if (RLAmt == 0 && Other.RLAmt != 0)
1213         return true;
1214       else if (RLAmt != 0 && Other.RLAmt == 0)
1215         return false;
1216       else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
1217         return true;
1218       return false;
1219     }
1220   };
1221 
1222   using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
1223   using ValueBitsMemoizer =
1224       DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
1225   ValueBitsMemoizer Memoizer;
1226 
1227   // Return a pair of bool and a SmallVector pointer to a memoization entry.
1228   // The bool is true if something interesting was deduced, otherwise if we're
1229   // providing only a generic representation of V (or something else likewise
1230   // uninteresting for instruction selection) through the SmallVector.
1231   std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1232                                                             unsigned NumBits) {
1233     auto &ValueEntry = Memoizer[V];
1234     if (ValueEntry)
1235       return std::make_pair(ValueEntry->first, &ValueEntry->second);
1236     ValueEntry.reset(new ValueBitsMemoizedValue());
1237     bool &Interesting = ValueEntry->first;
1238     SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1239     Bits.resize(NumBits);
1240 
1241     switch (V.getOpcode()) {
1242     default: break;
1243     case ISD::ROTL:
1244       if (isa<ConstantSDNode>(V.getOperand(1))) {
1245         unsigned RotAmt = V.getConstantOperandVal(1);
1246 
1247         const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1248 
1249         for (unsigned i = 0; i < NumBits; ++i)
1250           Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1251 
1252         return std::make_pair(Interesting = true, &Bits);
1253       }
1254       break;
1255     case ISD::SHL:
1256       if (isa<ConstantSDNode>(V.getOperand(1))) {
1257         unsigned ShiftAmt = V.getConstantOperandVal(1);
1258 
1259         const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1260 
1261         for (unsigned i = ShiftAmt; i < NumBits; ++i)
1262           Bits[i] = LHSBits[i - ShiftAmt];
1263 
1264         for (unsigned i = 0; i < ShiftAmt; ++i)
1265           Bits[i] = ValueBit(ValueBit::ConstZero);
1266 
1267         return std::make_pair(Interesting = true, &Bits);
1268       }
1269       break;
1270     case ISD::SRL:
1271       if (isa<ConstantSDNode>(V.getOperand(1))) {
1272         unsigned ShiftAmt = V.getConstantOperandVal(1);
1273 
1274         const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1275 
1276         for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1277           Bits[i] = LHSBits[i + ShiftAmt];
1278 
1279         for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1280           Bits[i] = ValueBit(ValueBit::ConstZero);
1281 
1282         return std::make_pair(Interesting = true, &Bits);
1283       }
1284       break;
1285     case ISD::AND:
1286       if (isa<ConstantSDNode>(V.getOperand(1))) {
1287         uint64_t Mask = V.getConstantOperandVal(1);
1288 
1289         const SmallVector<ValueBit, 64> *LHSBits;
1290         // Mark this as interesting, only if the LHS was also interesting. This
1291         // prevents the overall procedure from matching a single immediate 'and'
1292         // (which is non-optimal because such an and might be folded with other
1293         // things if we don't select it here).
1294         std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1295 
1296         for (unsigned i = 0; i < NumBits; ++i)
1297           if (((Mask >> i) & 1) == 1)
1298             Bits[i] = (*LHSBits)[i];
1299           else {
1300             // AND instruction masks this bit. If the input is already zero,
1301             // we have nothing to do here. Otherwise, make the bit ConstZero.
1302             if ((*LHSBits)[i].isZero())
1303               Bits[i] = (*LHSBits)[i];
1304             else
1305               Bits[i] = ValueBit(ValueBit::ConstZero);
1306           }
1307 
1308         return std::make_pair(Interesting, &Bits);
1309       }
1310       break;
1311     case ISD::OR: {
1312       const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1313       const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1314 
1315       bool AllDisjoint = true;
1316       SDValue LastVal = SDValue();
1317       unsigned LastIdx = 0;
1318       for (unsigned i = 0; i < NumBits; ++i) {
1319         if (LHSBits[i].isZero() && RHSBits[i].isZero()) {
1320           // If both inputs are known to be zero and one is ConstZero and
1321           // another is VariableKnownToBeZero, we can select whichever
1322           // we like. To minimize the number of bit groups, we select
1323           // VariableKnownToBeZero if this bit is the next bit of the same
1324           // input variable from the previous bit. Otherwise, we select
1325           // ConstZero.
1326           if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal &&
1327               LHSBits[i].getValueBitIndex() == LastIdx + 1)
1328             Bits[i] = LHSBits[i];
1329           else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal &&
1330                    RHSBits[i].getValueBitIndex() == LastIdx + 1)
1331             Bits[i] = RHSBits[i];
1332           else
1333             Bits[i] = ValueBit(ValueBit::ConstZero);
1334         }
1335         else if (LHSBits[i].isZero())
1336           Bits[i] = RHSBits[i];
1337         else if (RHSBits[i].isZero())
1338           Bits[i] = LHSBits[i];
1339         else {
1340           AllDisjoint = false;
1341           break;
1342         }
1343         // We remember the value and bit index of this bit.
1344         if (Bits[i].hasValue()) {
1345           LastVal = Bits[i].getValue();
1346           LastIdx = Bits[i].getValueBitIndex();
1347         }
1348         else {
1349           if (LastVal) LastVal = SDValue();
1350           LastIdx = 0;
1351         }
1352       }
1353 
1354       if (!AllDisjoint)
1355         break;
1356 
1357       return std::make_pair(Interesting = true, &Bits);
1358     }
1359     case ISD::ZERO_EXTEND: {
1360       // We support only the case with zero extension from i32 to i64 so far.
1361       if (V.getValueType() != MVT::i64 ||
1362           V.getOperand(0).getValueType() != MVT::i32)
1363         break;
1364 
1365       const SmallVector<ValueBit, 64> *LHSBits;
1366       const unsigned NumOperandBits = 32;
1367       std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1368                                                     NumOperandBits);
1369 
1370       for (unsigned i = 0; i < NumOperandBits; ++i)
1371         Bits[i] = (*LHSBits)[i];
1372 
1373       for (unsigned i = NumOperandBits; i < NumBits; ++i)
1374         Bits[i] = ValueBit(ValueBit::ConstZero);
1375 
1376       return std::make_pair(Interesting, &Bits);
1377     }
1378     case ISD::TRUNCATE: {
1379       EVT FromType = V.getOperand(0).getValueType();
1380       EVT ToType = V.getValueType();
1381       // We support only the case with truncate from i64 to i32.
1382       if (FromType != MVT::i64 || ToType != MVT::i32)
1383         break;
1384       const unsigned NumAllBits = FromType.getSizeInBits();
1385       SmallVector<ValueBit, 64> *InBits;
1386       std::tie(Interesting, InBits) = getValueBits(V.getOperand(0),
1387                                                     NumAllBits);
1388       const unsigned NumValidBits = ToType.getSizeInBits();
1389 
1390       // A 32-bit instruction cannot touch upper 32-bit part of 64-bit value.
1391       // So, we cannot include this truncate.
1392       bool UseUpper32bit = false;
1393       for (unsigned i = 0; i < NumValidBits; ++i)
1394         if ((*InBits)[i].hasValue() && (*InBits)[i].getValueBitIndex() >= 32) {
1395           UseUpper32bit = true;
1396           break;
1397         }
1398       if (UseUpper32bit)
1399         break;
1400 
1401       for (unsigned i = 0; i < NumValidBits; ++i)
1402         Bits[i] = (*InBits)[i];
1403 
1404       return std::make_pair(Interesting, &Bits);
1405     }
1406     case ISD::AssertZext: {
1407       // For AssertZext, we look through the operand and
1408       // mark the bits known to be zero.
1409       const SmallVector<ValueBit, 64> *LHSBits;
1410       std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1411                                                     NumBits);
1412 
1413       EVT FromType = cast<VTSDNode>(V.getOperand(1))->getVT();
1414       const unsigned NumValidBits = FromType.getSizeInBits();
1415       for (unsigned i = 0; i < NumValidBits; ++i)
1416         Bits[i] = (*LHSBits)[i];
1417 
1418       // These bits are known to be zero but the AssertZext may be from a value
1419       // that already has some constant zero bits (i.e. from a masking and).
1420       for (unsigned i = NumValidBits; i < NumBits; ++i)
1421         Bits[i] = (*LHSBits)[i].hasValue()
1422                       ? ValueBit((*LHSBits)[i].getValue(),
1423                                  (*LHSBits)[i].getValueBitIndex(),
1424                                  ValueBit::VariableKnownToBeZero)
1425                       : ValueBit(ValueBit::ConstZero);
1426 
1427       return std::make_pair(Interesting, &Bits);
1428     }
1429     case ISD::LOAD:
1430       LoadSDNode *LD = cast<LoadSDNode>(V);
1431       if (ISD::isZEXTLoad(V.getNode()) && V.getResNo() == 0) {
1432         EVT VT = LD->getMemoryVT();
1433         const unsigned NumValidBits = VT.getSizeInBits();
1434 
1435         for (unsigned i = 0; i < NumValidBits; ++i)
1436           Bits[i] = ValueBit(V, i);
1437 
1438         // These bits are known to be zero.
1439         for (unsigned i = NumValidBits; i < NumBits; ++i)
1440           Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero);
1441 
1442         // Zero-extending load itself cannot be optimized. So, it is not
1443         // interesting by itself though it gives useful information.
1444         return std::make_pair(Interesting = false, &Bits);
1445       }
1446       break;
1447     }
1448 
1449     for (unsigned i = 0; i < NumBits; ++i)
1450       Bits[i] = ValueBit(V, i);
1451 
1452     return std::make_pair(Interesting = false, &Bits);
1453   }
1454 
1455   // For each value (except the constant ones), compute the left-rotate amount
1456   // to get it from its original to final position.
1457   void computeRotationAmounts() {
1458     NeedMask = false;
1459     RLAmt.resize(Bits.size());
1460     for (unsigned i = 0; i < Bits.size(); ++i)
1461       if (Bits[i].hasValue()) {
1462         unsigned VBI = Bits[i].getValueBitIndex();
1463         if (i >= VBI)
1464           RLAmt[i] = i - VBI;
1465         else
1466           RLAmt[i] = Bits.size() - (VBI - i);
1467       } else if (Bits[i].isZero()) {
1468         NeedMask = true;
1469         RLAmt[i] = UINT32_MAX;
1470       } else {
1471         llvm_unreachable("Unknown value bit type");
1472       }
1473   }
1474 
1475   // Collect groups of consecutive bits with the same underlying value and
1476   // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1477   // they break up groups.
1478   void collectBitGroups(bool LateMask) {
1479     BitGroups.clear();
1480 
1481     unsigned LastRLAmt = RLAmt[0];
1482     SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1483     unsigned LastGroupStartIdx = 0;
1484     bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1485     for (unsigned i = 1; i < Bits.size(); ++i) {
1486       unsigned ThisRLAmt = RLAmt[i];
1487       SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1488       if (LateMask && !ThisValue) {
1489         ThisValue = LastValue;
1490         ThisRLAmt = LastRLAmt;
1491         // If we're doing late masking, then the first bit group always starts
1492         // at zero (even if the first bits were zero).
1493         if (BitGroups.empty())
1494           LastGroupStartIdx = 0;
1495       }
1496 
1497       // If this bit is known to be zero and the current group is a bit group
1498       // of zeros, we do not need to terminate the current bit group even the
1499       // Value or RLAmt does not match here. Instead, we terminate this group
1500       // when the first non-zero bit appears later.
1501       if (IsGroupOfZeros && Bits[i].isZero())
1502         continue;
1503 
1504       // If this bit has the same underlying value and the same rotate factor as
1505       // the last one, then they're part of the same group.
1506       if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1507         // We cannot continue the current group if this bits is not known to
1508         // be zero in a bit group of zeros.
1509         if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero()))
1510           continue;
1511 
1512       if (LastValue.getNode())
1513         BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1514                                      i-1));
1515       LastRLAmt = ThisRLAmt;
1516       LastValue = ThisValue;
1517       LastGroupStartIdx = i;
1518       IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1519     }
1520     if (LastValue.getNode())
1521       BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1522                                    Bits.size()-1));
1523 
1524     if (BitGroups.empty())
1525       return;
1526 
1527     // We might be able to combine the first and last groups.
1528     if (BitGroups.size() > 1) {
1529       // If the first and last groups are the same, then remove the first group
1530       // in favor of the last group, making the ending index of the last group
1531       // equal to the ending index of the to-be-removed first group.
1532       if (BitGroups[0].StartIdx == 0 &&
1533           BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1534           BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1535           BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1536         LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1537         BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1538         BitGroups.erase(BitGroups.begin());
1539       }
1540     }
1541   }
1542 
1543   // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1544   // associated with each. If the number of groups are same, we prefer a group
1545   // which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate
1546   // instruction. If there is a degeneracy, pick the one that occurs
1547   // first (in the final value).
1548   void collectValueRotInfo() {
1549     ValueRots.clear();
1550 
1551     for (auto &BG : BitGroups) {
1552       unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1553       ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1554       VRI.V = BG.V;
1555       VRI.RLAmt = BG.RLAmt;
1556       VRI.Repl32 = BG.Repl32;
1557       VRI.NumGroups += 1;
1558       VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1559     }
1560 
1561     // Now that we've collected the various ValueRotInfo instances, we need to
1562     // sort them.
1563     ValueRotsVec.clear();
1564     for (auto &I : ValueRots) {
1565       ValueRotsVec.push_back(I.second);
1566     }
1567     llvm::sort(ValueRotsVec);
1568   }
1569 
1570   // In 64-bit mode, rlwinm and friends have a rotation operator that
1571   // replicates the low-order 32 bits into the high-order 32-bits. The mask
1572   // indices of these instructions can only be in the lower 32 bits, so they
1573   // can only represent some 64-bit bit groups. However, when they can be used,
1574   // the 32-bit replication can be used to represent, as a single bit group,
1575   // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1576   // groups when possible. Returns true if any of the bit groups were
1577   // converted.
1578   void assignRepl32BitGroups() {
1579     // If we have bits like this:
1580     //
1581     // Indices:    15 14 13 12 11 10 9 8  7  6  5  4  3  2  1  0
1582     // V bits: ... 7  6  5  4  3  2  1 0 31 30 29 28 27 26 25 24
1583     // Groups:    |      RLAmt = 8      |      RLAmt = 40       |
1584     //
1585     // But, making use of a 32-bit operation that replicates the low-order 32
1586     // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1587     // of 8.
1588 
1589     auto IsAllLow32 = [this](BitGroup & BG) {
1590       if (BG.StartIdx <= BG.EndIdx) {
1591         for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1592           if (!Bits[i].hasValue())
1593             continue;
1594           if (Bits[i].getValueBitIndex() >= 32)
1595             return false;
1596         }
1597       } else {
1598         for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1599           if (!Bits[i].hasValue())
1600             continue;
1601           if (Bits[i].getValueBitIndex() >= 32)
1602             return false;
1603         }
1604         for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1605           if (!Bits[i].hasValue())
1606             continue;
1607           if (Bits[i].getValueBitIndex() >= 32)
1608             return false;
1609         }
1610       }
1611 
1612       return true;
1613     };
1614 
1615     for (auto &BG : BitGroups) {
1616       // If this bit group has RLAmt of 0 and will not be merged with
1617       // another bit group, we don't benefit from Repl32. We don't mark
1618       // such group to give more freedom for later instruction selection.
1619       if (BG.RLAmt == 0) {
1620         auto PotentiallyMerged = [this](BitGroup & BG) {
1621           for (auto &BG2 : BitGroups)
1622             if (&BG != &BG2 && BG.V == BG2.V &&
1623                 (BG2.RLAmt == 0 || BG2.RLAmt == 32))
1624               return true;
1625           return false;
1626         };
1627         if (!PotentiallyMerged(BG))
1628           continue;
1629       }
1630       if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1631         if (IsAllLow32(BG)) {
1632           if (BG.RLAmt >= 32) {
1633             BG.RLAmt -= 32;
1634             BG.Repl32CR = true;
1635           }
1636 
1637           BG.Repl32 = true;
1638 
1639           LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for "
1640                             << BG.V.getNode() << " RLAmt = " << BG.RLAmt << " ["
1641                             << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1642         }
1643       }
1644     }
1645 
1646     // Now walk through the bit groups, consolidating where possible.
1647     for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1648       // We might want to remove this bit group by merging it with the previous
1649       // group (which might be the ending group).
1650       auto IP = (I == BitGroups.begin()) ?
1651                 std::prev(BitGroups.end()) : std::prev(I);
1652       if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1653           I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1654 
1655         LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for "
1656                           << I->V.getNode() << " RLAmt = " << I->RLAmt << " ["
1657                           << I->StartIdx << ", " << I->EndIdx
1658                           << "] with group with range [" << IP->StartIdx << ", "
1659                           << IP->EndIdx << "]\n");
1660 
1661         IP->EndIdx = I->EndIdx;
1662         IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1663         IP->Repl32Coalesced = true;
1664         I = BitGroups.erase(I);
1665         continue;
1666       } else {
1667         // There is a special case worth handling: If there is a single group
1668         // covering the entire upper 32 bits, and it can be merged with both
1669         // the next and previous groups (which might be the same group), then
1670         // do so. If it is the same group (so there will be only one group in
1671         // total), then we need to reverse the order of the range so that it
1672         // covers the entire 64 bits.
1673         if (I->StartIdx == 32 && I->EndIdx == 63) {
1674           assert(std::next(I) == BitGroups.end() &&
1675                  "bit group ends at index 63 but there is another?");
1676           auto IN = BitGroups.begin();
1677 
1678           if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1679               (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1680               IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1681               IsAllLow32(*I)) {
1682 
1683             LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode()
1684                               << " RLAmt = " << I->RLAmt << " [" << I->StartIdx
1685                               << ", " << I->EndIdx
1686                               << "] with 32-bit replicated groups with ranges ["
1687                               << IP->StartIdx << ", " << IP->EndIdx << "] and ["
1688                               << IN->StartIdx << ", " << IN->EndIdx << "]\n");
1689 
1690             if (IP == IN) {
1691               // There is only one other group; change it to cover the whole
1692               // range (backward, so that it can still be Repl32 but cover the
1693               // whole 64-bit range).
1694               IP->StartIdx = 31;
1695               IP->EndIdx = 30;
1696               IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1697               IP->Repl32Coalesced = true;
1698               I = BitGroups.erase(I);
1699             } else {
1700               // There are two separate groups, one before this group and one
1701               // after us (at the beginning). We're going to remove this group,
1702               // but also the group at the very beginning.
1703               IP->EndIdx = IN->EndIdx;
1704               IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1705               IP->Repl32Coalesced = true;
1706               I = BitGroups.erase(I);
1707               BitGroups.erase(BitGroups.begin());
1708             }
1709 
1710             // This must be the last group in the vector (and we might have
1711             // just invalidated the iterator above), so break here.
1712             break;
1713           }
1714         }
1715       }
1716 
1717       ++I;
1718     }
1719   }
1720 
1721   SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
1722     return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1723   }
1724 
1725   uint64_t getZerosMask() {
1726     uint64_t Mask = 0;
1727     for (unsigned i = 0; i < Bits.size(); ++i) {
1728       if (Bits[i].hasValue())
1729         continue;
1730       Mask |= (UINT64_C(1) << i);
1731     }
1732 
1733     return ~Mask;
1734   }
1735 
1736   // This method extends an input value to 64 bit if input is 32-bit integer.
1737   // While selecting instructions in BitPermutationSelector in 64-bit mode,
1738   // an input value can be a 32-bit integer if a ZERO_EXTEND node is included.
1739   // In such case, we extend it to 64 bit to be consistent with other values.
1740   SDValue ExtendToInt64(SDValue V, const SDLoc &dl) {
1741     if (V.getValueSizeInBits() == 64)
1742       return V;
1743 
1744     assert(V.getValueSizeInBits() == 32);
1745     SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
1746     SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
1747                                                    MVT::i64), 0);
1748     SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
1749                                                     MVT::i64, ImDef, V,
1750                                                     SubRegIdx), 0);
1751     return ExtVal;
1752   }
1753 
1754   SDValue TruncateToInt32(SDValue V, const SDLoc &dl) {
1755     if (V.getValueSizeInBits() == 32)
1756       return V;
1757 
1758     assert(V.getValueSizeInBits() == 64);
1759     SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
1760     SDValue SubVal = SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl,
1761                                                     MVT::i32, V, SubRegIdx), 0);
1762     return SubVal;
1763   }
1764 
1765   // Depending on the number of groups for a particular value, it might be
1766   // better to rotate, mask explicitly (using andi/andis), and then or the
1767   // result. Select this part of the result first.
1768   void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1769     if (BPermRewriterNoMasking)
1770       return;
1771 
1772     for (ValueRotInfo &VRI : ValueRotsVec) {
1773       unsigned Mask = 0;
1774       for (unsigned i = 0; i < Bits.size(); ++i) {
1775         if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1776           continue;
1777         if (RLAmt[i] != VRI.RLAmt)
1778           continue;
1779         Mask |= (1u << i);
1780       }
1781 
1782       // Compute the masks for andi/andis that would be necessary.
1783       unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1784       assert((ANDIMask != 0 || ANDISMask != 0) &&
1785              "No set bits in mask for value bit groups");
1786       bool NeedsRotate = VRI.RLAmt != 0;
1787 
1788       // We're trying to minimize the number of instructions. If we have one
1789       // group, using one of andi/andis can break even.  If we have three
1790       // groups, we can use both andi and andis and break even (to use both
1791       // andi and andis we also need to or the results together). We need four
1792       // groups if we also need to rotate. To use andi/andis we need to do more
1793       // than break even because rotate-and-mask instructions tend to be easier
1794       // to schedule.
1795 
1796       // FIXME: We've biased here against using andi/andis, which is right for
1797       // POWER cores, but not optimal everywhere. For example, on the A2,
1798       // andi/andis have single-cycle latency whereas the rotate-and-mask
1799       // instructions take two cycles, and it would be better to bias toward
1800       // andi/andis in break-even cases.
1801 
1802       unsigned NumAndInsts = (unsigned) NeedsRotate +
1803                              (unsigned) (ANDIMask != 0) +
1804                              (unsigned) (ANDISMask != 0) +
1805                              (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1806                              (unsigned) (bool) Res;
1807 
1808       LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
1809                         << " RL: " << VRI.RLAmt << ":"
1810                         << "\n\t\t\tisel using masking: " << NumAndInsts
1811                         << " using rotates: " << VRI.NumGroups << "\n");
1812 
1813       if (NumAndInsts >= VRI.NumGroups)
1814         continue;
1815 
1816       LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1817 
1818       if (InstCnt) *InstCnt += NumAndInsts;
1819 
1820       SDValue VRot;
1821       if (VRI.RLAmt) {
1822         SDValue Ops[] =
1823           { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
1824             getI32Imm(0, dl), getI32Imm(31, dl) };
1825         VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1826                                               Ops), 0);
1827       } else {
1828         VRot = TruncateToInt32(VRI.V, dl);
1829       }
1830 
1831       SDValue ANDIVal, ANDISVal;
1832       if (ANDIMask != 0)
1833         ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
1834                                                  VRot, getI32Imm(ANDIMask, dl)),
1835                           0);
1836       if (ANDISMask != 0)
1837         ANDISVal =
1838             SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, VRot,
1839                                            getI32Imm(ANDISMask, dl)),
1840                     0);
1841 
1842       SDValue TotalVal;
1843       if (!ANDIVal)
1844         TotalVal = ANDISVal;
1845       else if (!ANDISVal)
1846         TotalVal = ANDIVal;
1847       else
1848         TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1849                              ANDIVal, ANDISVal), 0);
1850 
1851       if (!Res)
1852         Res = TotalVal;
1853       else
1854         Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1855                         Res, TotalVal), 0);
1856 
1857       // Now, remove all groups with this underlying value and rotation
1858       // factor.
1859       eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1860         return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1861       });
1862     }
1863   }
1864 
1865   // Instruction selection for the 32-bit case.
1866   SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1867     SDLoc dl(N);
1868     SDValue Res;
1869 
1870     if (InstCnt) *InstCnt = 0;
1871 
1872     // Take care of cases that should use andi/andis first.
1873     SelectAndParts32(dl, Res, InstCnt);
1874 
1875     // If we've not yet selected a 'starting' instruction, and we have no zeros
1876     // to fill in, select the (Value, RLAmt) with the highest priority (largest
1877     // number of groups), and start with this rotated value.
1878     if ((!NeedMask || LateMask) && !Res) {
1879       ValueRotInfo &VRI = ValueRotsVec[0];
1880       if (VRI.RLAmt) {
1881         if (InstCnt) *InstCnt += 1;
1882         SDValue Ops[] =
1883           { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
1884             getI32Imm(0, dl), getI32Imm(31, dl) };
1885         Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1886                       0);
1887       } else {
1888         Res = TruncateToInt32(VRI.V, dl);
1889       }
1890 
1891       // Now, remove all groups with this underlying value and rotation factor.
1892       eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1893         return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1894       });
1895     }
1896 
1897     if (InstCnt) *InstCnt += BitGroups.size();
1898 
1899     // Insert the other groups (one at a time).
1900     for (auto &BG : BitGroups) {
1901       if (!Res) {
1902         SDValue Ops[] =
1903           { TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
1904             getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1905             getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1906         Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1907       } else {
1908         SDValue Ops[] =
1909           { Res, TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
1910               getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1911             getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1912         Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1913       }
1914     }
1915 
1916     if (LateMask) {
1917       unsigned Mask = (unsigned) getZerosMask();
1918 
1919       unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1920       assert((ANDIMask != 0 || ANDISMask != 0) &&
1921              "No set bits in zeros mask?");
1922 
1923       if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1924                                (unsigned) (ANDISMask != 0) +
1925                                (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1926 
1927       SDValue ANDIVal, ANDISVal;
1928       if (ANDIMask != 0)
1929         ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
1930                                                  Res, getI32Imm(ANDIMask, dl)),
1931                           0);
1932       if (ANDISMask != 0)
1933         ANDISVal =
1934             SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, Res,
1935                                            getI32Imm(ANDISMask, dl)),
1936                     0);
1937 
1938       if (!ANDIVal)
1939         Res = ANDISVal;
1940       else if (!ANDISVal)
1941         Res = ANDIVal;
1942       else
1943         Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1944                         ANDIVal, ANDISVal), 0);
1945     }
1946 
1947     return Res.getNode();
1948   }
1949 
1950   unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1951                                 unsigned MaskStart, unsigned MaskEnd,
1952                                 bool IsIns) {
1953     // In the notation used by the instructions, 'start' and 'end' are reversed
1954     // because bits are counted from high to low order.
1955     unsigned InstMaskStart = 64 - MaskEnd - 1,
1956              InstMaskEnd   = 64 - MaskStart - 1;
1957 
1958     if (Repl32)
1959       return 1;
1960 
1961     if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1962         InstMaskEnd == 63 - RLAmt)
1963       return 1;
1964 
1965     return 2;
1966   }
1967 
1968   // For 64-bit values, not all combinations of rotates and masks are
1969   // available. Produce one if it is available.
1970   SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1971                           bool Repl32, unsigned MaskStart, unsigned MaskEnd,
1972                           unsigned *InstCnt = nullptr) {
1973     // In the notation used by the instructions, 'start' and 'end' are reversed
1974     // because bits are counted from high to low order.
1975     unsigned InstMaskStart = 64 - MaskEnd - 1,
1976              InstMaskEnd   = 64 - MaskStart - 1;
1977 
1978     if (InstCnt) *InstCnt += 1;
1979 
1980     if (Repl32) {
1981       // This rotation amount assumes that the lower 32 bits of the quantity
1982       // are replicated in the high 32 bits by the rotation operator (which is
1983       // done by rlwinm and friends).
1984       assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1985       assert(InstMaskEnd   >= 32 && "Mask cannot end out of range");
1986       SDValue Ops[] =
1987         { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1988           getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
1989       return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1990                                             Ops), 0);
1991     }
1992 
1993     if (InstMaskEnd == 63) {
1994       SDValue Ops[] =
1995         { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1996           getI32Imm(InstMaskStart, dl) };
1997       return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1998     }
1999 
2000     if (InstMaskStart == 0) {
2001       SDValue Ops[] =
2002         { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2003           getI32Imm(InstMaskEnd, dl) };
2004       return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
2005     }
2006 
2007     if (InstMaskEnd == 63 - RLAmt) {
2008       SDValue Ops[] =
2009         { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2010           getI32Imm(InstMaskStart, dl) };
2011       return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
2012     }
2013 
2014     // We cannot do this with a single instruction, so we'll use two. The
2015     // problem is that we're not free to choose both a rotation amount and mask
2016     // start and end independently. We can choose an arbitrary mask start and
2017     // end, but then the rotation amount is fixed. Rotation, however, can be
2018     // inverted, and so by applying an "inverse" rotation first, we can get the
2019     // desired result.
2020     if (InstCnt) *InstCnt += 1;
2021 
2022     // The rotation mask for the second instruction must be MaskStart.
2023     unsigned RLAmt2 = MaskStart;
2024     // The first instruction must rotate V so that the overall rotation amount
2025     // is RLAmt.
2026     unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2027     if (RLAmt1)
2028       V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
2029     return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
2030   }
2031 
2032   // For 64-bit values, not all combinations of rotates and masks are
2033   // available. Produce a rotate-mask-and-insert if one is available.
2034   SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
2035                              unsigned RLAmt, bool Repl32, unsigned MaskStart,
2036                              unsigned MaskEnd, unsigned *InstCnt = nullptr) {
2037     // In the notation used by the instructions, 'start' and 'end' are reversed
2038     // because bits are counted from high to low order.
2039     unsigned InstMaskStart = 64 - MaskEnd - 1,
2040              InstMaskEnd   = 64 - MaskStart - 1;
2041 
2042     if (InstCnt) *InstCnt += 1;
2043 
2044     if (Repl32) {
2045       // This rotation amount assumes that the lower 32 bits of the quantity
2046       // are replicated in the high 32 bits by the rotation operator (which is
2047       // done by rlwinm and friends).
2048       assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2049       assert(InstMaskEnd   >= 32 && "Mask cannot end out of range");
2050       SDValue Ops[] =
2051         { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2052           getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2053       return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
2054                                             Ops), 0);
2055     }
2056 
2057     if (InstMaskEnd == 63 - RLAmt) {
2058       SDValue Ops[] =
2059         { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2060           getI32Imm(InstMaskStart, dl) };
2061       return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
2062     }
2063 
2064     // We cannot do this with a single instruction, so we'll use two. The
2065     // problem is that we're not free to choose both a rotation amount and mask
2066     // start and end independently. We can choose an arbitrary mask start and
2067     // end, but then the rotation amount is fixed. Rotation, however, can be
2068     // inverted, and so by applying an "inverse" rotation first, we can get the
2069     // desired result.
2070     if (InstCnt) *InstCnt += 1;
2071 
2072     // The rotation mask for the second instruction must be MaskStart.
2073     unsigned RLAmt2 = MaskStart;
2074     // The first instruction must rotate V so that the overall rotation amount
2075     // is RLAmt.
2076     unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2077     if (RLAmt1)
2078       V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
2079     return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
2080   }
2081 
2082   void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2083     if (BPermRewriterNoMasking)
2084       return;
2085 
2086     // The idea here is the same as in the 32-bit version, but with additional
2087     // complications from the fact that Repl32 might be true. Because we
2088     // aggressively convert bit groups to Repl32 form (which, for small
2089     // rotation factors, involves no other change), and then coalesce, it might
2090     // be the case that a single 64-bit masking operation could handle both
2091     // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
2092     // form allowed coalescing, then we must use a 32-bit rotaton in order to
2093     // completely capture the new combined bit group.
2094 
2095     for (ValueRotInfo &VRI : ValueRotsVec) {
2096       uint64_t Mask = 0;
2097 
2098       // We need to add to the mask all bits from the associated bit groups.
2099       // If Repl32 is false, we need to add bits from bit groups that have
2100       // Repl32 true, but are trivially convertable to Repl32 false. Such a
2101       // group is trivially convertable if it overlaps only with the lower 32
2102       // bits, and the group has not been coalesced.
2103       auto MatchingBG = [VRI](const BitGroup &BG) {
2104         if (VRI.V != BG.V)
2105           return false;
2106 
2107         unsigned EffRLAmt = BG.RLAmt;
2108         if (!VRI.Repl32 && BG.Repl32) {
2109           if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
2110               !BG.Repl32Coalesced) {
2111             if (BG.Repl32CR)
2112               EffRLAmt += 32;
2113           } else {
2114             return false;
2115           }
2116         } else if (VRI.Repl32 != BG.Repl32) {
2117           return false;
2118         }
2119 
2120         return VRI.RLAmt == EffRLAmt;
2121       };
2122 
2123       for (auto &BG : BitGroups) {
2124         if (!MatchingBG(BG))
2125           continue;
2126 
2127         if (BG.StartIdx <= BG.EndIdx) {
2128           for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
2129             Mask |= (UINT64_C(1) << i);
2130         } else {
2131           for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
2132             Mask |= (UINT64_C(1) << i);
2133           for (unsigned i = 0; i <= BG.EndIdx; ++i)
2134             Mask |= (UINT64_C(1) << i);
2135         }
2136       }
2137 
2138       // We can use the 32-bit andi/andis technique if the mask does not
2139       // require any higher-order bits. This can save an instruction compared
2140       // to always using the general 64-bit technique.
2141       bool Use32BitInsts = isUInt<32>(Mask);
2142       // Compute the masks for andi/andis that would be necessary.
2143       unsigned ANDIMask = (Mask & UINT16_MAX),
2144                ANDISMask = (Mask >> 16) & UINT16_MAX;
2145 
2146       bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
2147 
2148       unsigned NumAndInsts = (unsigned) NeedsRotate +
2149                              (unsigned) (bool) Res;
2150       if (Use32BitInsts)
2151         NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
2152                        (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2153       else
2154         NumAndInsts += selectI64ImmInstrCount(Mask) + /* and */ 1;
2155 
2156       unsigned NumRLInsts = 0;
2157       bool FirstBG = true;
2158       bool MoreBG = false;
2159       for (auto &BG : BitGroups) {
2160         if (!MatchingBG(BG)) {
2161           MoreBG = true;
2162           continue;
2163         }
2164         NumRLInsts +=
2165           SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
2166                                !FirstBG);
2167         FirstBG = false;
2168       }
2169 
2170       LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2171                         << " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":")
2172                         << "\n\t\t\tisel using masking: " << NumAndInsts
2173                         << " using rotates: " << NumRLInsts << "\n");
2174 
2175       // When we'd use andi/andis, we bias toward using the rotates (andi only
2176       // has a record form, and is cracked on POWER cores). However, when using
2177       // general 64-bit constant formation, bias toward the constant form,
2178       // because that exposes more opportunities for CSE.
2179       if (NumAndInsts > NumRLInsts)
2180         continue;
2181       // When merging multiple bit groups, instruction or is used.
2182       // But when rotate is used, rldimi can inert the rotated value into any
2183       // register, so instruction or can be avoided.
2184       if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
2185         continue;
2186 
2187       LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2188 
2189       if (InstCnt) *InstCnt += NumAndInsts;
2190 
2191       SDValue VRot;
2192       // We actually need to generate a rotation if we have a non-zero rotation
2193       // factor or, in the Repl32 case, if we care about any of the
2194       // higher-order replicated bits. In the latter case, we generate a mask
2195       // backward so that it actually includes the entire 64 bits.
2196       if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
2197         VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2198                                VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
2199       else
2200         VRot = VRI.V;
2201 
2202       SDValue TotalVal;
2203       if (Use32BitInsts) {
2204         assert((ANDIMask != 0 || ANDISMask != 0) &&
2205                "No set bits in mask when using 32-bit ands for 64-bit value");
2206 
2207         SDValue ANDIVal, ANDISVal;
2208         if (ANDIMask != 0)
2209           ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,
2210                                                    ExtendToInt64(VRot, dl),
2211                                                    getI32Imm(ANDIMask, dl)),
2212                             0);
2213         if (ANDISMask != 0)
2214           ANDISVal =
2215               SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2216                                              ExtendToInt64(VRot, dl),
2217                                              getI32Imm(ANDISMask, dl)),
2218                       0);
2219 
2220         if (!ANDIVal)
2221           TotalVal = ANDISVal;
2222         else if (!ANDISVal)
2223           TotalVal = ANDIVal;
2224         else
2225           TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2226                                ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2227       } else {
2228         TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
2229         TotalVal =
2230           SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2231                                          ExtendToInt64(VRot, dl), TotalVal),
2232                   0);
2233      }
2234 
2235       if (!Res)
2236         Res = TotalVal;
2237       else
2238         Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2239                                              ExtendToInt64(Res, dl), TotalVal),
2240                       0);
2241 
2242       // Now, remove all groups with this underlying value and rotation
2243       // factor.
2244       eraseMatchingBitGroups(MatchingBG);
2245     }
2246   }
2247 
2248   // Instruction selection for the 64-bit case.
2249   SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
2250     SDLoc dl(N);
2251     SDValue Res;
2252 
2253     if (InstCnt) *InstCnt = 0;
2254 
2255     // Take care of cases that should use andi/andis first.
2256     SelectAndParts64(dl, Res, InstCnt);
2257 
2258     // If we've not yet selected a 'starting' instruction, and we have no zeros
2259     // to fill in, select the (Value, RLAmt) with the highest priority (largest
2260     // number of groups), and start with this rotated value.
2261     if ((!NeedMask || LateMask) && !Res) {
2262       // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
2263       // groups will come first, and so the VRI representing the largest number
2264       // of groups might not be first (it might be the first Repl32 groups).
2265       unsigned MaxGroupsIdx = 0;
2266       if (!ValueRotsVec[0].Repl32) {
2267         for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
2268           if (ValueRotsVec[i].Repl32) {
2269             if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
2270               MaxGroupsIdx = i;
2271             break;
2272           }
2273       }
2274 
2275       ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
2276       bool NeedsRotate = false;
2277       if (VRI.RLAmt) {
2278         NeedsRotate = true;
2279       } else if (VRI.Repl32) {
2280         for (auto &BG : BitGroups) {
2281           if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
2282               BG.Repl32 != VRI.Repl32)
2283             continue;
2284 
2285           // We don't need a rotate if the bit group is confined to the lower
2286           // 32 bits.
2287           if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
2288             continue;
2289 
2290           NeedsRotate = true;
2291           break;
2292         }
2293       }
2294 
2295       if (NeedsRotate)
2296         Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2297                               VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
2298                               InstCnt);
2299       else
2300         Res = VRI.V;
2301 
2302       // Now, remove all groups with this underlying value and rotation factor.
2303       if (Res)
2304         eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2305           return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
2306                  BG.Repl32 == VRI.Repl32;
2307         });
2308     }
2309 
2310     // Because 64-bit rotates are more flexible than inserts, we might have a
2311     // preference regarding which one we do first (to save one instruction).
2312     if (!Res)
2313       for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
2314         if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2315                                 false) <
2316             SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2317                                 true)) {
2318           if (I != BitGroups.begin()) {
2319             BitGroup BG = *I;
2320             BitGroups.erase(I);
2321             BitGroups.insert(BitGroups.begin(), BG);
2322           }
2323 
2324           break;
2325         }
2326       }
2327 
2328     // Insert the other groups (one at a time).
2329     for (auto &BG : BitGroups) {
2330       if (!Res)
2331         Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
2332                               BG.EndIdx, InstCnt);
2333       else
2334         Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
2335                                  BG.StartIdx, BG.EndIdx, InstCnt);
2336     }
2337 
2338     if (LateMask) {
2339       uint64_t Mask = getZerosMask();
2340 
2341       // We can use the 32-bit andi/andis technique if the mask does not
2342       // require any higher-order bits. This can save an instruction compared
2343       // to always using the general 64-bit technique.
2344       bool Use32BitInsts = isUInt<32>(Mask);
2345       // Compute the masks for andi/andis that would be necessary.
2346       unsigned ANDIMask = (Mask & UINT16_MAX),
2347                ANDISMask = (Mask >> 16) & UINT16_MAX;
2348 
2349       if (Use32BitInsts) {
2350         assert((ANDIMask != 0 || ANDISMask != 0) &&
2351                "No set bits in mask when using 32-bit ands for 64-bit value");
2352 
2353         if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2354                                  (unsigned) (ANDISMask != 0) +
2355                                  (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2356 
2357         SDValue ANDIVal, ANDISVal;
2358         if (ANDIMask != 0)
2359           ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,
2360                                                    ExtendToInt64(Res, dl),
2361                                                    getI32Imm(ANDIMask, dl)),
2362                             0);
2363         if (ANDISMask != 0)
2364           ANDISVal =
2365               SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2366                                              ExtendToInt64(Res, dl),
2367                                              getI32Imm(ANDISMask, dl)),
2368                       0);
2369 
2370         if (!ANDIVal)
2371           Res = ANDISVal;
2372         else if (!ANDISVal)
2373           Res = ANDIVal;
2374         else
2375           Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2376                           ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2377       } else {
2378         if (InstCnt) *InstCnt += selectI64ImmInstrCount(Mask) + /* and */ 1;
2379 
2380         SDValue MaskVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
2381         Res =
2382           SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2383                                          ExtendToInt64(Res, dl), MaskVal), 0);
2384       }
2385     }
2386 
2387     return Res.getNode();
2388   }
2389 
2390   SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
2391     // Fill in BitGroups.
2392     collectBitGroups(LateMask);
2393     if (BitGroups.empty())
2394       return nullptr;
2395 
2396     // For 64-bit values, figure out when we can use 32-bit instructions.
2397     if (Bits.size() == 64)
2398       assignRepl32BitGroups();
2399 
2400     // Fill in ValueRotsVec.
2401     collectValueRotInfo();
2402 
2403     if (Bits.size() == 32) {
2404       return Select32(N, LateMask, InstCnt);
2405     } else {
2406       assert(Bits.size() == 64 && "Not 64 bits here?");
2407       return Select64(N, LateMask, InstCnt);
2408     }
2409 
2410     return nullptr;
2411   }
2412 
2413   void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
2414     BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
2415   }
2416 
2417   SmallVector<ValueBit, 64> Bits;
2418 
2419   bool NeedMask = false;
2420   SmallVector<unsigned, 64> RLAmt;
2421 
2422   SmallVector<BitGroup, 16> BitGroups;
2423 
2424   DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
2425   SmallVector<ValueRotInfo, 16> ValueRotsVec;
2426 
2427   SelectionDAG *CurDAG = nullptr;
2428 
2429 public:
2430   BitPermutationSelector(SelectionDAG *DAG)
2431     : CurDAG(DAG) {}
2432 
2433   // Here we try to match complex bit permutations into a set of
2434   // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2435   // known to produce optimal code for common cases (like i32 byte swapping).
2436   SDNode *Select(SDNode *N) {
2437     Memoizer.clear();
2438     auto Result =
2439         getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2440     if (!Result.first)
2441       return nullptr;
2442     Bits = std::move(*Result.second);
2443 
2444     LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2445                          " selection for:    ");
2446     LLVM_DEBUG(N->dump(CurDAG));
2447 
2448     // Fill it RLAmt and set NeedMask.
2449     computeRotationAmounts();
2450 
2451     if (!NeedMask)
2452       return Select(N, false);
2453 
2454     // We currently have two techniques for handling results with zeros: early
2455     // masking (the default) and late masking. Late masking is sometimes more
2456     // efficient, but because the structure of the bit groups is different, it
2457     // is hard to tell without generating both and comparing the results. With
2458     // late masking, we ignore zeros in the resulting value when inserting each
2459     // set of bit groups, and then mask in the zeros at the end. With early
2460     // masking, we only insert the non-zero parts of the result at every step.
2461 
2462     unsigned InstCnt = 0, InstCntLateMask = 0;
2463     LLVM_DEBUG(dbgs() << "\tEarly masking:\n");
2464     SDNode *RN = Select(N, false, &InstCnt);
2465     LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2466 
2467     LLVM_DEBUG(dbgs() << "\tLate masking:\n");
2468     SDNode *RNLM = Select(N, true, &InstCntLateMask);
2469     LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask
2470                       << " instructions\n");
2471 
2472     if (InstCnt <= InstCntLateMask) {
2473       LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2474       return RN;
2475     }
2476 
2477     LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2478     return RNLM;
2479   }
2480 };
2481 
2482 class IntegerCompareEliminator {
2483   SelectionDAG *CurDAG;
2484   PPCDAGToDAGISel *S;
2485   // Conversion type for interpreting results of a 32-bit instruction as
2486   // a 64-bit value or vice versa.
2487   enum ExtOrTruncConversion { Ext, Trunc };
2488 
2489   // Modifiers to guide how an ISD::SETCC node's result is to be computed
2490   // in a GPR.
2491   // ZExtOrig - use the original condition code, zero-extend value
2492   // ZExtInvert - invert the condition code, zero-extend value
2493   // SExtOrig - use the original condition code, sign-extend value
2494   // SExtInvert - invert the condition code, sign-extend value
2495   enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
2496 
2497   // Comparisons against zero to emit GPR code sequences for. Each of these
2498   // sequences may need to be emitted for two or more equivalent patterns.
2499   // For example (a >= 0) == (a > -1). The direction of the comparison (</>)
2500   // matters as well as the extension type: sext (-1/0), zext (1/0).
2501   // GEZExt - (zext (LHS >= 0))
2502   // GESExt - (sext (LHS >= 0))
2503   // LEZExt - (zext (LHS <= 0))
2504   // LESExt - (sext (LHS <= 0))
2505   enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };
2506 
2507   SDNode *tryEXTEND(SDNode *N);
2508   SDNode *tryLogicOpOfCompares(SDNode *N);
2509   SDValue computeLogicOpInGPR(SDValue LogicOp);
2510   SDValue signExtendInputIfNeeded(SDValue Input);
2511   SDValue zeroExtendInputIfNeeded(SDValue Input);
2512   SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
2513   SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2514                                         ZeroCompare CmpTy);
2515   SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2516                               int64_t RHSValue, SDLoc dl);
2517  SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2518                               int64_t RHSValue, SDLoc dl);
2519   SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2520                               int64_t RHSValue, SDLoc dl);
2521   SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2522                               int64_t RHSValue, SDLoc dl);
2523   SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
2524 
2525 public:
2526   IntegerCompareEliminator(SelectionDAG *DAG,
2527                            PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) {
2528     assert(CurDAG->getTargetLoweringInfo()
2529            .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 &&
2530            "Only expecting to use this on 64 bit targets.");
2531   }
2532   SDNode *Select(SDNode *N) {
2533     if (CmpInGPR == ICGPR_None)
2534       return nullptr;
2535     switch (N->getOpcode()) {
2536     default: break;
2537     case ISD::ZERO_EXTEND:
2538       if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 ||
2539           CmpInGPR == ICGPR_SextI64)
2540         return nullptr;
2541       LLVM_FALLTHROUGH;
2542     case ISD::SIGN_EXTEND:
2543       if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 ||
2544           CmpInGPR == ICGPR_ZextI64)
2545         return nullptr;
2546       return tryEXTEND(N);
2547     case ISD::AND:
2548     case ISD::OR:
2549     case ISD::XOR:
2550       return tryLogicOpOfCompares(N);
2551     }
2552     return nullptr;
2553   }
2554 };
2555 
2556 static bool isLogicOp(unsigned Opc) {
2557   return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR;
2558 }
2559 // The obvious case for wanting to keep the value in a GPR. Namely, the
2560 // result of the comparison is actually needed in a GPR.
2561 SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) {
2562   assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2563           N->getOpcode() == ISD::SIGN_EXTEND) &&
2564          "Expecting a zero/sign extend node!");
2565   SDValue WideRes;
2566   // If we are zero-extending the result of a logical operation on i1
2567   // values, we can keep the values in GPRs.
2568   if (isLogicOp(N->getOperand(0).getOpcode()) &&
2569       N->getOperand(0).getValueType() == MVT::i1 &&
2570       N->getOpcode() == ISD::ZERO_EXTEND)
2571     WideRes = computeLogicOpInGPR(N->getOperand(0));
2572   else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2573     return nullptr;
2574   else
2575     WideRes =
2576       getSETCCInGPR(N->getOperand(0),
2577                     N->getOpcode() == ISD::SIGN_EXTEND ?
2578                     SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2579 
2580   if (!WideRes)
2581     return nullptr;
2582 
2583   SDLoc dl(N);
2584   bool Input32Bit = WideRes.getValueType() == MVT::i32;
2585   bool Output32Bit = N->getValueType(0) == MVT::i32;
2586 
2587   NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2588   NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2589 
2590   SDValue ConvOp = WideRes;
2591   if (Input32Bit != Output32Bit)
2592     ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext :
2593                            ExtOrTruncConversion::Trunc);
2594   return ConvOp.getNode();
2595 }
2596 
2597 // Attempt to perform logical operations on the results of comparisons while
2598 // keeping the values in GPRs. Without doing so, these would end up being
2599 // lowered to CR-logical operations which suffer from significant latency and
2600 // low ILP.
2601 SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) {
2602   if (N->getValueType(0) != MVT::i1)
2603     return nullptr;
2604   assert(isLogicOp(N->getOpcode()) &&
2605          "Expected a logic operation on setcc results.");
2606   SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
2607   if (!LoweredLogical)
2608     return nullptr;
2609 
2610   SDLoc dl(N);
2611   bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
2612   unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
2613   SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2614   SDValue LHS = LoweredLogical.getOperand(0);
2615   SDValue RHS = LoweredLogical.getOperand(1);
2616   SDValue WideOp;
2617   SDValue OpToConvToRecForm;
2618 
2619   // Look through any 32-bit to 64-bit implicit extend nodes to find the
2620   // opcode that is input to the XORI.
2621   if (IsBitwiseNegate &&
2622       LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
2623     OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
2624   else if (IsBitwiseNegate)
2625     // If the input to the XORI isn't an extension, that's what we're after.
2626     OpToConvToRecForm = LoweredLogical.getOperand(0);
2627   else
2628     // If this is not an XORI, it is a reg-reg logical op and we can convert
2629     // it to record-form.
2630     OpToConvToRecForm = LoweredLogical;
2631 
2632   // Get the record-form version of the node we're looking to use to get the
2633   // CR result from.
2634   uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
2635   int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
2636 
2637   // Convert the right node to record-form. This is either the logical we're
2638   // looking at or it is the input node to the negation (if we're looking at
2639   // a bitwise negation).
2640   if (NewOpc != -1 && IsBitwiseNegate) {
2641     // The input to the XORI has a record-form. Use it.
2642     assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
2643            "Expected a PPC::XORI8 only for bitwise negation.");
2644     // Emit the record-form instruction.
2645     std::vector<SDValue> Ops;
2646     for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
2647       Ops.push_back(OpToConvToRecForm.getOperand(i));
2648 
2649     WideOp =
2650       SDValue(CurDAG->getMachineNode(NewOpc, dl,
2651                                      OpToConvToRecForm.getValueType(),
2652                                      MVT::Glue, Ops), 0);
2653   } else {
2654     assert((NewOpc != -1 || !IsBitwiseNegate) &&
2655            "No record form available for AND8/OR8/XOR8?");
2656     WideOp =
2657         SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDI8_rec : NewOpc,
2658                                        dl, MVT::i64, MVT::Glue, LHS, RHS),
2659                 0);
2660   }
2661 
2662   // Select this node to a single bit from CR0 set by the record-form node
2663   // just created. For bitwise negation, use the EQ bit which is the equivalent
2664   // of negating the result (i.e. it is a bit set when the result of the
2665   // operation is zero).
2666   SDValue SRIdxVal =
2667     CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
2668   SDValue CRBit =
2669     SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
2670                                    MVT::i1, CR0Reg, SRIdxVal,
2671                                    WideOp.getValue(1)), 0);
2672   return CRBit.getNode();
2673 }
2674 
2675 // Lower a logical operation on i1 values into a GPR sequence if possible.
2676 // The result can be kept in a GPR if requested.
2677 // Three types of inputs can be handled:
2678 // - SETCC
2679 // - TRUNCATE
2680 // - Logical operation (AND/OR/XOR)
2681 // There is also a special case that is handled (namely a complement operation
2682 // achieved with xor %a, -1).
2683 SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) {
2684   assert(isLogicOp(LogicOp.getOpcode()) &&
2685         "Can only handle logic operations here.");
2686   assert(LogicOp.getValueType() == MVT::i1 &&
2687          "Can only handle logic operations on i1 values here.");
2688   SDLoc dl(LogicOp);
2689   SDValue LHS, RHS;
2690 
2691  // Special case: xor %a, -1
2692   bool IsBitwiseNegation = isBitwiseNot(LogicOp);
2693 
2694   // Produces a GPR sequence for each operand of the binary logic operation.
2695   // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
2696   // the value in a GPR and for logic operations, it will recursively produce
2697   // a GPR sequence for the operation.
2698  auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
2699     unsigned OperandOpcode = Operand.getOpcode();
2700     if (OperandOpcode == ISD::SETCC)
2701       return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
2702     else if (OperandOpcode == ISD::TRUNCATE) {
2703       SDValue InputOp = Operand.getOperand(0);
2704      EVT InVT = InputOp.getValueType();
2705       return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
2706                                             PPC::RLDICL, dl, InVT, InputOp,
2707                                             S->getI64Imm(0, dl),
2708                                             S->getI64Imm(63, dl)), 0);
2709     } else if (isLogicOp(OperandOpcode))
2710       return computeLogicOpInGPR(Operand);
2711     return SDValue();
2712   };
2713   LHS = getLogicOperand(LogicOp.getOperand(0));
2714   RHS = getLogicOperand(LogicOp.getOperand(1));
2715 
2716   // If a GPR sequence can't be produced for the LHS we can't proceed.
2717   // Not producing a GPR sequence for the RHS is only a problem if this isn't
2718   // a bitwise negation operation.
2719   if (!LHS || (!RHS && !IsBitwiseNegation))
2720     return SDValue();
2721 
2722   NumLogicOpsOnComparison++;
2723 
2724   // We will use the inputs as 64-bit values.
2725   if (LHS.getValueType() == MVT::i32)
2726     LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
2727   if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
2728     RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
2729 
2730   unsigned NewOpc;
2731   switch (LogicOp.getOpcode()) {
2732   default: llvm_unreachable("Unknown logic operation.");
2733   case ISD::AND: NewOpc = PPC::AND8; break;
2734   case ISD::OR:  NewOpc = PPC::OR8;  break;
2735   case ISD::XOR: NewOpc = PPC::XOR8; break;
2736   }
2737 
2738   if (IsBitwiseNegation) {
2739     RHS = S->getI64Imm(1, dl);
2740     NewOpc = PPC::XORI8;
2741   }
2742 
2743   return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
2744 
2745 }
2746 
2747 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
2748 /// Otherwise just reinterpret it as a 64-bit value.
2749 /// Useful when emitting comparison code for 32-bit values without using
2750 /// the compare instruction (which only considers the lower 32-bits).
2751 SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) {
2752   assert(Input.getValueType() == MVT::i32 &&
2753          "Can only sign-extend 32-bit values here.");
2754   unsigned Opc = Input.getOpcode();
2755 
2756   // The value was sign extended and then truncated to 32-bits. No need to
2757   // sign extend it again.
2758   if (Opc == ISD::TRUNCATE &&
2759       (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
2760        Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
2761     return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2762 
2763   LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2764   // The input is a sign-extending load. All ppc sign-extending loads
2765   // sign-extend to the full 64-bits.
2766   if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
2767     return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2768 
2769   ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2770   // We don't sign-extend constants.
2771   if (InputConst)
2772     return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2773 
2774   SDLoc dl(Input);
2775   SignExtensionsAdded++;
2776   return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl,
2777                                         MVT::i64, Input), 0);
2778 }
2779 
2780 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
2781 /// Otherwise just reinterpret it as a 64-bit value.
2782 /// Useful when emitting comparison code for 32-bit values without using
2783 /// the compare instruction (which only considers the lower 32-bits).
2784 SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) {
2785   assert(Input.getValueType() == MVT::i32 &&
2786          "Can only zero-extend 32-bit values here.");
2787   unsigned Opc = Input.getOpcode();
2788 
2789   // The only condition under which we can omit the actual extend instruction:
2790   // - The value is a positive constant
2791   // - The value comes from a load that isn't a sign-extending load
2792   // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext.
2793   bool IsTruncateOfZExt = Opc == ISD::TRUNCATE &&
2794     (Input.getOperand(0).getOpcode() == ISD::AssertZext ||
2795      Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND);
2796   if (IsTruncateOfZExt)
2797     return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2798 
2799   ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2800   if (InputConst && InputConst->getSExtValue() >= 0)
2801     return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2802 
2803   LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2804   // The input is a load that doesn't sign-extend (it will be zero-extended).
2805   if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
2806     return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2807 
2808   // None of the above, need to zero-extend.
2809   SDLoc dl(Input);
2810   ZeroExtensionsAdded++;
2811   return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input,
2812                                         S->getI64Imm(0, dl),
2813                                         S->getI64Imm(32, dl)), 0);
2814 }
2815 
2816 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of
2817 // course not actual zero/sign extensions that will generate machine code,
2818 // they're just a way to reinterpret a 32 bit value in a register as a
2819 // 64 bit value and vice-versa.
2820 SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes,
2821                                                 ExtOrTruncConversion Conv) {
2822   SDLoc dl(NatWidthRes);
2823 
2824   // For reinterpreting 32-bit values as 64 bit values, we generate
2825   // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
2826   if (Conv == ExtOrTruncConversion::Ext) {
2827     SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
2828     SDValue SubRegIdx =
2829       CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2830     return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
2831                                           ImDef, NatWidthRes, SubRegIdx), 0);
2832   }
2833 
2834   assert(Conv == ExtOrTruncConversion::Trunc &&
2835          "Unknown convertion between 32 and 64 bit values.");
2836   // For reinterpreting 64-bit values as 32-bit values, we just need to
2837   // EXTRACT_SUBREG (i.e. extract the low word).
2838   SDValue SubRegIdx =
2839     CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2840   return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
2841                                         NatWidthRes, SubRegIdx), 0);
2842 }
2843 
2844 // Produce a GPR sequence for compound comparisons (<=, >=) against zero.
2845 // Handle both zero-extensions and sign-extensions.
2846 SDValue
2847 IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2848                                                          ZeroCompare CmpTy) {
2849   EVT InVT = LHS.getValueType();
2850   bool Is32Bit = InVT == MVT::i32;
2851   SDValue ToExtend;
2852 
2853   // Produce the value that needs to be either zero or sign extended.
2854   switch (CmpTy) {
2855   case ZeroCompare::GEZExt:
2856   case ZeroCompare::GESExt:
2857     ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8,
2858                                               dl, InVT, LHS, LHS), 0);
2859     break;
2860   case ZeroCompare::LEZExt:
2861   case ZeroCompare::LESExt: {
2862     if (Is32Bit) {
2863       // Upper 32 bits cannot be undefined for this sequence.
2864       LHS = signExtendInputIfNeeded(LHS);
2865       SDValue Neg =
2866         SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
2867       ToExtend =
2868         SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2869                                        Neg, S->getI64Imm(1, dl),
2870                                        S->getI64Imm(63, dl)), 0);
2871     } else {
2872       SDValue Addi =
2873         SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
2874                                        S->getI64Imm(~0ULL, dl)), 0);
2875       ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2876                                                 Addi, LHS), 0);
2877     }
2878     break;
2879   }
2880   }
2881 
2882   // For 64-bit sequences, the extensions are the same for the GE/LE cases.
2883   if (!Is32Bit &&
2884       (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt))
2885     return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2886                                           ToExtend, S->getI64Imm(1, dl),
2887                                           S->getI64Imm(63, dl)), 0);
2888   if (!Is32Bit &&
2889       (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))
2890     return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,
2891                                           S->getI64Imm(63, dl)), 0);
2892 
2893   assert(Is32Bit && "Should have handled the 32-bit sequences above.");
2894   // For 32-bit sequences, the extensions differ between GE/LE cases.
2895   switch (CmpTy) {
2896   case ZeroCompare::GEZExt: {
2897     SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
2898                            S->getI32Imm(31, dl) };
2899     return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2900                                           ShiftOps), 0);
2901   }
2902   case ZeroCompare::GESExt:
2903     return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,
2904                                           S->getI32Imm(31, dl)), 0);
2905   case ZeroCompare::LEZExt:
2906     return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend,
2907                                           S->getI32Imm(1, dl)), 0);
2908   case ZeroCompare::LESExt:
2909     return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend,
2910                                           S->getI32Imm(-1, dl)), 0);
2911   }
2912 
2913   // The above case covers all the enumerators so it can't have a default clause
2914   // to avoid compiler warnings.
2915   llvm_unreachable("Unknown zero-comparison type.");
2916 }
2917 
2918 /// Produces a zero-extended result of comparing two 32-bit values according to
2919 /// the passed condition code.
2920 SDValue
2921 IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS,
2922                                               ISD::CondCode CC,
2923                                               int64_t RHSValue, SDLoc dl) {
2924   if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
2925       CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext)
2926     return SDValue();
2927   bool IsRHSZero = RHSValue == 0;
2928   bool IsRHSOne = RHSValue == 1;
2929   bool IsRHSNegOne = RHSValue == -1LL;
2930   switch (CC) {
2931   default: return SDValue();
2932   case ISD::SETEQ: {
2933     // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
2934     // (zext (setcc %a, 0, seteq))  -> (lshr (cntlzw %a), 5)
2935     SDValue Xor = IsRHSZero ? LHS :
2936       SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2937     SDValue Clz =
2938       SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2939     SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
2940       S->getI32Imm(31, dl) };
2941     return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2942                                           ShiftOps), 0);
2943   }
2944   case ISD::SETNE: {
2945     // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
2946     // (zext (setcc %a, 0, setne))  -> (xor (lshr (cntlzw %a), 5), 1)
2947     SDValue Xor = IsRHSZero ? LHS :
2948       SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2949     SDValue Clz =
2950       SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2951     SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
2952       S->getI32Imm(31, dl) };
2953     SDValue Shift =
2954       SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2955     return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2956                                           S->getI32Imm(1, dl)), 0);
2957   }
2958   case ISD::SETGE: {
2959     // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)
2960     // (zext (setcc %a, 0, setge))  -> (lshr (~ %a), 31)
2961     if(IsRHSZero)
2962       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
2963 
2964     // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
2965     // by swapping inputs and falling through.
2966     std::swap(LHS, RHS);
2967     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2968     IsRHSZero = RHSConst && RHSConst->isNullValue();
2969     LLVM_FALLTHROUGH;
2970   }
2971   case ISD::SETLE: {
2972     if (CmpInGPR == ICGPR_NonExtIn)
2973       return SDValue();
2974     // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)
2975     // (zext (setcc %a, 0, setle))  -> (xor (lshr (- %a), 63), 1)
2976     if(IsRHSZero) {
2977       if (CmpInGPR == ICGPR_NonExtIn)
2978         return SDValue();
2979       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
2980     }
2981 
2982     // The upper 32-bits of the register can't be undefined for this sequence.
2983     LHS = signExtendInputIfNeeded(LHS);
2984     RHS = signExtendInputIfNeeded(RHS);
2985     SDValue Sub =
2986       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
2987     SDValue Shift =
2988       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub,
2989                                      S->getI64Imm(1, dl), S->getI64Imm(63, dl)),
2990               0);
2991     return
2992       SDValue(CurDAG->getMachineNode(PPC::XORI8, dl,
2993                                      MVT::i64, Shift, S->getI32Imm(1, dl)), 0);
2994   }
2995   case ISD::SETGT: {
2996     // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63)
2997     // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31)
2998     // (zext (setcc %a, 0, setgt))  -> (lshr (- %a), 63)
2999     // Handle SETLT -1 (which is equivalent to SETGE 0).
3000     if (IsRHSNegOne)
3001       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3002 
3003     if (IsRHSZero) {
3004       if (CmpInGPR == ICGPR_NonExtIn)
3005         return SDValue();
3006       // The upper 32-bits of the register can't be undefined for this sequence.
3007       LHS = signExtendInputIfNeeded(LHS);
3008       RHS = signExtendInputIfNeeded(RHS);
3009       SDValue Neg =
3010         SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3011       return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3012                      Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0);
3013     }
3014     // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3015     // (%b < %a) by swapping inputs and falling through.
3016     std::swap(LHS, RHS);
3017     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3018     IsRHSZero = RHSConst && RHSConst->isNullValue();
3019     IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3020     LLVM_FALLTHROUGH;
3021   }
3022   case ISD::SETLT: {
3023     // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63)
3024     // (zext (setcc %a, 1, setlt))  -> (xor (lshr (- %a), 63), 1)
3025     // (zext (setcc %a, 0, setlt))  -> (lshr %a, 31)
3026     // Handle SETLT 1 (which is equivalent to SETLE 0).
3027     if (IsRHSOne) {
3028       if (CmpInGPR == ICGPR_NonExtIn)
3029         return SDValue();
3030       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3031     }
3032 
3033     if (IsRHSZero) {
3034       SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
3035                              S->getI32Imm(31, dl) };
3036       return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3037                                             ShiftOps), 0);
3038     }
3039 
3040     if (CmpInGPR == ICGPR_NonExtIn)
3041       return SDValue();
3042     // The upper 32-bits of the register can't be undefined for this sequence.
3043     LHS = signExtendInputIfNeeded(LHS);
3044     RHS = signExtendInputIfNeeded(RHS);
3045     SDValue SUBFNode =
3046       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3047     return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3048                                     SUBFNode, S->getI64Imm(1, dl),
3049                                     S->getI64Imm(63, dl)), 0);
3050   }
3051   case ISD::SETUGE:
3052     // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1)
3053     // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1)
3054     std::swap(LHS, RHS);
3055     LLVM_FALLTHROUGH;
3056   case ISD::SETULE: {
3057     if (CmpInGPR == ICGPR_NonExtIn)
3058       return SDValue();
3059     // The upper 32-bits of the register can't be undefined for this sequence.
3060     LHS = zeroExtendInputIfNeeded(LHS);
3061     RHS = zeroExtendInputIfNeeded(RHS);
3062     SDValue Subtract =
3063       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3064     SDValue SrdiNode =
3065       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3066                                           Subtract, S->getI64Imm(1, dl),
3067                                           S->getI64Imm(63, dl)), 0);
3068     return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode,
3069                                             S->getI32Imm(1, dl)), 0);
3070   }
3071   case ISD::SETUGT:
3072     // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63)
3073     // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63)
3074     std::swap(LHS, RHS);
3075     LLVM_FALLTHROUGH;
3076   case ISD::SETULT: {
3077     if (CmpInGPR == ICGPR_NonExtIn)
3078       return SDValue();
3079     // The upper 32-bits of the register can't be undefined for this sequence.
3080     LHS = zeroExtendInputIfNeeded(LHS);
3081     RHS = zeroExtendInputIfNeeded(RHS);
3082     SDValue Subtract =
3083       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3084     return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3085                                           Subtract, S->getI64Imm(1, dl),
3086                                           S->getI64Imm(63, dl)), 0);
3087   }
3088   }
3089 }
3090 
3091 /// Produces a sign-extended result of comparing two 32-bit values according to
3092 /// the passed condition code.
3093 SDValue
3094 IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS,
3095                                               ISD::CondCode CC,
3096                                               int64_t RHSValue, SDLoc dl) {
3097   if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
3098       CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext)
3099     return SDValue();
3100   bool IsRHSZero = RHSValue == 0;
3101   bool IsRHSOne = RHSValue == 1;
3102   bool IsRHSNegOne = RHSValue == -1LL;
3103 
3104   switch (CC) {
3105   default: return SDValue();
3106   case ISD::SETEQ: {
3107     // (sext (setcc %a, %b, seteq)) ->
3108     //   (ashr (shl (ctlz (xor %a, %b)), 58), 63)
3109     // (sext (setcc %a, 0, seteq)) ->
3110     //   (ashr (shl (ctlz %a), 58), 63)
3111     SDValue CountInput = IsRHSZero ? LHS :
3112       SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3113     SDValue Cntlzw =
3114       SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
3115     SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl),
3116                          S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3117     SDValue Slwi =
3118       SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0);
3119     return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0);
3120   }
3121   case ISD::SETNE: {
3122     // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
3123     // flip the bit, finally take 2's complement.
3124     // (sext (setcc %a, %b, setne)) ->
3125     //   (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
3126     // Same as above, but the first xor is not needed.
3127     // (sext (setcc %a, 0, setne)) ->
3128     //   (neg (xor (lshr (ctlz %a), 5), 1))
3129     SDValue Xor = IsRHSZero ? LHS :
3130       SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3131     SDValue Clz =
3132       SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3133     SDValue ShiftOps[] =
3134       { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3135     SDValue Shift =
3136       SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3137     SDValue Xori =
3138       SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3139                                      S->getI32Imm(1, dl)), 0);
3140     return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
3141   }
3142   case ISD::SETGE: {
3143     // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)
3144     // (sext (setcc %a, 0, setge))  -> (ashr (~ %a), 31)
3145     if (IsRHSZero)
3146       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3147 
3148     // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3149     // by swapping inputs and falling through.
3150     std::swap(LHS, RHS);
3151     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3152     IsRHSZero = RHSConst && RHSConst->isNullValue();
3153     LLVM_FALLTHROUGH;
3154   }
3155   case ISD::SETLE: {
3156     if (CmpInGPR == ICGPR_NonExtIn)
3157       return SDValue();
3158     // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)
3159     // (sext (setcc %a, 0, setle))  -> (add (lshr (- %a), 63), -1)
3160     if (IsRHSZero)
3161       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3162 
3163     // The upper 32-bits of the register can't be undefined for this sequence.
3164     LHS = signExtendInputIfNeeded(LHS);
3165     RHS = signExtendInputIfNeeded(RHS);
3166     SDValue SUBFNode =
3167       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue,
3168                                      LHS, RHS), 0);
3169     SDValue Srdi =
3170       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3171                                      SUBFNode, S->getI64Imm(1, dl),
3172                                      S->getI64Imm(63, dl)), 0);
3173     return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi,
3174                                           S->getI32Imm(-1, dl)), 0);
3175   }
3176   case ISD::SETGT: {
3177     // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63)
3178     // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31)
3179     // (sext (setcc %a, 0, setgt))  -> (ashr (- %a), 63)
3180     if (IsRHSNegOne)
3181       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3182     if (IsRHSZero) {
3183       if (CmpInGPR == ICGPR_NonExtIn)
3184         return SDValue();
3185       // The upper 32-bits of the register can't be undefined for this sequence.
3186       LHS = signExtendInputIfNeeded(LHS);
3187       RHS = signExtendInputIfNeeded(RHS);
3188       SDValue Neg =
3189         SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3190         return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg,
3191                                               S->getI64Imm(63, dl)), 0);
3192     }
3193     // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3194     // (%b < %a) by swapping inputs and falling through.
3195     std::swap(LHS, RHS);
3196     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3197     IsRHSZero = RHSConst && RHSConst->isNullValue();
3198     IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3199     LLVM_FALLTHROUGH;
3200   }
3201   case ISD::SETLT: {
3202     // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63)
3203     // (sext (setcc %a, 1, setgt))  -> (add (lshr (- %a), 63), -1)
3204     // (sext (setcc %a, 0, setgt))  -> (ashr %a, 31)
3205     if (IsRHSOne) {
3206       if (CmpInGPR == ICGPR_NonExtIn)
3207         return SDValue();
3208       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3209     }
3210     if (IsRHSZero)
3211       return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS,
3212                                             S->getI32Imm(31, dl)), 0);
3213 
3214     if (CmpInGPR == ICGPR_NonExtIn)
3215       return SDValue();
3216     // The upper 32-bits of the register can't be undefined for this sequence.
3217     LHS = signExtendInputIfNeeded(LHS);
3218     RHS = signExtendInputIfNeeded(RHS);
3219     SDValue SUBFNode =
3220       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3221     return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3222                                           SUBFNode, S->getI64Imm(63, dl)), 0);
3223   }
3224   case ISD::SETUGE:
3225     // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1)
3226     // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1)
3227     std::swap(LHS, RHS);
3228     LLVM_FALLTHROUGH;
3229   case ISD::SETULE: {
3230     if (CmpInGPR == ICGPR_NonExtIn)
3231       return SDValue();
3232     // The upper 32-bits of the register can't be undefined for this sequence.
3233     LHS = zeroExtendInputIfNeeded(LHS);
3234     RHS = zeroExtendInputIfNeeded(RHS);
3235     SDValue Subtract =
3236       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3237     SDValue Shift =
3238       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract,
3239                                      S->getI32Imm(1, dl), S->getI32Imm(63,dl)),
3240               0);
3241     return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift,
3242                                           S->getI32Imm(-1, dl)), 0);
3243   }
3244   case ISD::SETUGT:
3245     // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63)
3246     // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63)
3247     std::swap(LHS, RHS);
3248     LLVM_FALLTHROUGH;
3249   case ISD::SETULT: {
3250     if (CmpInGPR == ICGPR_NonExtIn)
3251       return SDValue();
3252     // The upper 32-bits of the register can't be undefined for this sequence.
3253     LHS = zeroExtendInputIfNeeded(LHS);
3254     RHS = zeroExtendInputIfNeeded(RHS);
3255     SDValue Subtract =
3256       SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3257     return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3258                                           Subtract, S->getI64Imm(63, dl)), 0);
3259   }
3260   }
3261 }
3262 
3263 /// Produces a zero-extended result of comparing two 64-bit values according to
3264 /// the passed condition code.
3265 SDValue
3266 IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS,
3267                                               ISD::CondCode CC,
3268                                               int64_t RHSValue, SDLoc dl) {
3269   if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3270       CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext)
3271     return SDValue();
3272   bool IsRHSZero = RHSValue == 0;
3273   bool IsRHSOne = RHSValue == 1;
3274   bool IsRHSNegOne = RHSValue == -1LL;
3275   switch (CC) {
3276   default: return SDValue();
3277   case ISD::SETEQ: {
3278     // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
3279     // (zext (setcc %a, 0, seteq)) ->  (lshr (ctlz %a), 6)
3280     SDValue Xor = IsRHSZero ? LHS :
3281       SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3282     SDValue Clz =
3283       SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
3284     return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
3285                                           S->getI64Imm(58, dl),
3286                                           S->getI64Imm(63, dl)), 0);
3287   }
3288   case ISD::SETNE: {
3289     // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3290     // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)
3291     // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3292     // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3293     SDValue Xor = IsRHSZero ? LHS :
3294       SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3295     SDValue AC =
3296       SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3297                                      Xor, S->getI32Imm(~0U, dl)), 0);
3298     return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,
3299                                           Xor, AC.getValue(1)), 0);
3300   }
3301   case ISD::SETGE: {
3302     // {subc.reg, subc.CA} = (subcarry %a, %b)
3303     // (zext (setcc %a, %b, setge)) ->
3304     //   (adde (lshr %b, 63), (ashr %a, 63), subc.CA)
3305     // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63)
3306     if (IsRHSZero)
3307       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3308     std::swap(LHS, RHS);
3309     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3310     IsRHSZero = RHSConst && RHSConst->isNullValue();
3311     LLVM_FALLTHROUGH;
3312   }
3313   case ISD::SETLE: {
3314     // {subc.reg, subc.CA} = (subcarry %b, %a)
3315     // (zext (setcc %a, %b, setge)) ->
3316     //   (adde (lshr %a, 63), (ashr %b, 63), subc.CA)
3317     // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63)
3318     if (IsRHSZero)
3319       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3320     SDValue ShiftL =
3321       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3322                                      S->getI64Imm(1, dl),
3323                                      S->getI64Imm(63, dl)), 0);
3324     SDValue ShiftR =
3325       SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3326                                      S->getI64Imm(63, dl)), 0);
3327     SDValue SubtractCarry =
3328       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3329                                      LHS, RHS), 1);
3330     return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3331                                           ShiftR, ShiftL, SubtractCarry), 0);
3332   }
3333   case ISD::SETGT: {
3334     // {subc.reg, subc.CA} = (subcarry %b, %a)
3335     // (zext (setcc %a, %b, setgt)) ->
3336     //   (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3337     // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63)
3338     if (IsRHSNegOne)
3339       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3340     if (IsRHSZero) {
3341       SDValue Addi =
3342         SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3343                                        S->getI64Imm(~0ULL, dl)), 0);
3344       SDValue Nor =
3345         SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0);
3346       return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor,
3347                                             S->getI64Imm(1, dl),
3348                                             S->getI64Imm(63, dl)), 0);
3349     }
3350     std::swap(LHS, RHS);
3351     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3352     IsRHSZero = RHSConst && RHSConst->isNullValue();
3353     IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3354     LLVM_FALLTHROUGH;
3355   }
3356   case ISD::SETLT: {
3357     // {subc.reg, subc.CA} = (subcarry %a, %b)
3358     // (zext (setcc %a, %b, setlt)) ->
3359     //   (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3360     // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63)
3361     if (IsRHSOne)
3362       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3363     if (IsRHSZero)
3364       return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3365                                             S->getI64Imm(1, dl),
3366                                             S->getI64Imm(63, dl)), 0);
3367     SDValue SRADINode =
3368       SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3369                                      LHS, S->getI64Imm(63, dl)), 0);
3370     SDValue SRDINode =
3371       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3372                                      RHS, S->getI64Imm(1, dl),
3373                                      S->getI64Imm(63, dl)), 0);
3374     SDValue SUBFC8Carry =
3375       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3376                                      RHS, LHS), 1);
3377     SDValue ADDE8Node =
3378       SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3379                                      SRDINode, SRADINode, SUBFC8Carry), 0);
3380     return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3381                                           ADDE8Node, S->getI64Imm(1, dl)), 0);
3382   }
3383   case ISD::SETUGE:
3384     // {subc.reg, subc.CA} = (subcarry %a, %b)
3385     // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1)
3386     std::swap(LHS, RHS);
3387     LLVM_FALLTHROUGH;
3388   case ISD::SETULE: {
3389     // {subc.reg, subc.CA} = (subcarry %b, %a)
3390     // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1)
3391     SDValue SUBFC8Carry =
3392       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3393                                      LHS, RHS), 1);
3394     SDValue SUBFE8Node =
3395       SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue,
3396                                      LHS, LHS, SUBFC8Carry), 0);
3397     return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64,
3398                                           SUBFE8Node, S->getI64Imm(1, dl)), 0);
3399   }
3400   case ISD::SETUGT:
3401     // {subc.reg, subc.CA} = (subcarry %b, %a)
3402     // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA)
3403     std::swap(LHS, RHS);
3404     LLVM_FALLTHROUGH;
3405   case ISD::SETULT: {
3406     // {subc.reg, subc.CA} = (subcarry %a, %b)
3407     // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA)
3408     SDValue SubtractCarry =
3409       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3410                                      RHS, LHS), 1);
3411     SDValue ExtSub =
3412       SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3413                                      LHS, LHS, SubtractCarry), 0);
3414     return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3415                                           ExtSub), 0);
3416   }
3417   }
3418 }
3419 
3420 /// Produces a sign-extended result of comparing two 64-bit values according to
3421 /// the passed condition code.
3422 SDValue
3423 IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS,
3424                                               ISD::CondCode CC,
3425                                               int64_t RHSValue, SDLoc dl) {
3426   if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3427       CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext)
3428     return SDValue();
3429   bool IsRHSZero = RHSValue == 0;
3430   bool IsRHSOne = RHSValue == 1;
3431   bool IsRHSNegOne = RHSValue == -1LL;
3432   switch (CC) {
3433   default: return SDValue();
3434   case ISD::SETEQ: {
3435     // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3436     // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
3437     // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3438     // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3439     SDValue AddInput = IsRHSZero ? LHS :
3440       SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3441     SDValue Addic =
3442       SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3443                                      AddInput, S->getI32Imm(~0U, dl)), 0);
3444     return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
3445                                           Addic, Addic.getValue(1)), 0);
3446   }
3447   case ISD::SETNE: {
3448     // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))
3449     // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)
3450     // {subfcz.reg, subfcz.CA} = (subcarry 0, %a)
3451     // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)
3452     SDValue Xor = IsRHSZero ? LHS :
3453       SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3454     SDValue SC =
3455       SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,
3456                                      Xor, S->getI32Imm(0, dl)), 0);
3457     return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,
3458                                           SC, SC.getValue(1)), 0);
3459   }
3460   case ISD::SETGE: {
3461     // {subc.reg, subc.CA} = (subcarry %a, %b)
3462     // (zext (setcc %a, %b, setge)) ->
3463     //   (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA))
3464     // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63))
3465     if (IsRHSZero)
3466       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3467     std::swap(LHS, RHS);
3468     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3469     IsRHSZero = RHSConst && RHSConst->isNullValue();
3470     LLVM_FALLTHROUGH;
3471   }
3472   case ISD::SETLE: {
3473     // {subc.reg, subc.CA} = (subcarry %b, %a)
3474     // (zext (setcc %a, %b, setge)) ->
3475     //   (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA))
3476     // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63)
3477     if (IsRHSZero)
3478       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3479     SDValue ShiftR =
3480       SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3481                                      S->getI64Imm(63, dl)), 0);
3482     SDValue ShiftL =
3483       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3484                                      S->getI64Imm(1, dl),
3485                                      S->getI64Imm(63, dl)), 0);
3486     SDValue SubtractCarry =
3487       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3488                                      LHS, RHS), 1);
3489     SDValue Adde =
3490       SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3491                                      ShiftR, ShiftL, SubtractCarry), 0);
3492     return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0);
3493   }
3494   case ISD::SETGT: {
3495     // {subc.reg, subc.CA} = (subcarry %b, %a)
3496     // (zext (setcc %a, %b, setgt)) ->
3497     //   -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3498     // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63)
3499     if (IsRHSNegOne)
3500       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3501     if (IsRHSZero) {
3502       SDValue Add =
3503         SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3504                                        S->getI64Imm(-1, dl)), 0);
3505       SDValue Nor =
3506         SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0);
3507       return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor,
3508                                             S->getI64Imm(63, dl)), 0);
3509     }
3510     std::swap(LHS, RHS);
3511     ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3512     IsRHSZero = RHSConst && RHSConst->isNullValue();
3513     IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3514     LLVM_FALLTHROUGH;
3515   }
3516   case ISD::SETLT: {
3517     // {subc.reg, subc.CA} = (subcarry %a, %b)
3518     // (zext (setcc %a, %b, setlt)) ->
3519     //   -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3520     // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63)
3521     if (IsRHSOne)
3522       return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3523     if (IsRHSZero) {
3524       return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS,
3525                                             S->getI64Imm(63, dl)), 0);
3526     }
3527     SDValue SRADINode =
3528       SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3529                                      LHS, S->getI64Imm(63, dl)), 0);
3530     SDValue SRDINode =
3531       SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3532                                      RHS, S->getI64Imm(1, dl),
3533                                      S->getI64Imm(63, dl)), 0);
3534     SDValue SUBFC8Carry =
3535       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3536                                      RHS, LHS), 1);
3537     SDValue ADDE8Node =
3538       SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64,
3539                                      SRDINode, SRADINode, SUBFC8Carry), 0);
3540     SDValue XORI8Node =
3541       SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3542                                      ADDE8Node, S->getI64Imm(1, dl)), 0);
3543     return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3544                                           XORI8Node), 0);
3545   }
3546   case ISD::SETUGE:
3547     // {subc.reg, subc.CA} = (subcarry %a, %b)
3548     // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA)
3549     std::swap(LHS, RHS);
3550     LLVM_FALLTHROUGH;
3551   case ISD::SETULE: {
3552     // {subc.reg, subc.CA} = (subcarry %b, %a)
3553     // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA)
3554     SDValue SubtractCarry =
3555       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3556                                      LHS, RHS), 1);
3557     SDValue ExtSub =
3558       SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS,
3559                                      LHS, SubtractCarry), 0);
3560     return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64,
3561                                           ExtSub, ExtSub), 0);
3562   }
3563   case ISD::SETUGT:
3564     // {subc.reg, subc.CA} = (subcarry %b, %a)
3565     // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA)
3566     std::swap(LHS, RHS);
3567     LLVM_FALLTHROUGH;
3568   case ISD::SETULT: {
3569     // {subc.reg, subc.CA} = (subcarry %a, %b)
3570     // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA)
3571     SDValue SubCarry =
3572       SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3573                                      RHS, LHS), 1);
3574     return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3575                                      LHS, LHS, SubCarry), 0);
3576   }
3577   }
3578 }
3579 
3580 /// Do all uses of this SDValue need the result in a GPR?
3581 /// This is meant to be used on values that have type i1 since
3582 /// it is somewhat meaningless to ask if values of other types
3583 /// should be kept in GPR's.
3584 static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
3585   assert(Compare.getOpcode() == ISD::SETCC &&
3586          "An ISD::SETCC node required here.");
3587 
3588   // For values that have a single use, the caller should obviously already have
3589   // checked if that use is an extending use. We check the other uses here.
3590   if (Compare.hasOneUse())
3591     return true;
3592   // We want the value in a GPR if it is being extended, used for a select, or
3593   // used in logical operations.
3594   for (auto CompareUse : Compare.getNode()->uses())
3595     if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
3596         CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
3597         CompareUse->getOpcode() != ISD::SELECT &&
3598         !isLogicOp(CompareUse->getOpcode())) {
3599       OmittedForNonExtendUses++;
3600       return false;
3601     }
3602   return true;
3603 }
3604 
3605 /// Returns an equivalent of a SETCC node but with the result the same width as
3606 /// the inputs. This can also be used for SELECT_CC if either the true or false
3607 /// values is a power of two while the other is zero.
3608 SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare,
3609                                                 SetccInGPROpts ConvOpts) {
3610   assert((Compare.getOpcode() == ISD::SETCC ||
3611           Compare.getOpcode() == ISD::SELECT_CC) &&
3612          "An ISD::SETCC node required here.");
3613 
3614   // Don't convert this comparison to a GPR sequence because there are uses
3615   // of the i1 result (i.e. uses that require the result in the CR).
3616   if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
3617     return SDValue();
3618 
3619   SDValue LHS = Compare.getOperand(0);
3620   SDValue RHS = Compare.getOperand(1);
3621 
3622   // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
3623   int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
3624   ISD::CondCode CC =
3625     cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
3626   EVT InputVT = LHS.getValueType();
3627   if (InputVT != MVT::i32 && InputVT != MVT::i64)
3628     return SDValue();
3629 
3630   if (ConvOpts == SetccInGPROpts::ZExtInvert ||
3631       ConvOpts == SetccInGPROpts::SExtInvert)
3632     CC = ISD::getSetCCInverse(CC, InputVT);
3633 
3634   bool Inputs32Bit = InputVT == MVT::i32;
3635 
3636   SDLoc dl(Compare);
3637   ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3638   int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
3639   bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
3640     ConvOpts == SetccInGPROpts::SExtInvert;
3641 
3642   if (IsSext && Inputs32Bit)
3643     return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3644   else if (Inputs32Bit)
3645     return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3646   else if (IsSext)
3647     return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3648   return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3649 }
3650 
3651 } // end anonymous namespace
3652 
3653 bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {
3654   if (N->getValueType(0) != MVT::i32 &&
3655       N->getValueType(0) != MVT::i64)
3656     return false;
3657 
3658   // This optimization will emit code that assumes 64-bit registers
3659   // so we don't want to run it in 32-bit mode. Also don't run it
3660   // on functions that are not to be optimized.
3661   if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
3662     return false;
3663 
3664   switch (N->getOpcode()) {
3665   default: break;
3666   case ISD::ZERO_EXTEND:
3667   case ISD::SIGN_EXTEND:
3668   case ISD::AND:
3669   case ISD::OR:
3670   case ISD::XOR: {
3671     IntegerCompareEliminator ICmpElim(CurDAG, this);
3672     if (SDNode *New = ICmpElim.Select(N)) {
3673       ReplaceNode(N, New);
3674       return true;
3675     }
3676   }
3677   }
3678   return false;
3679 }
3680 
3681 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
3682   if (N->getValueType(0) != MVT::i32 &&
3683       N->getValueType(0) != MVT::i64)
3684     return false;
3685 
3686   if (!UseBitPermRewriter)
3687     return false;
3688 
3689   switch (N->getOpcode()) {
3690   default: break;
3691   case ISD::ROTL:
3692   case ISD::SHL:
3693   case ISD::SRL:
3694   case ISD::AND:
3695   case ISD::OR: {
3696     BitPermutationSelector BPS(CurDAG);
3697     if (SDNode *New = BPS.Select(N)) {
3698       ReplaceNode(N, New);
3699       return true;
3700     }
3701     return false;
3702   }
3703   }
3704 
3705   return false;
3706 }
3707 
3708 /// SelectCC - Select a comparison of the specified values with the specified
3709 /// condition code, returning the CR# of the expression.
3710 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3711                                   const SDLoc &dl) {
3712   // Always select the LHS.
3713   unsigned Opc;
3714 
3715   if (LHS.getValueType() == MVT::i32) {
3716     unsigned Imm;
3717     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3718       if (isInt32Immediate(RHS, Imm)) {
3719         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
3720         if (isUInt<16>(Imm))
3721           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
3722                                                 getI32Imm(Imm & 0xFFFF, dl)),
3723                          0);
3724         // If this is a 16-bit signed immediate, fold it.
3725         if (isInt<16>((int)Imm))
3726           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
3727                                                 getI32Imm(Imm & 0xFFFF, dl)),
3728                          0);
3729 
3730         // For non-equality comparisons, the default code would materialize the
3731         // constant, then compare against it, like this:
3732         //   lis r2, 4660
3733         //   ori r2, r2, 22136
3734         //   cmpw cr0, r3, r2
3735         // Since we are just comparing for equality, we can emit this instead:
3736         //   xoris r0,r3,0x1234
3737         //   cmplwi cr0,r0,0x5678
3738         //   beq cr0,L6
3739         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
3740                                            getI32Imm(Imm >> 16, dl)), 0);
3741         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
3742                                               getI32Imm(Imm & 0xFFFF, dl)), 0);
3743       }
3744       Opc = PPC::CMPLW;
3745     } else if (ISD::isUnsignedIntSetCC(CC)) {
3746       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
3747         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
3748                                               getI32Imm(Imm & 0xFFFF, dl)), 0);
3749       Opc = PPC::CMPLW;
3750     } else {
3751       int16_t SImm;
3752       if (isIntS16Immediate(RHS, SImm))
3753         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
3754                                               getI32Imm((int)SImm & 0xFFFF,
3755                                                         dl)),
3756                          0);
3757       Opc = PPC::CMPW;
3758     }
3759   } else if (LHS.getValueType() == MVT::i64) {
3760     uint64_t Imm;
3761     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3762       if (isInt64Immediate(RHS.getNode(), Imm)) {
3763         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
3764         if (isUInt<16>(Imm))
3765           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
3766                                                 getI32Imm(Imm & 0xFFFF, dl)),
3767                          0);
3768         // If this is a 16-bit signed immediate, fold it.
3769         if (isInt<16>(Imm))
3770           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
3771                                                 getI32Imm(Imm & 0xFFFF, dl)),
3772                          0);
3773 
3774         // For non-equality comparisons, the default code would materialize the
3775         // constant, then compare against it, like this:
3776         //   lis r2, 4660
3777         //   ori r2, r2, 22136
3778         //   cmpd cr0, r3, r2
3779         // Since we are just comparing for equality, we can emit this instead:
3780         //   xoris r0,r3,0x1234
3781         //   cmpldi cr0,r0,0x5678
3782         //   beq cr0,L6
3783         if (isUInt<32>(Imm)) {
3784           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
3785                                              getI64Imm(Imm >> 16, dl)), 0);
3786           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
3787                                                 getI64Imm(Imm & 0xFFFF, dl)),
3788                          0);
3789         }
3790       }
3791       Opc = PPC::CMPLD;
3792     } else if (ISD::isUnsignedIntSetCC(CC)) {
3793       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
3794         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
3795                                               getI64Imm(Imm & 0xFFFF, dl)), 0);
3796       Opc = PPC::CMPLD;
3797     } else {
3798       int16_t SImm;
3799       if (isIntS16Immediate(RHS, SImm))
3800         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
3801                                               getI64Imm(SImm & 0xFFFF, dl)),
3802                          0);
3803       Opc = PPC::CMPD;
3804     }
3805   } else if (LHS.getValueType() == MVT::f32) {
3806     if (Subtarget->hasSPE()) {
3807       switch (CC) {
3808         default:
3809         case ISD::SETEQ:
3810         case ISD::SETNE:
3811           Opc = PPC::EFSCMPEQ;
3812           break;
3813         case ISD::SETLT:
3814         case ISD::SETGE:
3815         case ISD::SETOLT:
3816         case ISD::SETOGE:
3817         case ISD::SETULT:
3818         case ISD::SETUGE:
3819           Opc = PPC::EFSCMPLT;
3820           break;
3821         case ISD::SETGT:
3822         case ISD::SETLE:
3823         case ISD::SETOGT:
3824         case ISD::SETOLE:
3825         case ISD::SETUGT:
3826         case ISD::SETULE:
3827           Opc = PPC::EFSCMPGT;
3828           break;
3829       }
3830     } else
3831       Opc = PPC::FCMPUS;
3832   } else if (LHS.getValueType() == MVT::f64) {
3833     if (Subtarget->hasSPE()) {
3834       switch (CC) {
3835         default:
3836         case ISD::SETEQ:
3837         case ISD::SETNE:
3838           Opc = PPC::EFDCMPEQ;
3839           break;
3840         case ISD::SETLT:
3841         case ISD::SETGE:
3842         case ISD::SETOLT:
3843         case ISD::SETOGE:
3844         case ISD::SETULT:
3845         case ISD::SETUGE:
3846           Opc = PPC::EFDCMPLT;
3847           break;
3848         case ISD::SETGT:
3849         case ISD::SETLE:
3850         case ISD::SETOGT:
3851         case ISD::SETOLE:
3852         case ISD::SETUGT:
3853         case ISD::SETULE:
3854           Opc = PPC::EFDCMPGT;
3855           break;
3856       }
3857     } else
3858       Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
3859   } else {
3860     assert(LHS.getValueType() == MVT::f128 && "Unknown vt!");
3861     assert(Subtarget->hasVSX() && "__float128 requires VSX");
3862     Opc = PPC::XSCMPUQP;
3863   }
3864   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
3865 }
3866 
3867 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT,
3868                                            const PPCSubtarget *Subtarget) {
3869   // For SPE instructions, the result is in GT bit of the CR
3870   bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();
3871 
3872   switch (CC) {
3873   case ISD::SETUEQ:
3874   case ISD::SETONE:
3875   case ISD::SETOLE:
3876   case ISD::SETOGE:
3877     llvm_unreachable("Should be lowered by legalize!");
3878   default: llvm_unreachable("Unknown condition!");
3879   case ISD::SETOEQ:
3880   case ISD::SETEQ:
3881     return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;
3882   case ISD::SETUNE:
3883   case ISD::SETNE:
3884     return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;
3885   case ISD::SETOLT:
3886   case ISD::SETLT:
3887     return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;
3888   case ISD::SETULE:
3889   case ISD::SETLE:
3890     return PPC::PRED_LE;
3891   case ISD::SETOGT:
3892   case ISD::SETGT:
3893     return PPC::PRED_GT;
3894   case ISD::SETUGE:
3895   case ISD::SETGE:
3896     return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;
3897   case ISD::SETO:   return PPC::PRED_NU;
3898   case ISD::SETUO:  return PPC::PRED_UN;
3899     // These two are invalid for floating point.  Assume we have int.
3900   case ISD::SETULT: return PPC::PRED_LT;
3901   case ISD::SETUGT: return PPC::PRED_GT;
3902   }
3903 }
3904 
3905 /// getCRIdxForSetCC - Return the index of the condition register field
3906 /// associated with the SetCC condition, and whether or not the field is
3907 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
3908 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
3909   Invert = false;
3910   switch (CC) {
3911   default: llvm_unreachable("Unknown condition!");
3912   case ISD::SETOLT:
3913   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
3914   case ISD::SETOGT:
3915   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
3916   case ISD::SETOEQ:
3917   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
3918   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
3919   case ISD::SETUGE:
3920   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
3921   case ISD::SETULE:
3922   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
3923   case ISD::SETUNE:
3924   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
3925   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
3926   case ISD::SETUEQ:
3927   case ISD::SETOGE:
3928   case ISD::SETOLE:
3929   case ISD::SETONE:
3930     llvm_unreachable("Invalid branch code: should be expanded by legalize");
3931   // These are invalid for floating point.  Assume integer.
3932   case ISD::SETULT: return 0;
3933   case ISD::SETUGT: return 1;
3934   }
3935 }
3936 
3937 // getVCmpInst: return the vector compare instruction for the specified
3938 // vector type and condition code. Since this is for altivec specific code,
3939 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
3940 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
3941                                 bool HasVSX, bool &Swap, bool &Negate) {
3942   Swap = false;
3943   Negate = false;
3944 
3945   if (VecVT.isFloatingPoint()) {
3946     /* Handle some cases by swapping input operands.  */
3947     switch (CC) {
3948       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
3949       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
3950       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
3951       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
3952       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
3953       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
3954       default: break;
3955     }
3956     /* Handle some cases by negating the result.  */
3957     switch (CC) {
3958       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
3959       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
3960       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
3961       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
3962       default: break;
3963     }
3964     /* We have instructions implementing the remaining cases.  */
3965     switch (CC) {
3966       case ISD::SETEQ:
3967       case ISD::SETOEQ:
3968         if (VecVT == MVT::v4f32)
3969           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
3970         else if (VecVT == MVT::v2f64)
3971           return PPC::XVCMPEQDP;
3972         break;
3973       case ISD::SETGT:
3974       case ISD::SETOGT:
3975         if (VecVT == MVT::v4f32)
3976           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
3977         else if (VecVT == MVT::v2f64)
3978           return PPC::XVCMPGTDP;
3979         break;
3980       case ISD::SETGE:
3981       case ISD::SETOGE:
3982         if (VecVT == MVT::v4f32)
3983           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
3984         else if (VecVT == MVT::v2f64)
3985           return PPC::XVCMPGEDP;
3986         break;
3987       default:
3988         break;
3989     }
3990     llvm_unreachable("Invalid floating-point vector compare condition");
3991   } else {
3992     /* Handle some cases by swapping input operands.  */
3993     switch (CC) {
3994       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
3995       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
3996       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
3997       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
3998       default: break;
3999     }
4000     /* Handle some cases by negating the result.  */
4001     switch (CC) {
4002       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4003       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
4004       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
4005       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
4006       default: break;
4007     }
4008     /* We have instructions implementing the remaining cases.  */
4009     switch (CC) {
4010       case ISD::SETEQ:
4011       case ISD::SETUEQ:
4012         if (VecVT == MVT::v16i8)
4013           return PPC::VCMPEQUB;
4014         else if (VecVT == MVT::v8i16)
4015           return PPC::VCMPEQUH;
4016         else if (VecVT == MVT::v4i32)
4017           return PPC::VCMPEQUW;
4018         else if (VecVT == MVT::v2i64)
4019           return PPC::VCMPEQUD;
4020         break;
4021       case ISD::SETGT:
4022         if (VecVT == MVT::v16i8)
4023           return PPC::VCMPGTSB;
4024         else if (VecVT == MVT::v8i16)
4025           return PPC::VCMPGTSH;
4026         else if (VecVT == MVT::v4i32)
4027           return PPC::VCMPGTSW;
4028         else if (VecVT == MVT::v2i64)
4029           return PPC::VCMPGTSD;
4030         break;
4031       case ISD::SETUGT:
4032         if (VecVT == MVT::v16i8)
4033           return PPC::VCMPGTUB;
4034         else if (VecVT == MVT::v8i16)
4035           return PPC::VCMPGTUH;
4036         else if (VecVT == MVT::v4i32)
4037           return PPC::VCMPGTUW;
4038         else if (VecVT == MVT::v2i64)
4039           return PPC::VCMPGTUD;
4040         break;
4041       default:
4042         break;
4043     }
4044     llvm_unreachable("Invalid integer vector compare condition");
4045   }
4046 }
4047 
4048 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
4049   SDLoc dl(N);
4050   unsigned Imm;
4051   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4052   EVT PtrVT =
4053       CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
4054   bool isPPC64 = (PtrVT == MVT::i64);
4055 
4056   if (!Subtarget->useCRBits() && isInt32Immediate(N->getOperand(1), Imm)) {
4057     // We can codegen setcc op, imm very efficiently compared to a brcond.
4058     // Check for those cases here.
4059     // setcc op, 0
4060     if (Imm == 0) {
4061       SDValue Op = N->getOperand(0);
4062       switch (CC) {
4063       default: break;
4064       case ISD::SETEQ: {
4065         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
4066         SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
4067                           getI32Imm(31, dl) };
4068         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4069         return true;
4070       }
4071       case ISD::SETNE: {
4072         if (isPPC64) break;
4073         SDValue AD =
4074           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4075                                          Op, getI32Imm(~0U, dl)), 0);
4076         CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
4077         return true;
4078       }
4079       case ISD::SETLT: {
4080         SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4081                           getI32Imm(31, dl) };
4082         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4083         return true;
4084       }
4085       case ISD::SETGT: {
4086         SDValue T =
4087           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
4088         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
4089         SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
4090                           getI32Imm(31, dl) };
4091         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4092         return true;
4093       }
4094       }
4095     } else if (Imm == ~0U) {        // setcc op, -1
4096       SDValue Op = N->getOperand(0);
4097       switch (CC) {
4098       default: break;
4099       case ISD::SETEQ:
4100         if (isPPC64) break;
4101         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4102                                             Op, getI32Imm(1, dl)), 0);
4103         CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
4104                              SDValue(CurDAG->getMachineNode(PPC::LI, dl,
4105                                                             MVT::i32,
4106                                                             getI32Imm(0, dl)),
4107                                      0), Op.getValue(1));
4108         return true;
4109       case ISD::SETNE: {
4110         if (isPPC64) break;
4111         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
4112         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4113                                             Op, getI32Imm(~0U, dl));
4114         CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
4115                              SDValue(AD, 1));
4116         return true;
4117       }
4118       case ISD::SETLT: {
4119         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
4120                                                     getI32Imm(1, dl)), 0);
4121         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
4122                                                     Op), 0);
4123         SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
4124                           getI32Imm(31, dl) };
4125         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4126         return true;
4127       }
4128       case ISD::SETGT: {
4129         SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4130                           getI32Imm(31, dl) };
4131         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4132         CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
4133         return true;
4134       }
4135       }
4136     }
4137   }
4138 
4139   SDValue LHS = N->getOperand(0);
4140   SDValue RHS = N->getOperand(1);
4141 
4142   // Altivec Vector compare instructions do not set any CR register by default and
4143   // vector compare operations return the same type as the operands.
4144   if (LHS.getValueType().isVector()) {
4145     if (Subtarget->hasQPX() || Subtarget->hasSPE())
4146       return false;
4147 
4148     EVT VecVT = LHS.getValueType();
4149     bool Swap, Negate;
4150     unsigned int VCmpInst =
4151         getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate);
4152     if (Swap)
4153       std::swap(LHS, RHS);
4154 
4155     EVT ResVT = VecVT.changeVectorElementTypeToInteger();
4156     if (Negate) {
4157       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
4158       CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
4159                            ResVT, VCmp, VCmp);
4160       return true;
4161     }
4162 
4163     CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
4164     return true;
4165   }
4166 
4167   if (Subtarget->useCRBits())
4168     return false;
4169 
4170   bool Inv;
4171   unsigned Idx = getCRIdxForSetCC(CC, Inv);
4172   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
4173   SDValue IntCR;
4174 
4175   // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that
4176   // The correct compare instruction is already set by SelectCC()
4177   if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {
4178     Idx = 1;
4179   }
4180 
4181   // Force the ccreg into CR7.
4182   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
4183 
4184   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
4185   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
4186                                InFlag).getValue(1);
4187 
4188   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
4189                                          CCReg), 0);
4190 
4191   SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
4192                       getI32Imm(31, dl), getI32Imm(31, dl) };
4193   if (!Inv) {
4194     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4195     return true;
4196   }
4197 
4198   // Get the specified bit.
4199   SDValue Tmp =
4200     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4201   CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
4202   return true;
4203 }
4204 
4205 /// Does this node represent a load/store node whose address can be represented
4206 /// with a register plus an immediate that's a multiple of \p Val:
4207 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
4208   LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
4209   StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
4210   SDValue AddrOp;
4211   if (LDN)
4212     AddrOp = LDN->getOperand(1);
4213   else if (STN)
4214     AddrOp = STN->getOperand(2);
4215 
4216   // If the address points a frame object or a frame object with an offset,
4217   // we need to check the object alignment.
4218   short Imm = 0;
4219   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(
4220           AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) :
4221                                            AddrOp)) {
4222     // If op0 is a frame index that is under aligned, we can't do it either,
4223     // because it is translated to r31 or r1 + slot + offset. We won't know the
4224     // slot number until the stack frame is finalized.
4225     const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
4226     unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value();
4227     if ((SlotAlign % Val) != 0)
4228       return false;
4229 
4230     // If we have an offset, we need further check on the offset.
4231     if (AddrOp.getOpcode() != ISD::ADD)
4232       return true;
4233   }
4234 
4235   if (AddrOp.getOpcode() == ISD::ADD)
4236     return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
4237 
4238   // If the address comes from the outside, the offset will be zero.
4239   return AddrOp.getOpcode() == ISD::CopyFromReg;
4240 }
4241 
4242 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
4243   // Transfer memoperands.
4244   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
4245   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
4246 }
4247 
4248 static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG,
4249                          bool &NeedSwapOps, bool &IsUnCmp) {
4250 
4251   assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");
4252 
4253   SDValue LHS = N->getOperand(0);
4254   SDValue RHS = N->getOperand(1);
4255   SDValue TrueRes = N->getOperand(2);
4256   SDValue FalseRes = N->getOperand(3);
4257   ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes);
4258   if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 &&
4259                      N->getSimpleValueType(0) != MVT::i32))
4260     return false;
4261 
4262   // We are looking for any of:
4263   // (select_cc lhs, rhs,  1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4264   // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4265   // (select_cc lhs, rhs,  0, (select_cc [lr]hs, [lr]hs,  1, -1, cc2), seteq)
4266   // (select_cc lhs, rhs,  0, (select_cc [lr]hs, [lr]hs, -1,  1, cc2), seteq)
4267   int64_t TrueResVal = TrueConst->getSExtValue();
4268   if ((TrueResVal < -1 || TrueResVal > 1) ||
4269       (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||
4270       (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||
4271       (TrueResVal == 0 &&
4272        (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))
4273     return false;
4274 
4275   bool InnerIsSel = FalseRes.getOpcode() == ISD::SELECT_CC;
4276   SDValue SetOrSelCC = InnerIsSel ? FalseRes : FalseRes.getOperand(0);
4277   if (SetOrSelCC.getOpcode() != ISD::SETCC &&
4278       SetOrSelCC.getOpcode() != ISD::SELECT_CC)
4279     return false;
4280 
4281   // Without this setb optimization, the outer SELECT_CC will be manually
4282   // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass
4283   // transforms pseudo instruction to isel instruction. When there are more than
4284   // one use for result like zext/sext, with current optimization we only see
4285   // isel is replaced by setb but can't see any significant gain. Since
4286   // setb has longer latency than original isel, we should avoid this. Another
4287   // point is that setb requires comparison always kept, it can break the
4288   // opportunity to get the comparison away if we have in future.
4289   if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))
4290     return false;
4291 
4292   SDValue InnerLHS = SetOrSelCC.getOperand(0);
4293   SDValue InnerRHS = SetOrSelCC.getOperand(1);
4294   ISD::CondCode InnerCC =
4295       cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get();
4296   // If the inner comparison is a select_cc, make sure the true/false values are
4297   // 1/-1 and canonicalize it if needed.
4298   if (InnerIsSel) {
4299     ConstantSDNode *SelCCTrueConst =
4300         dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2));
4301     ConstantSDNode *SelCCFalseConst =
4302         dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3));
4303     if (!SelCCTrueConst || !SelCCFalseConst)
4304       return false;
4305     int64_t SelCCTVal = SelCCTrueConst->getSExtValue();
4306     int64_t SelCCFVal = SelCCFalseConst->getSExtValue();
4307     // The values must be -1/1 (requiring a swap) or 1/-1.
4308     if (SelCCTVal == -1 && SelCCFVal == 1) {
4309       std::swap(InnerLHS, InnerRHS);
4310     } else if (SelCCTVal != 1 || SelCCFVal != -1)
4311       return false;
4312   }
4313 
4314   // Canonicalize unsigned case
4315   if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {
4316     IsUnCmp = true;
4317     InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;
4318   }
4319 
4320   bool InnerSwapped = false;
4321   if (LHS == InnerRHS && RHS == InnerLHS)
4322     InnerSwapped = true;
4323   else if (LHS != InnerLHS || RHS != InnerRHS)
4324     return false;
4325 
4326   switch (CC) {
4327   // (select_cc lhs, rhs,  0, \
4328   //     (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)
4329   case ISD::SETEQ:
4330     if (!InnerIsSel)
4331       return false;
4332     if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)
4333       return false;
4334     NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;
4335     break;
4336 
4337   // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4338   // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)
4339   // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)
4340   // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4341   // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)
4342   // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)
4343   case ISD::SETULT:
4344     if (!IsUnCmp && InnerCC != ISD::SETNE)
4345       return false;
4346     IsUnCmp = true;
4347     LLVM_FALLTHROUGH;
4348   case ISD::SETLT:
4349     if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||
4350         (InnerCC == ISD::SETLT && InnerSwapped))
4351       NeedSwapOps = (TrueResVal == 1);
4352     else
4353       return false;
4354     break;
4355 
4356   // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4357   // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)
4358   // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)
4359   // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4360   // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)
4361   // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)
4362   case ISD::SETUGT:
4363     if (!IsUnCmp && InnerCC != ISD::SETNE)
4364       return false;
4365     IsUnCmp = true;
4366     LLVM_FALLTHROUGH;
4367   case ISD::SETGT:
4368     if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||
4369         (InnerCC == ISD::SETGT && InnerSwapped))
4370       NeedSwapOps = (TrueResVal == -1);
4371     else
4372       return false;
4373     break;
4374 
4375   default:
4376     return false;
4377   }
4378 
4379   LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");
4380   LLVM_DEBUG(N->dump());
4381 
4382   return true;
4383 }
4384 
4385 bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {
4386   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4387   unsigned Imm;
4388   if (!isInt32Immediate(N->getOperand(1), Imm))
4389     return false;
4390 
4391   SDLoc dl(N);
4392   SDValue Val = N->getOperand(0);
4393   unsigned SH, MB, ME;
4394   // If this is an and of a value rotated between 0 and 31 bits and then and'd
4395   // with a mask, emit rlwinm
4396   if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) {
4397     Val = Val.getOperand(0);
4398     SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
4399                      getI32Imm(ME, dl)};
4400     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4401     return true;
4402   }
4403 
4404   // If this is just a masked value where the input is not handled, and
4405   // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4406   if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {
4407     SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl),
4408                      getI32Imm(ME, dl)};
4409     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4410     return true;
4411   }
4412 
4413   // AND X, 0 -> 0, not "rlwinm 32".
4414   if (Imm == 0) {
4415     ReplaceUses(SDValue(N, 0), N->getOperand(1));
4416     return true;
4417   }
4418 
4419   return false;
4420 }
4421 
4422 bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) {
4423   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4424   uint64_t Imm64;
4425   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
4426     return false;
4427 
4428   unsigned MB, ME;
4429   if (isRunOfOnes64(Imm64, MB, ME) && MB >= 32 && MB <= ME) {
4430     //                MB  ME
4431     // +----------------------+
4432     // |xxxxxxxxxxx00011111000|
4433     // +----------------------+
4434     //  0         32         64
4435     // We can only do it if the MB is larger than 32 and MB <= ME
4436     // as RLWINM will replace the contents of [0 - 32) with [32 - 64) even
4437     // we didn't rotate it.
4438     SDLoc dl(N);
4439     SDValue Ops[] = {N->getOperand(0), getI64Imm(0, dl), getI64Imm(MB - 32, dl),
4440                      getI64Imm(ME - 32, dl)};
4441     CurDAG->SelectNodeTo(N, PPC::RLWINM8, MVT::i64, Ops);
4442     return true;
4443   }
4444 
4445   return false;
4446 }
4447 
4448 bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) {
4449   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4450   uint64_t Imm64;
4451   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
4452     return false;
4453 
4454   // Do nothing if it is 16-bit imm as the pattern in the .td file handle
4455   // it well with "andi.".
4456   if (isUInt<16>(Imm64))
4457     return false;
4458 
4459   SDLoc Loc(N);
4460   SDValue Val = N->getOperand(0);
4461 
4462   // Optimized with two rldicl's as follows:
4463   // Add missing bits on left to the mask and check that the mask is a
4464   // wrapped run of ones, i.e.
4465   // Change pattern |0001111100000011111111|
4466   //             to |1111111100000011111111|.
4467   unsigned NumOfLeadingZeros = countLeadingZeros(Imm64);
4468   if (NumOfLeadingZeros != 0)
4469     Imm64 |= maskLeadingOnes<uint64_t>(NumOfLeadingZeros);
4470 
4471   unsigned MB, ME;
4472   if (!isRunOfOnes64(Imm64, MB, ME))
4473     return false;
4474 
4475   //         ME     MB                   MB-ME+63
4476   // +----------------------+     +----------------------+
4477   // |1111111100000011111111| ->  |0000001111111111111111|
4478   // +----------------------+     +----------------------+
4479   //  0                    63      0                    63
4480   // There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between.
4481   unsigned OnesOnLeft = ME + 1;
4482   unsigned ZerosInBetween = (MB - ME + 63) & 63;
4483   // Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear
4484   // on the left the bits that are already zeros in the mask.
4485   Val = SDValue(CurDAG->getMachineNode(PPC::RLDICL, Loc, MVT::i64, Val,
4486                                        getI64Imm(OnesOnLeft, Loc),
4487                                        getI64Imm(ZerosInBetween, Loc)),
4488                 0);
4489   //        MB-ME+63                      ME     MB
4490   // +----------------------+     +----------------------+
4491   // |0000001111111111111111| ->  |0001111100000011111111|
4492   // +----------------------+     +----------------------+
4493   //  0                    63      0                    63
4494   // Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the
4495   // left the number of ones we previously added.
4496   SDValue Ops[] = {Val, getI64Imm(64 - OnesOnLeft, Loc),
4497                    getI64Imm(NumOfLeadingZeros, Loc)};
4498   CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
4499   return true;
4500 }
4501 
4502 bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) {
4503   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4504   unsigned Imm;
4505   if (!isInt32Immediate(N->getOperand(1), Imm))
4506     return false;
4507 
4508   SDValue Val = N->getOperand(0);
4509   unsigned Imm2;
4510   // ISD::OR doesn't get all the bitfield insertion fun.
4511   // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
4512   // bitfield insert.
4513   if (Val.getOpcode() != ISD::OR || !isInt32Immediate(Val.getOperand(1), Imm2))
4514     return false;
4515 
4516   // The idea here is to check whether this is equivalent to:
4517   //   (c1 & m) | (x & ~m)
4518   // where m is a run-of-ones mask. The logic here is that, for each bit in
4519   // c1 and c2:
4520   //  - if both are 1, then the output will be 1.
4521   //  - if both are 0, then the output will be 0.
4522   //  - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
4523   //    come from x.
4524   //  - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
4525   //    be 0.
4526   //  If that last condition is never the case, then we can form m from the
4527   //  bits that are the same between c1 and c2.
4528   unsigned MB, ME;
4529   if (isRunOfOnes(~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) {
4530     SDLoc dl(N);
4531     SDValue Ops[] = {Val.getOperand(0), Val.getOperand(1), getI32Imm(0, dl),
4532                      getI32Imm(MB, dl), getI32Imm(ME, dl)};
4533     ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
4534     return true;
4535   }
4536 
4537   return false;
4538 }
4539 
4540 bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) {
4541   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4542   uint64_t Imm64;
4543   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))
4544     return false;
4545 
4546   // If this is a 64-bit zero-extension mask, emit rldicl.
4547   unsigned MB = 64 - countTrailingOnes(Imm64);
4548   unsigned SH = 0;
4549   unsigned Imm;
4550   SDValue Val = N->getOperand(0);
4551   SDLoc dl(N);
4552 
4553   if (Val.getOpcode() == ISD::ANY_EXTEND) {
4554     auto Op0 = Val.getOperand(0);
4555     if (Op0.getOpcode() == ISD::SRL &&
4556         isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
4557 
4558       auto ResultType = Val.getNode()->getValueType(0);
4559       auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, ResultType);
4560       SDValue IDVal(ImDef, 0);
4561 
4562       Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, ResultType,
4563                                            IDVal, Op0.getOperand(0),
4564                                            getI32Imm(1, dl)),
4565                     0);
4566       SH = 64 - Imm;
4567     }
4568   }
4569 
4570   // If the operand is a logical right shift, we can fold it into this
4571   // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
4572   // for n <= mb. The right shift is really a left rotate followed by a
4573   // mask, and this mask is a more-restrictive sub-mask of the mask implied
4574   // by the shift.
4575   if (Val.getOpcode() == ISD::SRL &&
4576       isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
4577     assert(Imm < 64 && "Illegal shift amount");
4578     Val = Val.getOperand(0);
4579     SH = 64 - Imm;
4580   }
4581 
4582   SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl)};
4583   CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
4584   return true;
4585 }
4586 
4587 bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) {
4588   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4589   uint64_t Imm64;
4590   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
4591       !isMask_64(~Imm64))
4592     return false;
4593 
4594   // If this is a negated 64-bit zero-extension mask,
4595   // i.e. the immediate is a sequence of ones from most significant side
4596   // and all zero for reminder, we should use rldicr.
4597   unsigned MB = 63 - countTrailingOnes(~Imm64);
4598   unsigned SH = 0;
4599   SDLoc dl(N);
4600   SDValue Ops[] = {N->getOperand(0), getI32Imm(SH, dl), getI32Imm(MB, dl)};
4601   CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
4602   return true;
4603 }
4604 
4605 bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) {
4606   assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected");
4607   uint64_t Imm64;
4608   unsigned MB, ME;
4609   SDValue N0 = N->getOperand(0);
4610 
4611   // We won't get fewer instructions if the imm is 32-bit integer.
4612   // rldimi requires the imm to have consecutive ones with both sides zero.
4613   // Also, make sure the first Op has only one use, otherwise this may increase
4614   // register pressure since rldimi is destructive.
4615   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
4616       isUInt<32>(Imm64) || !isRunOfOnes64(Imm64, MB, ME) || !N0.hasOneUse())
4617     return false;
4618 
4619   unsigned SH = 63 - ME;
4620   SDLoc Dl(N);
4621   // Use select64Imm for making LI instr instead of directly putting Imm64
4622   SDValue Ops[] = {
4623       N->getOperand(0),
4624       SDValue(selectI64Imm(CurDAG, getI64Imm(-1, Dl).getNode()), 0),
4625       getI32Imm(SH, Dl), getI32Imm(MB, Dl)};
4626   CurDAG->SelectNodeTo(N, PPC::RLDIMI, MVT::i64, Ops);
4627   return true;
4628 }
4629 
4630 // Select - Convert the specified operand from a target-independent to a
4631 // target-specific node if it hasn't already been changed.
4632 void PPCDAGToDAGISel::Select(SDNode *N) {
4633   SDLoc dl(N);
4634   if (N->isMachineOpcode()) {
4635     N->setNodeId(-1);
4636     return;   // Already selected.
4637   }
4638 
4639   // In case any misguided DAG-level optimizations form an ADD with a
4640   // TargetConstant operand, crash here instead of miscompiling (by selecting
4641   // an r+r add instead of some kind of r+i add).
4642   if (N->getOpcode() == ISD::ADD &&
4643       N->getOperand(1).getOpcode() == ISD::TargetConstant)
4644     llvm_unreachable("Invalid ADD with TargetConstant operand");
4645 
4646   // Try matching complex bit permutations before doing anything else.
4647   if (tryBitPermutation(N))
4648     return;
4649 
4650   // Try to emit integer compares as GPR-only sequences (i.e. no use of CR).
4651   if (tryIntCompareInGPR(N))
4652     return;
4653 
4654   switch (N->getOpcode()) {
4655   default: break;
4656 
4657   case ISD::Constant:
4658     if (N->getValueType(0) == MVT::i64) {
4659       ReplaceNode(N, selectI64Imm(CurDAG, N));
4660       return;
4661     }
4662     break;
4663 
4664   case ISD::SETCC:
4665     if (trySETCC(N))
4666       return;
4667     break;
4668   // These nodes will be transformed into GETtlsADDR32 node, which
4669   // later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT
4670   case PPCISD::ADDI_TLSLD_L_ADDR:
4671   case PPCISD::ADDI_TLSGD_L_ADDR: {
4672     const Module *Mod = MF->getFunction().getParent();
4673     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
4674         !Subtarget->isSecurePlt() || !Subtarget->isTargetELF() ||
4675         Mod->getPICLevel() == PICLevel::SmallPIC)
4676       break;
4677     // Attach global base pointer on GETtlsADDR32 node in order to
4678     // generate secure plt code for TLS symbols.
4679     getGlobalBaseReg();
4680   } break;
4681   case PPCISD::CALL: {
4682     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
4683         !TM.isPositionIndependent() || !Subtarget->isSecurePlt() ||
4684         !Subtarget->isTargetELF())
4685       break;
4686 
4687     SDValue Op = N->getOperand(1);
4688 
4689     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4690       if (GA->getTargetFlags() == PPCII::MO_PLT)
4691         getGlobalBaseReg();
4692     }
4693     else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
4694       if (ES->getTargetFlags() == PPCII::MO_PLT)
4695         getGlobalBaseReg();
4696     }
4697   }
4698     break;
4699 
4700   case PPCISD::GlobalBaseReg:
4701     ReplaceNode(N, getGlobalBaseReg());
4702     return;
4703 
4704   case ISD::FrameIndex:
4705     selectFrameIndex(N, N);
4706     return;
4707 
4708   case PPCISD::MFOCRF: {
4709     SDValue InFlag = N->getOperand(1);
4710     ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
4711                                           N->getOperand(0), InFlag));
4712     return;
4713   }
4714 
4715   case PPCISD::READ_TIME_BASE:
4716     ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
4717                                           MVT::Other, N->getOperand(0)));
4718     return;
4719 
4720   case PPCISD::SRA_ADDZE: {
4721     SDValue N0 = N->getOperand(0);
4722     SDValue ShiftAmt =
4723       CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
4724                                   getConstantIntValue(), dl,
4725                                   N->getValueType(0));
4726     if (N->getValueType(0) == MVT::i64) {
4727       SDNode *Op =
4728         CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
4729                                N0, ShiftAmt);
4730       CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
4731                            SDValue(Op, 1));
4732       return;
4733     } else {
4734       assert(N->getValueType(0) == MVT::i32 &&
4735              "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
4736       SDNode *Op =
4737         CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
4738                                N0, ShiftAmt);
4739       CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
4740                            SDValue(Op, 1));
4741       return;
4742     }
4743   }
4744 
4745   case ISD::STORE: {
4746     // Change TLS initial-exec D-form stores to X-form stores.
4747     StoreSDNode *ST = cast<StoreSDNode>(N);
4748     if (EnableTLSOpt && Subtarget->isELFv2ABI() &&
4749         ST->getAddressingMode() != ISD::PRE_INC)
4750       if (tryTLSXFormStore(ST))
4751         return;
4752     break;
4753   }
4754   case ISD::LOAD: {
4755     // Handle preincrement loads.
4756     LoadSDNode *LD = cast<LoadSDNode>(N);
4757     EVT LoadedVT = LD->getMemoryVT();
4758 
4759     // Normal loads are handled by code generated from the .td file.
4760     if (LD->getAddressingMode() != ISD::PRE_INC) {
4761       // Change TLS initial-exec D-form loads to X-form loads.
4762       if (EnableTLSOpt && Subtarget->isELFv2ABI())
4763         if (tryTLSXFormLoad(LD))
4764           return;
4765       break;
4766     }
4767 
4768     SDValue Offset = LD->getOffset();
4769     if (Offset.getOpcode() == ISD::TargetConstant ||
4770         Offset.getOpcode() == ISD::TargetGlobalAddress) {
4771 
4772       unsigned Opcode;
4773       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
4774       if (LD->getValueType(0) != MVT::i64) {
4775         // Handle PPC32 integer and normal FP loads.
4776         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
4777         switch (LoadedVT.getSimpleVT().SimpleTy) {
4778           default: llvm_unreachable("Invalid PPC load type!");
4779           case MVT::f64: Opcode = PPC::LFDU; break;
4780           case MVT::f32: Opcode = PPC::LFSU; break;
4781           case MVT::i32: Opcode = PPC::LWZU; break;
4782           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
4783           case MVT::i1:
4784           case MVT::i8:  Opcode = PPC::LBZU; break;
4785         }
4786       } else {
4787         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
4788         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
4789         switch (LoadedVT.getSimpleVT().SimpleTy) {
4790           default: llvm_unreachable("Invalid PPC load type!");
4791           case MVT::i64: Opcode = PPC::LDU; break;
4792           case MVT::i32: Opcode = PPC::LWZU8; break;
4793           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
4794           case MVT::i1:
4795           case MVT::i8:  Opcode = PPC::LBZU8; break;
4796         }
4797       }
4798 
4799       SDValue Chain = LD->getChain();
4800       SDValue Base = LD->getBasePtr();
4801       SDValue Ops[] = { Offset, Base, Chain };
4802       SDNode *MN = CurDAG->getMachineNode(
4803           Opcode, dl, LD->getValueType(0),
4804           PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
4805       transferMemOperands(N, MN);
4806       ReplaceNode(N, MN);
4807       return;
4808     } else {
4809       unsigned Opcode;
4810       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
4811       if (LD->getValueType(0) != MVT::i64) {
4812         // Handle PPC32 integer and normal FP loads.
4813         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
4814         switch (LoadedVT.getSimpleVT().SimpleTy) {
4815           default: llvm_unreachable("Invalid PPC load type!");
4816           case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
4817           case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
4818           case MVT::f64: Opcode = PPC::LFDUX; break;
4819           case MVT::f32: Opcode = PPC::LFSUX; break;
4820           case MVT::i32: Opcode = PPC::LWZUX; break;
4821           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
4822           case MVT::i1:
4823           case MVT::i8:  Opcode = PPC::LBZUX; break;
4824         }
4825       } else {
4826         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
4827         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
4828                "Invalid sext update load");
4829         switch (LoadedVT.getSimpleVT().SimpleTy) {
4830           default: llvm_unreachable("Invalid PPC load type!");
4831           case MVT::i64: Opcode = PPC::LDUX; break;
4832           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
4833           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
4834           case MVT::i1:
4835           case MVT::i8:  Opcode = PPC::LBZUX8; break;
4836         }
4837       }
4838 
4839       SDValue Chain = LD->getChain();
4840       SDValue Base = LD->getBasePtr();
4841       SDValue Ops[] = { Base, Offset, Chain };
4842       SDNode *MN = CurDAG->getMachineNode(
4843           Opcode, dl, LD->getValueType(0),
4844           PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
4845       transferMemOperands(N, MN);
4846       ReplaceNode(N, MN);
4847       return;
4848     }
4849   }
4850 
4851   case ISD::AND:
4852     // If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr
4853     if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDICL(N) ||
4854         tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) || tryAsPairOfRLDICL(N))
4855       return;
4856 
4857     // Other cases are autogenerated.
4858     break;
4859   case ISD::OR: {
4860     if (N->getValueType(0) == MVT::i32)
4861       if (tryBitfieldInsert(N))
4862         return;
4863 
4864     int16_t Imm;
4865     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
4866         isIntS16Immediate(N->getOperand(1), Imm)) {
4867       KnownBits LHSKnown = CurDAG->computeKnownBits(N->getOperand(0));
4868 
4869       // If this is equivalent to an add, then we can fold it with the
4870       // FrameIndex calculation.
4871       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
4872         selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
4873         return;
4874       }
4875     }
4876 
4877     // If this is 'or' against an imm with consecutive ones and both sides zero,
4878     // try to emit rldimi
4879     if (tryAsSingleRLDIMI(N))
4880       return;
4881 
4882     // OR with a 32-bit immediate can be handled by ori + oris
4883     // without creating an immediate in a GPR.
4884     uint64_t Imm64 = 0;
4885     bool IsPPC64 = Subtarget->isPPC64();
4886     if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
4887         (Imm64 & ~0xFFFFFFFFuLL) == 0) {
4888       // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.
4889       uint64_t ImmHi = Imm64 >> 16;
4890       uint64_t ImmLo = Imm64 & 0xFFFF;
4891       if (ImmHi != 0 && ImmLo != 0) {
4892         SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
4893                                             N->getOperand(0),
4894                                             getI16Imm(ImmLo, dl));
4895         SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
4896         CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1);
4897         return;
4898       }
4899     }
4900 
4901     // Other cases are autogenerated.
4902     break;
4903   }
4904   case ISD::XOR: {
4905     // XOR with a 32-bit immediate can be handled by xori + xoris
4906     // without creating an immediate in a GPR.
4907     uint64_t Imm64 = 0;
4908     bool IsPPC64 = Subtarget->isPPC64();
4909     if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
4910         (Imm64 & ~0xFFFFFFFFuLL) == 0) {
4911       // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.
4912       uint64_t ImmHi = Imm64 >> 16;
4913       uint64_t ImmLo = Imm64 & 0xFFFF;
4914       if (ImmHi != 0 && ImmLo != 0) {
4915         SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
4916                                             N->getOperand(0),
4917                                             getI16Imm(ImmLo, dl));
4918         SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
4919         CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1);
4920         return;
4921       }
4922     }
4923 
4924     break;
4925   }
4926   case ISD::ADD: {
4927     int16_t Imm;
4928     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
4929         isIntS16Immediate(N->getOperand(1), Imm)) {
4930       selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
4931       return;
4932     }
4933 
4934     break;
4935   }
4936   case ISD::SHL: {
4937     unsigned Imm, SH, MB, ME;
4938     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
4939         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
4940       SDValue Ops[] = { N->getOperand(0).getOperand(0),
4941                           getI32Imm(SH, dl), getI32Imm(MB, dl),
4942                           getI32Imm(ME, dl) };
4943       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4944       return;
4945     }
4946 
4947     // Other cases are autogenerated.
4948     break;
4949   }
4950   case ISD::SRL: {
4951     unsigned Imm, SH, MB, ME;
4952     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
4953         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
4954       SDValue Ops[] = { N->getOperand(0).getOperand(0),
4955                           getI32Imm(SH, dl), getI32Imm(MB, dl),
4956                           getI32Imm(ME, dl) };
4957       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4958       return;
4959     }
4960 
4961     // Other cases are autogenerated.
4962     break;
4963   }
4964   // FIXME: Remove this once the ANDI glue bug is fixed:
4965   case PPCISD::ANDI_rec_1_EQ_BIT:
4966   case PPCISD::ANDI_rec_1_GT_BIT: {
4967     if (!ANDIGlueBug)
4968       break;
4969 
4970     EVT InVT = N->getOperand(0).getValueType();
4971     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
4972            "Invalid input type for ANDI_rec_1_EQ_BIT");
4973 
4974     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec;
4975     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
4976                                         N->getOperand(0),
4977                                         CurDAG->getTargetConstant(1, dl, InVT)),
4978                  0);
4979     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
4980     SDValue SRIdxVal = CurDAG->getTargetConstant(
4981         N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt,
4982         dl, MVT::i32);
4983 
4984     CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
4985                          SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
4986     return;
4987   }
4988   case ISD::SELECT_CC: {
4989     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
4990     EVT PtrVT =
4991         CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
4992     bool isPPC64 = (PtrVT == MVT::i64);
4993 
4994     // If this is a select of i1 operands, we'll pattern match it.
4995     if (Subtarget->useCRBits() && N->getOperand(0).getValueType() == MVT::i1)
4996       break;
4997 
4998     if (Subtarget->isISA3_0() && Subtarget->isPPC64()) {
4999       bool NeedSwapOps = false;
5000       bool IsUnCmp = false;
5001       if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) {
5002         SDValue LHS = N->getOperand(0);
5003         SDValue RHS = N->getOperand(1);
5004         if (NeedSwapOps)
5005           std::swap(LHS, RHS);
5006 
5007         // Make use of SelectCC to generate the comparison to set CR bits, for
5008         // equality comparisons having one literal operand, SelectCC probably
5009         // doesn't need to materialize the whole literal and just use xoris to
5010         // check it first, it leads the following comparison result can't
5011         // exactly represent GT/LT relationship. So to avoid this we specify
5012         // SETGT/SETUGT here instead of SETEQ.
5013         SDValue GenCC =
5014             SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl);
5015         CurDAG->SelectNodeTo(
5016             N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB,
5017             N->getValueType(0), GenCC);
5018         NumP9Setb++;
5019         return;
5020       }
5021     }
5022 
5023     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
5024     if (!isPPC64)
5025       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
5026         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
5027           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
5028             if (N1C->isNullValue() && N3C->isNullValue() &&
5029                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
5030                 // FIXME: Implement this optzn for PPC64.
5031                 N->getValueType(0) == MVT::i32) {
5032               SDNode *Tmp =
5033                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
5034                                        N->getOperand(0), getI32Imm(~0U, dl));
5035               CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
5036                                    N->getOperand(0), SDValue(Tmp, 1));
5037               return;
5038             }
5039 
5040     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
5041 
5042     if (N->getValueType(0) == MVT::i1) {
5043       // An i1 select is: (c & t) | (!c & f).
5044       bool Inv;
5045       unsigned Idx = getCRIdxForSetCC(CC, Inv);
5046 
5047       unsigned SRI;
5048       switch (Idx) {
5049       default: llvm_unreachable("Invalid CC index");
5050       case 0: SRI = PPC::sub_lt; break;
5051       case 1: SRI = PPC::sub_gt; break;
5052       case 2: SRI = PPC::sub_eq; break;
5053       case 3: SRI = PPC::sub_un; break;
5054       }
5055 
5056       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
5057 
5058       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
5059                                               CCBit, CCBit), 0);
5060       SDValue C =    Inv ? NotCCBit : CCBit,
5061               NotC = Inv ? CCBit    : NotCCBit;
5062 
5063       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5064                                            C, N->getOperand(2)), 0);
5065       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5066                                               NotC, N->getOperand(3)), 0);
5067 
5068       CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
5069       return;
5070     }
5071 
5072     unsigned BROpc =
5073         getPredicateForSetCC(CC, N->getOperand(0).getValueType(), Subtarget);
5074 
5075     unsigned SelectCCOp;
5076     if (N->getValueType(0) == MVT::i32)
5077       SelectCCOp = PPC::SELECT_CC_I4;
5078     else if (N->getValueType(0) == MVT::i64)
5079       SelectCCOp = PPC::SELECT_CC_I8;
5080     else if (N->getValueType(0) == MVT::f32) {
5081       if (Subtarget->hasP8Vector())
5082         SelectCCOp = PPC::SELECT_CC_VSSRC;
5083       else if (Subtarget->hasSPE())
5084         SelectCCOp = PPC::SELECT_CC_SPE4;
5085       else
5086         SelectCCOp = PPC::SELECT_CC_F4;
5087     } else if (N->getValueType(0) == MVT::f64) {
5088       if (Subtarget->hasVSX())
5089         SelectCCOp = PPC::SELECT_CC_VSFRC;
5090       else if (Subtarget->hasSPE())
5091         SelectCCOp = PPC::SELECT_CC_SPE;
5092       else
5093         SelectCCOp = PPC::SELECT_CC_F8;
5094     } else if (N->getValueType(0) == MVT::f128)
5095       SelectCCOp = PPC::SELECT_CC_F16;
5096     else if (Subtarget->hasSPE())
5097       SelectCCOp = PPC::SELECT_CC_SPE;
5098     else if (Subtarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
5099       SelectCCOp = PPC::SELECT_CC_QFRC;
5100     else if (Subtarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
5101       SelectCCOp = PPC::SELECT_CC_QSRC;
5102     else if (Subtarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
5103       SelectCCOp = PPC::SELECT_CC_QBRC;
5104     else if (N->getValueType(0) == MVT::v2f64 ||
5105              N->getValueType(0) == MVT::v2i64)
5106       SelectCCOp = PPC::SELECT_CC_VSRC;
5107     else
5108       SelectCCOp = PPC::SELECT_CC_VRRC;
5109 
5110     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
5111                         getI32Imm(BROpc, dl) };
5112     CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
5113     return;
5114   }
5115   case ISD::VECTOR_SHUFFLE:
5116     if (Subtarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
5117                                 N->getValueType(0) == MVT::v2i64)) {
5118       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5119 
5120       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
5121               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
5122       unsigned DM[2];
5123 
5124       for (int i = 0; i < 2; ++i)
5125         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
5126           DM[i] = 0;
5127         else
5128           DM[i] = 1;
5129 
5130       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
5131           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5132           isa<LoadSDNode>(Op1.getOperand(0))) {
5133         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
5134         SDValue Base, Offset;
5135 
5136         if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
5137             (LD->getMemoryVT() == MVT::f64 ||
5138              LD->getMemoryVT() == MVT::i64) &&
5139             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
5140           SDValue Chain = LD->getChain();
5141           SDValue Ops[] = { Base, Offset, Chain };
5142           MachineMemOperand *MemOp = LD->getMemOperand();
5143           SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
5144                                               N->getValueType(0), Ops);
5145           CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp});
5146           return;
5147         }
5148       }
5149 
5150       // For little endian, we must swap the input operands and adjust
5151       // the mask elements (reverse and invert them).
5152       if (Subtarget->isLittleEndian()) {
5153         std::swap(Op1, Op2);
5154         unsigned tmp = DM[0];
5155         DM[0] = 1 - DM[1];
5156         DM[1] = 1 - tmp;
5157       }
5158 
5159       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
5160                                               MVT::i32);
5161       SDValue Ops[] = { Op1, Op2, DMV };
5162       CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
5163       return;
5164     }
5165 
5166     break;
5167   case PPCISD::BDNZ:
5168   case PPCISD::BDZ: {
5169     bool IsPPC64 = Subtarget->isPPC64();
5170     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
5171     CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
5172                                 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
5173                                 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
5174                          MVT::Other, Ops);
5175     return;
5176   }
5177   case PPCISD::COND_BRANCH: {
5178     // Op #0 is the Chain.
5179     // Op #1 is the PPC::PRED_* number.
5180     // Op #2 is the CR#
5181     // Op #3 is the Dest MBB
5182     // Op #4 is the Flag.
5183     // Prevent PPC::PRED_* from being selected into LI.
5184     unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
5185     if (EnableBranchHint)
5186       PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(3));
5187 
5188     SDValue Pred = getI32Imm(PCC, dl);
5189     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
5190       N->getOperand(0), N->getOperand(4) };
5191     CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
5192     return;
5193   }
5194   case ISD::BR_CC: {
5195     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
5196     unsigned PCC =
5197         getPredicateForSetCC(CC, N->getOperand(2).getValueType(), Subtarget);
5198 
5199     if (N->getOperand(2).getValueType() == MVT::i1) {
5200       unsigned Opc;
5201       bool Swap;
5202       switch (PCC) {
5203       default: llvm_unreachable("Unexpected Boolean-operand predicate");
5204       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
5205       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
5206       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
5207       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
5208       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
5209       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
5210       }
5211 
5212       // A signed comparison of i1 values produces the opposite result to an
5213       // unsigned one if the condition code includes less-than or greater-than.
5214       // This is because 1 is the most negative signed i1 number and the most
5215       // positive unsigned i1 number. The CR-logical operations used for such
5216       // comparisons are non-commutative so for signed comparisons vs. unsigned
5217       // ones, the input operands just need to be swapped.
5218       if (ISD::isSignedIntSetCC(CC))
5219         Swap = !Swap;
5220 
5221       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
5222                                              N->getOperand(Swap ? 3 : 2),
5223                                              N->getOperand(Swap ? 2 : 3)), 0);
5224       CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
5225                            N->getOperand(0));
5226       return;
5227     }
5228 
5229     if (EnableBranchHint)
5230       PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(4));
5231 
5232     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
5233     SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
5234                         N->getOperand(4), N->getOperand(0) };
5235     CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
5236     return;
5237   }
5238   case ISD::BRIND: {
5239     // FIXME: Should custom lower this.
5240     SDValue Chain = N->getOperand(0);
5241     SDValue Target = N->getOperand(1);
5242     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
5243     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
5244     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
5245                                            Chain), 0);
5246     CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
5247     return;
5248   }
5249   case PPCISD::TOC_ENTRY: {
5250     const bool isPPC64 = Subtarget->isPPC64();
5251     const bool isELFABI = Subtarget->isSVR4ABI();
5252     const bool isAIXABI = Subtarget->isAIXABI();
5253 
5254     // PowerPC only support small, medium and large code model.
5255     const CodeModel::Model CModel = TM.getCodeModel();
5256     assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) &&
5257            "PowerPC doesn't support tiny or kernel code models.");
5258 
5259     if (isAIXABI && CModel == CodeModel::Medium)
5260       report_fatal_error("Medium code model is not supported on AIX.");
5261 
5262     // For 64-bit small code model, we allow SelectCodeCommon to handle this,
5263     // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
5264     if (isPPC64 && CModel == CodeModel::Small)
5265       break;
5266 
5267     // Handle 32-bit small code model.
5268     if (!isPPC64) {
5269       // Transforms the ISD::TOC_ENTRY node to a PPCISD::LWZtoc.
5270       auto replaceWithLWZtoc = [this, &dl](SDNode *TocEntry) {
5271         SDValue GA = TocEntry->getOperand(0);
5272         SDValue TocBase = TocEntry->getOperand(1);
5273         SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
5274                                             TocBase);
5275         transferMemOperands(TocEntry, MN);
5276         ReplaceNode(TocEntry, MN);
5277       };
5278 
5279       if (isELFABI) {
5280         assert(TM.isPositionIndependent() &&
5281                "32-bit ELF can only have TOC entries in position independent"
5282                " code.");
5283         // 32-bit ELF always uses a small code model toc access.
5284         replaceWithLWZtoc(N);
5285         return;
5286       }
5287 
5288       if (isAIXABI && CModel == CodeModel::Small) {
5289         replaceWithLWZtoc(N);
5290         return;
5291       }
5292     }
5293 
5294     assert(CModel != CodeModel::Small && "All small code models handled.");
5295 
5296     assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit"
5297            " ELF/AIX or 32-bit AIX in the following.");
5298 
5299     // Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode
5300     // or 64-bit medium (ELF-only) or large (ELF and AIX) code model code. We
5301     // generate two instructions as described below. The first source operand
5302     // is a symbol reference. If it must be toc-referenced according to
5303     // Subtarget, we generate:
5304     // [32-bit AIX]
5305     //   LWZtocL(@sym, ADDIStocHA(%r2, @sym))
5306     // [64-bit ELF/AIX]
5307     //   LDtocL(@sym, ADDIStocHA8(%x2, @sym))
5308     // Otherwise we generate:
5309     //   ADDItocL(ADDIStocHA8(%x2, @sym), @sym)
5310     SDValue GA = N->getOperand(0);
5311     SDValue TOCbase = N->getOperand(1);
5312 
5313     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5314     SDNode *Tmp = CurDAG->getMachineNode(
5315         isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, TOCbase, GA);
5316 
5317     if (PPCLowering->isAccessedAsGotIndirect(GA)) {
5318       // If it is accessed as got-indirect, we need an extra LWZ/LD to load
5319       // the address.
5320       SDNode *MN = CurDAG->getMachineNode(
5321           isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, GA, SDValue(Tmp, 0));
5322 
5323       transferMemOperands(N, MN);
5324       ReplaceNode(N, MN);
5325       return;
5326     }
5327 
5328     // Build the address relative to the TOC-pointer.
5329     ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
5330                                           SDValue(Tmp, 0), GA));
5331     return;
5332   }
5333   case PPCISD::PPC32_PICGOT:
5334     // Generate a PIC-safe GOT reference.
5335     assert(Subtarget->is32BitELFABI() &&
5336            "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
5337     CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
5338                          PPCLowering->getPointerTy(CurDAG->getDataLayout()),
5339                          MVT::i32);
5340     return;
5341 
5342   case PPCISD::VADD_SPLAT: {
5343     // This expands into one of three sequences, depending on whether
5344     // the first operand is odd or even, positive or negative.
5345     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
5346            isa<ConstantSDNode>(N->getOperand(1)) &&
5347            "Invalid operand on VADD_SPLAT!");
5348 
5349     int Elt     = N->getConstantOperandVal(0);
5350     int EltSize = N->getConstantOperandVal(1);
5351     unsigned Opc1, Opc2, Opc3;
5352     EVT VT;
5353 
5354     if (EltSize == 1) {
5355       Opc1 = PPC::VSPLTISB;
5356       Opc2 = PPC::VADDUBM;
5357       Opc3 = PPC::VSUBUBM;
5358       VT = MVT::v16i8;
5359     } else if (EltSize == 2) {
5360       Opc1 = PPC::VSPLTISH;
5361       Opc2 = PPC::VADDUHM;
5362       Opc3 = PPC::VSUBUHM;
5363       VT = MVT::v8i16;
5364     } else {
5365       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
5366       Opc1 = PPC::VSPLTISW;
5367       Opc2 = PPC::VADDUWM;
5368       Opc3 = PPC::VSUBUWM;
5369       VT = MVT::v4i32;
5370     }
5371 
5372     if ((Elt & 1) == 0) {
5373       // Elt is even, in the range [-32,-18] + [16,30].
5374       //
5375       // Convert: VADD_SPLAT elt, size
5376       // Into:    tmp = VSPLTIS[BHW] elt
5377       //          VADDU[BHW]M tmp, tmp
5378       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
5379       SDValue EltVal = getI32Imm(Elt >> 1, dl);
5380       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5381       SDValue TmpVal = SDValue(Tmp, 0);
5382       ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
5383       return;
5384     } else if (Elt > 0) {
5385       // Elt is odd and positive, in the range [17,31].
5386       //
5387       // Convert: VADD_SPLAT elt, size
5388       // Into:    tmp1 = VSPLTIS[BHW] elt-16
5389       //          tmp2 = VSPLTIS[BHW] -16
5390       //          VSUBU[BHW]M tmp1, tmp2
5391       SDValue EltVal = getI32Imm(Elt - 16, dl);
5392       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5393       EltVal = getI32Imm(-16, dl);
5394       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5395       ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
5396                                             SDValue(Tmp2, 0)));
5397       return;
5398     } else {
5399       // Elt is odd and negative, in the range [-31,-17].
5400       //
5401       // Convert: VADD_SPLAT elt, size
5402       // Into:    tmp1 = VSPLTIS[BHW] elt+16
5403       //          tmp2 = VSPLTIS[BHW] -16
5404       //          VADDU[BHW]M tmp1, tmp2
5405       SDValue EltVal = getI32Imm(Elt + 16, dl);
5406       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5407       EltVal = getI32Imm(-16, dl);
5408       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5409       ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
5410                                             SDValue(Tmp2, 0)));
5411       return;
5412     }
5413   }
5414   }
5415 
5416   SelectCode(N);
5417 }
5418 
5419 // If the target supports the cmpb instruction, do the idiom recognition here.
5420 // We don't do this as a DAG combine because we don't want to do it as nodes
5421 // are being combined (because we might miss part of the eventual idiom). We
5422 // don't want to do it during instruction selection because we want to reuse
5423 // the logic for lowering the masking operations already part of the
5424 // instruction selector.
5425 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
5426   SDLoc dl(N);
5427 
5428   assert(N->getOpcode() == ISD::OR &&
5429          "Only OR nodes are supported for CMPB");
5430 
5431   SDValue Res;
5432   if (!Subtarget->hasCMPB())
5433     return Res;
5434 
5435   if (N->getValueType(0) != MVT::i32 &&
5436       N->getValueType(0) != MVT::i64)
5437     return Res;
5438 
5439   EVT VT = N->getValueType(0);
5440 
5441   SDValue RHS, LHS;
5442   bool BytesFound[8] = {false, false, false, false, false, false, false, false};
5443   uint64_t Mask = 0, Alt = 0;
5444 
5445   auto IsByteSelectCC = [this](SDValue O, unsigned &b,
5446                                uint64_t &Mask, uint64_t &Alt,
5447                                SDValue &LHS, SDValue &RHS) {
5448     if (O.getOpcode() != ISD::SELECT_CC)
5449       return false;
5450     ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
5451 
5452     if (!isa<ConstantSDNode>(O.getOperand(2)) ||
5453         !isa<ConstantSDNode>(O.getOperand(3)))
5454       return false;
5455 
5456     uint64_t PM = O.getConstantOperandVal(2);
5457     uint64_t PAlt = O.getConstantOperandVal(3);
5458     for (b = 0; b < 8; ++b) {
5459       uint64_t Mask = UINT64_C(0xFF) << (8*b);
5460       if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
5461         break;
5462     }
5463 
5464     if (b == 8)
5465       return false;
5466     Mask |= PM;
5467     Alt  |= PAlt;
5468 
5469     if (!isa<ConstantSDNode>(O.getOperand(1)) ||
5470         O.getConstantOperandVal(1) != 0) {
5471       SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
5472       if (Op0.getOpcode() == ISD::TRUNCATE)
5473         Op0 = Op0.getOperand(0);
5474       if (Op1.getOpcode() == ISD::TRUNCATE)
5475         Op1 = Op1.getOperand(0);
5476 
5477       if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
5478           Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
5479           isa<ConstantSDNode>(Op0.getOperand(1))) {
5480 
5481         unsigned Bits = Op0.getValueSizeInBits();
5482         if (b != Bits/8-1)
5483           return false;
5484         if (Op0.getConstantOperandVal(1) != Bits-8)
5485           return false;
5486 
5487         LHS = Op0.getOperand(0);
5488         RHS = Op1.getOperand(0);
5489         return true;
5490       }
5491 
5492       // When we have small integers (i16 to be specific), the form present
5493       // post-legalization uses SETULT in the SELECT_CC for the
5494       // higher-order byte, depending on the fact that the
5495       // even-higher-order bytes are known to all be zero, for example:
5496       //   select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
5497       // (so when the second byte is the same, because all higher-order
5498       // bits from bytes 3 and 4 are known to be zero, the result of the
5499       // xor can be at most 255)
5500       if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
5501           isa<ConstantSDNode>(O.getOperand(1))) {
5502 
5503         uint64_t ULim = O.getConstantOperandVal(1);
5504         if (ULim != (UINT64_C(1) << b*8))
5505           return false;
5506 
5507         // Now we need to make sure that the upper bytes are known to be
5508         // zero.
5509         unsigned Bits = Op0.getValueSizeInBits();
5510         if (!CurDAG->MaskedValueIsZero(
5511                 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
5512           return false;
5513 
5514         LHS = Op0.getOperand(0);
5515         RHS = Op0.getOperand(1);
5516         return true;
5517       }
5518 
5519       return false;
5520     }
5521 
5522     if (CC != ISD::SETEQ)
5523       return false;
5524 
5525     SDValue Op = O.getOperand(0);
5526     if (Op.getOpcode() == ISD::AND) {
5527       if (!isa<ConstantSDNode>(Op.getOperand(1)))
5528         return false;
5529       if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
5530         return false;
5531 
5532       SDValue XOR = Op.getOperand(0);
5533       if (XOR.getOpcode() == ISD::TRUNCATE)
5534         XOR = XOR.getOperand(0);
5535       if (XOR.getOpcode() != ISD::XOR)
5536         return false;
5537 
5538       LHS = XOR.getOperand(0);
5539       RHS = XOR.getOperand(1);
5540       return true;
5541     } else if (Op.getOpcode() == ISD::SRL) {
5542       if (!isa<ConstantSDNode>(Op.getOperand(1)))
5543         return false;
5544       unsigned Bits = Op.getValueSizeInBits();
5545       if (b != Bits/8-1)
5546         return false;
5547       if (Op.getConstantOperandVal(1) != Bits-8)
5548         return false;
5549 
5550       SDValue XOR = Op.getOperand(0);
5551       if (XOR.getOpcode() == ISD::TRUNCATE)
5552         XOR = XOR.getOperand(0);
5553       if (XOR.getOpcode() != ISD::XOR)
5554         return false;
5555 
5556       LHS = XOR.getOperand(0);
5557       RHS = XOR.getOperand(1);
5558       return true;
5559     }
5560 
5561     return false;
5562   };
5563 
5564   SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
5565   while (!Queue.empty()) {
5566     SDValue V = Queue.pop_back_val();
5567 
5568     for (const SDValue &O : V.getNode()->ops()) {
5569       unsigned b = 0;
5570       uint64_t M = 0, A = 0;
5571       SDValue OLHS, ORHS;
5572       if (O.getOpcode() == ISD::OR) {
5573         Queue.push_back(O);
5574       } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
5575         if (!LHS) {
5576           LHS = OLHS;
5577           RHS = ORHS;
5578           BytesFound[b] = true;
5579           Mask |= M;
5580           Alt  |= A;
5581         } else if ((LHS == ORHS && RHS == OLHS) ||
5582                    (RHS == ORHS && LHS == OLHS)) {
5583           BytesFound[b] = true;
5584           Mask |= M;
5585           Alt  |= A;
5586         } else {
5587           return Res;
5588         }
5589       } else {
5590         return Res;
5591       }
5592     }
5593   }
5594 
5595   unsigned LastB = 0, BCnt = 0;
5596   for (unsigned i = 0; i < 8; ++i)
5597     if (BytesFound[LastB]) {
5598       ++BCnt;
5599       LastB = i;
5600     }
5601 
5602   if (!LastB || BCnt < 2)
5603     return Res;
5604 
5605   // Because we'll be zero-extending the output anyway if don't have a specific
5606   // value for each input byte (via the Mask), we can 'anyext' the inputs.
5607   if (LHS.getValueType() != VT) {
5608     LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
5609     RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
5610   }
5611 
5612   Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
5613 
5614   bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
5615   if (NonTrivialMask && !Alt) {
5616     // Res = Mask & CMPB
5617     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
5618                           CurDAG->getConstant(Mask, dl, VT));
5619   } else if (Alt) {
5620     // Res = (CMPB & Mask) | (~CMPB & Alt)
5621     // Which, as suggested here:
5622     //   https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
5623     // can be written as:
5624     // Res = Alt ^ ((Alt ^ Mask) & CMPB)
5625     // useful because the (Alt ^ Mask) can be pre-computed.
5626     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
5627                           CurDAG->getConstant(Mask ^ Alt, dl, VT));
5628     Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
5629                           CurDAG->getConstant(Alt, dl, VT));
5630   }
5631 
5632   return Res;
5633 }
5634 
5635 // When CR bit registers are enabled, an extension of an i1 variable to a i32
5636 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
5637 // involves constant materialization of a 0 or a 1 or both. If the result of
5638 // the extension is then operated upon by some operator that can be constant
5639 // folded with a constant 0 or 1, and that constant can be materialized using
5640 // only one instruction (like a zero or one), then we should fold in those
5641 // operations with the select.
5642 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
5643   if (!Subtarget->useCRBits())
5644     return;
5645 
5646   if (N->getOpcode() != ISD::ZERO_EXTEND &&
5647       N->getOpcode() != ISD::SIGN_EXTEND &&
5648       N->getOpcode() != ISD::ANY_EXTEND)
5649     return;
5650 
5651   if (N->getOperand(0).getValueType() != MVT::i1)
5652     return;
5653 
5654   if (!N->hasOneUse())
5655     return;
5656 
5657   SDLoc dl(N);
5658   EVT VT = N->getValueType(0);
5659   SDValue Cond = N->getOperand(0);
5660   SDValue ConstTrue =
5661     CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
5662   SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
5663 
5664   do {
5665     SDNode *User = *N->use_begin();
5666     if (User->getNumOperands() != 2)
5667       break;
5668 
5669     auto TryFold = [this, N, User, dl](SDValue Val) {
5670       SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
5671       SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
5672       SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
5673 
5674       return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
5675                                             User->getValueType(0), {O0, O1});
5676     };
5677 
5678     // FIXME: When the semantics of the interaction between select and undef
5679     // are clearly defined, it may turn out to be unnecessary to break here.
5680     SDValue TrueRes = TryFold(ConstTrue);
5681     if (!TrueRes || TrueRes.isUndef())
5682       break;
5683     SDValue FalseRes = TryFold(ConstFalse);
5684     if (!FalseRes || FalseRes.isUndef())
5685       break;
5686 
5687     // For us to materialize these using one instruction, we must be able to
5688     // represent them as signed 16-bit integers.
5689     uint64_t True  = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
5690              False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
5691     if (!isInt<16>(True) || !isInt<16>(False))
5692       break;
5693 
5694     // We can replace User with a new SELECT node, and try again to see if we
5695     // can fold the select with its user.
5696     Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
5697     N = User;
5698     ConstTrue = TrueRes;
5699     ConstFalse = FalseRes;
5700   } while (N->hasOneUse());
5701 }
5702 
5703 void PPCDAGToDAGISel::PreprocessISelDAG() {
5704   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
5705 
5706   bool MadeChange = false;
5707   while (Position != CurDAG->allnodes_begin()) {
5708     SDNode *N = &*--Position;
5709     if (N->use_empty())
5710       continue;
5711 
5712     SDValue Res;
5713     switch (N->getOpcode()) {
5714     default: break;
5715     case ISD::OR:
5716       Res = combineToCMPB(N);
5717       break;
5718     }
5719 
5720     if (!Res)
5721       foldBoolExts(Res, N);
5722 
5723     if (Res) {
5724       LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld:    ");
5725       LLVM_DEBUG(N->dump(CurDAG));
5726       LLVM_DEBUG(dbgs() << "\nNew: ");
5727       LLVM_DEBUG(Res.getNode()->dump(CurDAG));
5728       LLVM_DEBUG(dbgs() << "\n");
5729 
5730       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
5731       MadeChange = true;
5732     }
5733   }
5734 
5735   if (MadeChange)
5736     CurDAG->RemoveDeadNodes();
5737 }
5738 
5739 /// PostprocessISelDAG - Perform some late peephole optimizations
5740 /// on the DAG representation.
5741 void PPCDAGToDAGISel::PostprocessISelDAG() {
5742   // Skip peepholes at -O0.
5743   if (TM.getOptLevel() == CodeGenOpt::None)
5744     return;
5745 
5746   PeepholePPC64();
5747   PeepholeCROps();
5748   PeepholePPC64ZExt();
5749 }
5750 
5751 // Check if all users of this node will become isel where the second operand
5752 // is the constant zero. If this is so, and if we can negate the condition,
5753 // then we can flip the true and false operands. This will allow the zero to
5754 // be folded with the isel so that we don't need to materialize a register
5755 // containing zero.
5756 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
5757   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5758        UI != UE; ++UI) {
5759     SDNode *User = *UI;
5760     if (!User->isMachineOpcode())
5761       return false;
5762     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
5763         User->getMachineOpcode() != PPC::SELECT_I8)
5764       return false;
5765 
5766     SDNode *Op2 = User->getOperand(2).getNode();
5767     if (!Op2->isMachineOpcode())
5768       return false;
5769 
5770     if (Op2->getMachineOpcode() != PPC::LI &&
5771         Op2->getMachineOpcode() != PPC::LI8)
5772       return false;
5773 
5774     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
5775     if (!C)
5776       return false;
5777 
5778     if (!C->isNullValue())
5779       return false;
5780   }
5781 
5782   return true;
5783 }
5784 
5785 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
5786   SmallVector<SDNode *, 4> ToReplace;
5787   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5788        UI != UE; ++UI) {
5789     SDNode *User = *UI;
5790     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
5791             User->getMachineOpcode() == PPC::SELECT_I8) &&
5792            "Must have all select users");
5793     ToReplace.push_back(User);
5794   }
5795 
5796   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
5797        UE = ToReplace.end(); UI != UE; ++UI) {
5798     SDNode *User = *UI;
5799     SDNode *ResNode =
5800       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
5801                              User->getValueType(0), User->getOperand(0),
5802                              User->getOperand(2),
5803                              User->getOperand(1));
5804 
5805     LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
5806     LLVM_DEBUG(User->dump(CurDAG));
5807     LLVM_DEBUG(dbgs() << "\nNew: ");
5808     LLVM_DEBUG(ResNode->dump(CurDAG));
5809     LLVM_DEBUG(dbgs() << "\n");
5810 
5811     ReplaceUses(User, ResNode);
5812   }
5813 }
5814 
5815 void PPCDAGToDAGISel::PeepholeCROps() {
5816   bool IsModified;
5817   do {
5818     IsModified = false;
5819     for (SDNode &Node : CurDAG->allnodes()) {
5820       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
5821       if (!MachineNode || MachineNode->use_empty())
5822         continue;
5823       SDNode *ResNode = MachineNode;
5824 
5825       bool Op1Set   = false, Op1Unset = false,
5826            Op1Not   = false,
5827            Op2Set   = false, Op2Unset = false,
5828            Op2Not   = false;
5829 
5830       unsigned Opcode = MachineNode->getMachineOpcode();
5831       switch (Opcode) {
5832       default: break;
5833       case PPC::CRAND:
5834       case PPC::CRNAND:
5835       case PPC::CROR:
5836       case PPC::CRXOR:
5837       case PPC::CRNOR:
5838       case PPC::CREQV:
5839       case PPC::CRANDC:
5840       case PPC::CRORC: {
5841         SDValue Op = MachineNode->getOperand(1);
5842         if (Op.isMachineOpcode()) {
5843           if (Op.getMachineOpcode() == PPC::CRSET)
5844             Op2Set = true;
5845           else if (Op.getMachineOpcode() == PPC::CRUNSET)
5846             Op2Unset = true;
5847           else if (Op.getMachineOpcode() == PPC::CRNOR &&
5848                    Op.getOperand(0) == Op.getOperand(1))
5849             Op2Not = true;
5850         }
5851         LLVM_FALLTHROUGH;
5852       }
5853       case PPC::BC:
5854       case PPC::BCn:
5855       case PPC::SELECT_I4:
5856       case PPC::SELECT_I8:
5857       case PPC::SELECT_F4:
5858       case PPC::SELECT_F8:
5859       case PPC::SELECT_QFRC:
5860       case PPC::SELECT_QSRC:
5861       case PPC::SELECT_QBRC:
5862       case PPC::SELECT_SPE:
5863       case PPC::SELECT_SPE4:
5864       case PPC::SELECT_VRRC:
5865       case PPC::SELECT_VSFRC:
5866       case PPC::SELECT_VSSRC:
5867       case PPC::SELECT_VSRC: {
5868         SDValue Op = MachineNode->getOperand(0);
5869         if (Op.isMachineOpcode()) {
5870           if (Op.getMachineOpcode() == PPC::CRSET)
5871             Op1Set = true;
5872           else if (Op.getMachineOpcode() == PPC::CRUNSET)
5873             Op1Unset = true;
5874           else if (Op.getMachineOpcode() == PPC::CRNOR &&
5875                    Op.getOperand(0) == Op.getOperand(1))
5876             Op1Not = true;
5877         }
5878         }
5879         break;
5880       }
5881 
5882       bool SelectSwap = false;
5883       switch (Opcode) {
5884       default: break;
5885       case PPC::CRAND:
5886         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5887           // x & x = x
5888           ResNode = MachineNode->getOperand(0).getNode();
5889         else if (Op1Set)
5890           // 1 & y = y
5891           ResNode = MachineNode->getOperand(1).getNode();
5892         else if (Op2Set)
5893           // x & 1 = x
5894           ResNode = MachineNode->getOperand(0).getNode();
5895         else if (Op1Unset || Op2Unset)
5896           // x & 0 = 0 & y = 0
5897           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5898                                            MVT::i1);
5899         else if (Op1Not)
5900           // ~x & y = andc(y, x)
5901           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5902                                            MVT::i1, MachineNode->getOperand(1),
5903                                            MachineNode->getOperand(0).
5904                                              getOperand(0));
5905         else if (Op2Not)
5906           // x & ~y = andc(x, y)
5907           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5908                                            MVT::i1, MachineNode->getOperand(0),
5909                                            MachineNode->getOperand(1).
5910                                              getOperand(0));
5911         else if (AllUsersSelectZero(MachineNode)) {
5912           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
5913                                            MVT::i1, MachineNode->getOperand(0),
5914                                            MachineNode->getOperand(1));
5915           SelectSwap = true;
5916         }
5917         break;
5918       case PPC::CRNAND:
5919         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5920           // nand(x, x) -> nor(x, x)
5921           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5922                                            MVT::i1, MachineNode->getOperand(0),
5923                                            MachineNode->getOperand(0));
5924         else if (Op1Set)
5925           // nand(1, y) -> nor(y, y)
5926           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5927                                            MVT::i1, MachineNode->getOperand(1),
5928                                            MachineNode->getOperand(1));
5929         else if (Op2Set)
5930           // nand(x, 1) -> nor(x, x)
5931           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5932                                            MVT::i1, MachineNode->getOperand(0),
5933                                            MachineNode->getOperand(0));
5934         else if (Op1Unset || Op2Unset)
5935           // nand(x, 0) = nand(0, y) = 1
5936           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5937                                            MVT::i1);
5938         else if (Op1Not)
5939           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
5940           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5941                                            MVT::i1, MachineNode->getOperand(0).
5942                                                       getOperand(0),
5943                                            MachineNode->getOperand(1));
5944         else if (Op2Not)
5945           // nand(x, ~y) = ~x | y = orc(y, x)
5946           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5947                                            MVT::i1, MachineNode->getOperand(1).
5948                                                       getOperand(0),
5949                                            MachineNode->getOperand(0));
5950         else if (AllUsersSelectZero(MachineNode)) {
5951           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
5952                                            MVT::i1, MachineNode->getOperand(0),
5953                                            MachineNode->getOperand(1));
5954           SelectSwap = true;
5955         }
5956         break;
5957       case PPC::CROR:
5958         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5959           // x | x = x
5960           ResNode = MachineNode->getOperand(0).getNode();
5961         else if (Op1Set || Op2Set)
5962           // x | 1 = 1 | y = 1
5963           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5964                                            MVT::i1);
5965         else if (Op1Unset)
5966           // 0 | y = y
5967           ResNode = MachineNode->getOperand(1).getNode();
5968         else if (Op2Unset)
5969           // x | 0 = x
5970           ResNode = MachineNode->getOperand(0).getNode();
5971         else if (Op1Not)
5972           // ~x | y = orc(y, x)
5973           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5974                                            MVT::i1, MachineNode->getOperand(1),
5975                                            MachineNode->getOperand(0).
5976                                              getOperand(0));
5977         else if (Op2Not)
5978           // x | ~y = orc(x, y)
5979           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5980                                            MVT::i1, MachineNode->getOperand(0),
5981                                            MachineNode->getOperand(1).
5982                                              getOperand(0));
5983         else if (AllUsersSelectZero(MachineNode)) {
5984           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5985                                            MVT::i1, MachineNode->getOperand(0),
5986                                            MachineNode->getOperand(1));
5987           SelectSwap = true;
5988         }
5989         break;
5990       case PPC::CRXOR:
5991         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5992           // xor(x, x) = 0
5993           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5994                                            MVT::i1);
5995         else if (Op1Set)
5996           // xor(1, y) -> nor(y, y)
5997           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5998                                            MVT::i1, MachineNode->getOperand(1),
5999                                            MachineNode->getOperand(1));
6000         else if (Op2Set)
6001           // xor(x, 1) -> nor(x, x)
6002           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6003                                            MVT::i1, MachineNode->getOperand(0),
6004                                            MachineNode->getOperand(0));
6005         else if (Op1Unset)
6006           // xor(0, y) = y
6007           ResNode = MachineNode->getOperand(1).getNode();
6008         else if (Op2Unset)
6009           // xor(x, 0) = x
6010           ResNode = MachineNode->getOperand(0).getNode();
6011         else if (Op1Not)
6012           // xor(~x, y) = eqv(x, y)
6013           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6014                                            MVT::i1, MachineNode->getOperand(0).
6015                                                       getOperand(0),
6016                                            MachineNode->getOperand(1));
6017         else if (Op2Not)
6018           // xor(x, ~y) = eqv(x, y)
6019           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6020                                            MVT::i1, MachineNode->getOperand(0),
6021                                            MachineNode->getOperand(1).
6022                                              getOperand(0));
6023         else if (AllUsersSelectZero(MachineNode)) {
6024           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6025                                            MVT::i1, MachineNode->getOperand(0),
6026                                            MachineNode->getOperand(1));
6027           SelectSwap = true;
6028         }
6029         break;
6030       case PPC::CRNOR:
6031         if (Op1Set || Op2Set)
6032           // nor(1, y) -> 0
6033           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6034                                            MVT::i1);
6035         else if (Op1Unset)
6036           // nor(0, y) = ~y -> nor(y, y)
6037           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6038                                            MVT::i1, MachineNode->getOperand(1),
6039                                            MachineNode->getOperand(1));
6040         else if (Op2Unset)
6041           // nor(x, 0) = ~x
6042           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6043                                            MVT::i1, MachineNode->getOperand(0),
6044                                            MachineNode->getOperand(0));
6045         else if (Op1Not)
6046           // nor(~x, y) = andc(x, y)
6047           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6048                                            MVT::i1, MachineNode->getOperand(0).
6049                                                       getOperand(0),
6050                                            MachineNode->getOperand(1));
6051         else if (Op2Not)
6052           // nor(x, ~y) = andc(y, x)
6053           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6054                                            MVT::i1, MachineNode->getOperand(1).
6055                                                       getOperand(0),
6056                                            MachineNode->getOperand(0));
6057         else if (AllUsersSelectZero(MachineNode)) {
6058           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
6059                                            MVT::i1, MachineNode->getOperand(0),
6060                                            MachineNode->getOperand(1));
6061           SelectSwap = true;
6062         }
6063         break;
6064       case PPC::CREQV:
6065         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6066           // eqv(x, x) = 1
6067           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6068                                            MVT::i1);
6069         else if (Op1Set)
6070           // eqv(1, y) = y
6071           ResNode = MachineNode->getOperand(1).getNode();
6072         else if (Op2Set)
6073           // eqv(x, 1) = x
6074           ResNode = MachineNode->getOperand(0).getNode();
6075         else if (Op1Unset)
6076           // eqv(0, y) = ~y -> nor(y, y)
6077           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6078                                            MVT::i1, MachineNode->getOperand(1),
6079                                            MachineNode->getOperand(1));
6080         else if (Op2Unset)
6081           // eqv(x, 0) = ~x
6082           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6083                                            MVT::i1, MachineNode->getOperand(0),
6084                                            MachineNode->getOperand(0));
6085         else if (Op1Not)
6086           // eqv(~x, y) = xor(x, y)
6087           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6088                                            MVT::i1, MachineNode->getOperand(0).
6089                                                       getOperand(0),
6090                                            MachineNode->getOperand(1));
6091         else if (Op2Not)
6092           // eqv(x, ~y) = xor(x, y)
6093           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6094                                            MVT::i1, MachineNode->getOperand(0),
6095                                            MachineNode->getOperand(1).
6096                                              getOperand(0));
6097         else if (AllUsersSelectZero(MachineNode)) {
6098           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6099                                            MVT::i1, MachineNode->getOperand(0),
6100                                            MachineNode->getOperand(1));
6101           SelectSwap = true;
6102         }
6103         break;
6104       case PPC::CRANDC:
6105         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6106           // andc(x, x) = 0
6107           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6108                                            MVT::i1);
6109         else if (Op1Set)
6110           // andc(1, y) = ~y
6111           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6112                                            MVT::i1, MachineNode->getOperand(1),
6113                                            MachineNode->getOperand(1));
6114         else if (Op1Unset || Op2Set)
6115           // andc(0, y) = andc(x, 1) = 0
6116           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6117                                            MVT::i1);
6118         else if (Op2Unset)
6119           // andc(x, 0) = x
6120           ResNode = MachineNode->getOperand(0).getNode();
6121         else if (Op1Not)
6122           // andc(~x, y) = ~(x | y) = nor(x, y)
6123           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6124                                            MVT::i1, MachineNode->getOperand(0).
6125                                                       getOperand(0),
6126                                            MachineNode->getOperand(1));
6127         else if (Op2Not)
6128           // andc(x, ~y) = x & y
6129           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
6130                                            MVT::i1, MachineNode->getOperand(0),
6131                                            MachineNode->getOperand(1).
6132                                              getOperand(0));
6133         else if (AllUsersSelectZero(MachineNode)) {
6134           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6135                                            MVT::i1, MachineNode->getOperand(1),
6136                                            MachineNode->getOperand(0));
6137           SelectSwap = true;
6138         }
6139         break;
6140       case PPC::CRORC:
6141         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6142           // orc(x, x) = 1
6143           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6144                                            MVT::i1);
6145         else if (Op1Set || Op2Unset)
6146           // orc(1, y) = orc(x, 0) = 1
6147           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6148                                            MVT::i1);
6149         else if (Op2Set)
6150           // orc(x, 1) = x
6151           ResNode = MachineNode->getOperand(0).getNode();
6152         else if (Op1Unset)
6153           // orc(0, y) = ~y
6154           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6155                                            MVT::i1, MachineNode->getOperand(1),
6156                                            MachineNode->getOperand(1));
6157         else if (Op1Not)
6158           // orc(~x, y) = ~(x & y) = nand(x, y)
6159           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
6160                                            MVT::i1, MachineNode->getOperand(0).
6161                                                       getOperand(0),
6162                                            MachineNode->getOperand(1));
6163         else if (Op2Not)
6164           // orc(x, ~y) = x | y
6165           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
6166                                            MVT::i1, MachineNode->getOperand(0),
6167                                            MachineNode->getOperand(1).
6168                                              getOperand(0));
6169         else if (AllUsersSelectZero(MachineNode)) {
6170           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6171                                            MVT::i1, MachineNode->getOperand(1),
6172                                            MachineNode->getOperand(0));
6173           SelectSwap = true;
6174         }
6175         break;
6176       case PPC::SELECT_I4:
6177       case PPC::SELECT_I8:
6178       case PPC::SELECT_F4:
6179       case PPC::SELECT_F8:
6180       case PPC::SELECT_QFRC:
6181       case PPC::SELECT_QSRC:
6182       case PPC::SELECT_QBRC:
6183       case PPC::SELECT_SPE:
6184       case PPC::SELECT_SPE4:
6185       case PPC::SELECT_VRRC:
6186       case PPC::SELECT_VSFRC:
6187       case PPC::SELECT_VSSRC:
6188       case PPC::SELECT_VSRC:
6189         if (Op1Set)
6190           ResNode = MachineNode->getOperand(1).getNode();
6191         else if (Op1Unset)
6192           ResNode = MachineNode->getOperand(2).getNode();
6193         else if (Op1Not)
6194           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
6195                                            SDLoc(MachineNode),
6196                                            MachineNode->getValueType(0),
6197                                            MachineNode->getOperand(0).
6198                                              getOperand(0),
6199                                            MachineNode->getOperand(2),
6200                                            MachineNode->getOperand(1));
6201         break;
6202       case PPC::BC:
6203       case PPC::BCn:
6204         if (Op1Not)
6205           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
6206                                                                PPC::BC,
6207                                            SDLoc(MachineNode),
6208                                            MVT::Other,
6209                                            MachineNode->getOperand(0).
6210                                              getOperand(0),
6211                                            MachineNode->getOperand(1),
6212                                            MachineNode->getOperand(2));
6213         // FIXME: Handle Op1Set, Op1Unset here too.
6214         break;
6215       }
6216 
6217       // If we're inverting this node because it is used only by selects that
6218       // we'd like to swap, then swap the selects before the node replacement.
6219       if (SelectSwap)
6220         SwapAllSelectUsers(MachineNode);
6221 
6222       if (ResNode != MachineNode) {
6223         LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
6224         LLVM_DEBUG(MachineNode->dump(CurDAG));
6225         LLVM_DEBUG(dbgs() << "\nNew: ");
6226         LLVM_DEBUG(ResNode->dump(CurDAG));
6227         LLVM_DEBUG(dbgs() << "\n");
6228 
6229         ReplaceUses(MachineNode, ResNode);
6230         IsModified = true;
6231       }
6232     }
6233     if (IsModified)
6234       CurDAG->RemoveDeadNodes();
6235   } while (IsModified);
6236 }
6237 
6238 // Gather the set of 32-bit operations that are known to have their
6239 // higher-order 32 bits zero, where ToPromote contains all such operations.
6240 static bool PeepholePPC64ZExtGather(SDValue Op32,
6241                                     SmallPtrSetImpl<SDNode *> &ToPromote) {
6242   if (!Op32.isMachineOpcode())
6243     return false;
6244 
6245   // First, check for the "frontier" instructions (those that will clear the
6246   // higher-order 32 bits.
6247 
6248   // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
6249   // around. If it does not, then these instructions will clear the
6250   // higher-order bits.
6251   if ((Op32.getMachineOpcode() == PPC::RLWINM ||
6252        Op32.getMachineOpcode() == PPC::RLWNM) &&
6253       Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
6254     ToPromote.insert(Op32.getNode());
6255     return true;
6256   }
6257 
6258   // SLW and SRW always clear the higher-order bits.
6259   if (Op32.getMachineOpcode() == PPC::SLW ||
6260       Op32.getMachineOpcode() == PPC::SRW) {
6261     ToPromote.insert(Op32.getNode());
6262     return true;
6263   }
6264 
6265   // For LI and LIS, we need the immediate to be positive (so that it is not
6266   // sign extended).
6267   if (Op32.getMachineOpcode() == PPC::LI ||
6268       Op32.getMachineOpcode() == PPC::LIS) {
6269     if (!isUInt<15>(Op32.getConstantOperandVal(0)))
6270       return false;
6271 
6272     ToPromote.insert(Op32.getNode());
6273     return true;
6274   }
6275 
6276   // LHBRX and LWBRX always clear the higher-order bits.
6277   if (Op32.getMachineOpcode() == PPC::LHBRX ||
6278       Op32.getMachineOpcode() == PPC::LWBRX) {
6279     ToPromote.insert(Op32.getNode());
6280     return true;
6281   }
6282 
6283   // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
6284   if (Op32.getMachineOpcode() == PPC::CNTLZW ||
6285       Op32.getMachineOpcode() == PPC::CNTTZW) {
6286     ToPromote.insert(Op32.getNode());
6287     return true;
6288   }
6289 
6290   // Next, check for those instructions we can look through.
6291 
6292   // Assuming the mask does not wrap around, then the higher-order bits are
6293   // taken directly from the first operand.
6294   if (Op32.getMachineOpcode() == PPC::RLWIMI &&
6295       Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
6296     SmallPtrSet<SDNode *, 16> ToPromote1;
6297     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
6298       return false;
6299 
6300     ToPromote.insert(Op32.getNode());
6301     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6302     return true;
6303   }
6304 
6305   // For OR, the higher-order bits are zero if that is true for both operands.
6306   // For SELECT_I4, the same is true (but the relevant operand numbers are
6307   // shifted by 1).
6308   if (Op32.getMachineOpcode() == PPC::OR ||
6309       Op32.getMachineOpcode() == PPC::SELECT_I4) {
6310     unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
6311     SmallPtrSet<SDNode *, 16> ToPromote1;
6312     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
6313       return false;
6314     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
6315       return false;
6316 
6317     ToPromote.insert(Op32.getNode());
6318     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6319     return true;
6320   }
6321 
6322   // For ORI and ORIS, we need the higher-order bits of the first operand to be
6323   // zero, and also for the constant to be positive (so that it is not sign
6324   // extended).
6325   if (Op32.getMachineOpcode() == PPC::ORI ||
6326       Op32.getMachineOpcode() == PPC::ORIS) {
6327     SmallPtrSet<SDNode *, 16> ToPromote1;
6328     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
6329       return false;
6330     if (!isUInt<15>(Op32.getConstantOperandVal(1)))
6331       return false;
6332 
6333     ToPromote.insert(Op32.getNode());
6334     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6335     return true;
6336   }
6337 
6338   // The higher-order bits of AND are zero if that is true for at least one of
6339   // the operands.
6340   if (Op32.getMachineOpcode() == PPC::AND) {
6341     SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
6342     bool Op0OK =
6343       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
6344     bool Op1OK =
6345       PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
6346     if (!Op0OK && !Op1OK)
6347       return false;
6348 
6349     ToPromote.insert(Op32.getNode());
6350 
6351     if (Op0OK)
6352       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6353 
6354     if (Op1OK)
6355       ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
6356 
6357     return true;
6358   }
6359 
6360   // For ANDI and ANDIS, the higher-order bits are zero if either that is true
6361   // of the first operand, or if the second operand is positive (so that it is
6362   // not sign extended).
6363   if (Op32.getMachineOpcode() == PPC::ANDI_rec ||
6364       Op32.getMachineOpcode() == PPC::ANDIS_rec) {
6365     SmallPtrSet<SDNode *, 16> ToPromote1;
6366     bool Op0OK =
6367       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
6368     bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
6369     if (!Op0OK && !Op1OK)
6370       return false;
6371 
6372     ToPromote.insert(Op32.getNode());
6373 
6374     if (Op0OK)
6375       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6376 
6377     return true;
6378   }
6379 
6380   return false;
6381 }
6382 
6383 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
6384   if (!Subtarget->isPPC64())
6385     return;
6386 
6387   // When we zero-extend from i32 to i64, we use a pattern like this:
6388   // def : Pat<(i64 (zext i32:$in)),
6389   //           (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
6390   //                   0, 32)>;
6391   // There are several 32-bit shift/rotate instructions, however, that will
6392   // clear the higher-order bits of their output, rendering the RLDICL
6393   // unnecessary. When that happens, we remove it here, and redefine the
6394   // relevant 32-bit operation to be a 64-bit operation.
6395 
6396   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6397 
6398   bool MadeChange = false;
6399   while (Position != CurDAG->allnodes_begin()) {
6400     SDNode *N = &*--Position;
6401     // Skip dead nodes and any non-machine opcodes.
6402     if (N->use_empty() || !N->isMachineOpcode())
6403       continue;
6404 
6405     if (N->getMachineOpcode() != PPC::RLDICL)
6406       continue;
6407 
6408     if (N->getConstantOperandVal(1) != 0 ||
6409         N->getConstantOperandVal(2) != 32)
6410       continue;
6411 
6412     SDValue ISR = N->getOperand(0);
6413     if (!ISR.isMachineOpcode() ||
6414         ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
6415       continue;
6416 
6417     if (!ISR.hasOneUse())
6418       continue;
6419 
6420     if (ISR.getConstantOperandVal(2) != PPC::sub_32)
6421       continue;
6422 
6423     SDValue IDef = ISR.getOperand(0);
6424     if (!IDef.isMachineOpcode() ||
6425         IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
6426       continue;
6427 
6428     // We now know that we're looking at a canonical i32 -> i64 zext. See if we
6429     // can get rid of it.
6430 
6431     SDValue Op32 = ISR->getOperand(1);
6432     if (!Op32.isMachineOpcode())
6433       continue;
6434 
6435     // There are some 32-bit instructions that always clear the high-order 32
6436     // bits, there are also some instructions (like AND) that we can look
6437     // through.
6438     SmallPtrSet<SDNode *, 16> ToPromote;
6439     if (!PeepholePPC64ZExtGather(Op32, ToPromote))
6440       continue;
6441 
6442     // If the ToPromote set contains nodes that have uses outside of the set
6443     // (except for the original INSERT_SUBREG), then abort the transformation.
6444     bool OutsideUse = false;
6445     for (SDNode *PN : ToPromote) {
6446       for (SDNode *UN : PN->uses()) {
6447         if (!ToPromote.count(UN) && UN != ISR.getNode()) {
6448           OutsideUse = true;
6449           break;
6450         }
6451       }
6452 
6453       if (OutsideUse)
6454         break;
6455     }
6456     if (OutsideUse)
6457       continue;
6458 
6459     MadeChange = true;
6460 
6461     // We now know that this zero extension can be removed by promoting to
6462     // nodes in ToPromote to 64-bit operations, where for operations in the
6463     // frontier of the set, we need to insert INSERT_SUBREGs for their
6464     // operands.
6465     for (SDNode *PN : ToPromote) {
6466       unsigned NewOpcode;
6467       switch (PN->getMachineOpcode()) {
6468       default:
6469         llvm_unreachable("Don't know the 64-bit variant of this instruction");
6470       case PPC::RLWINM:    NewOpcode = PPC::RLWINM8; break;
6471       case PPC::RLWNM:     NewOpcode = PPC::RLWNM8; break;
6472       case PPC::SLW:       NewOpcode = PPC::SLW8; break;
6473       case PPC::SRW:       NewOpcode = PPC::SRW8; break;
6474       case PPC::LI:        NewOpcode = PPC::LI8; break;
6475       case PPC::LIS:       NewOpcode = PPC::LIS8; break;
6476       case PPC::LHBRX:     NewOpcode = PPC::LHBRX8; break;
6477       case PPC::LWBRX:     NewOpcode = PPC::LWBRX8; break;
6478       case PPC::CNTLZW:    NewOpcode = PPC::CNTLZW8; break;
6479       case PPC::CNTTZW:    NewOpcode = PPC::CNTTZW8; break;
6480       case PPC::RLWIMI:    NewOpcode = PPC::RLWIMI8; break;
6481       case PPC::OR:        NewOpcode = PPC::OR8; break;
6482       case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
6483       case PPC::ORI:       NewOpcode = PPC::ORI8; break;
6484       case PPC::ORIS:      NewOpcode = PPC::ORIS8; break;
6485       case PPC::AND:       NewOpcode = PPC::AND8; break;
6486       case PPC::ANDI_rec:
6487         NewOpcode = PPC::ANDI8_rec;
6488         break;
6489       case PPC::ANDIS_rec:
6490         NewOpcode = PPC::ANDIS8_rec;
6491         break;
6492       }
6493 
6494       // Note: During the replacement process, the nodes will be in an
6495       // inconsistent state (some instructions will have operands with values
6496       // of the wrong type). Once done, however, everything should be right
6497       // again.
6498 
6499       SmallVector<SDValue, 4> Ops;
6500       for (const SDValue &V : PN->ops()) {
6501         if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
6502             !isa<ConstantSDNode>(V)) {
6503           SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
6504           SDNode *ReplOp =
6505             CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
6506                                    ISR.getNode()->getVTList(), ReplOpOps);
6507           Ops.push_back(SDValue(ReplOp, 0));
6508         } else {
6509           Ops.push_back(V);
6510         }
6511       }
6512 
6513       // Because all to-be-promoted nodes only have users that are other
6514       // promoted nodes (or the original INSERT_SUBREG), we can safely replace
6515       // the i32 result value type with i64.
6516 
6517       SmallVector<EVT, 2> NewVTs;
6518       SDVTList VTs = PN->getVTList();
6519       for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
6520         if (VTs.VTs[i] == MVT::i32)
6521           NewVTs.push_back(MVT::i64);
6522         else
6523           NewVTs.push_back(VTs.VTs[i]);
6524 
6525       LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld:    ");
6526       LLVM_DEBUG(PN->dump(CurDAG));
6527 
6528       CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
6529 
6530       LLVM_DEBUG(dbgs() << "\nNew: ");
6531       LLVM_DEBUG(PN->dump(CurDAG));
6532       LLVM_DEBUG(dbgs() << "\n");
6533     }
6534 
6535     // Now we replace the original zero extend and its associated INSERT_SUBREG
6536     // with the value feeding the INSERT_SUBREG (which has now been promoted to
6537     // return an i64).
6538 
6539     LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld:    ");
6540     LLVM_DEBUG(N->dump(CurDAG));
6541     LLVM_DEBUG(dbgs() << "\nNew: ");
6542     LLVM_DEBUG(Op32.getNode()->dump(CurDAG));
6543     LLVM_DEBUG(dbgs() << "\n");
6544 
6545     ReplaceUses(N, Op32.getNode());
6546   }
6547 
6548   if (MadeChange)
6549     CurDAG->RemoveDeadNodes();
6550 }
6551 
6552 void PPCDAGToDAGISel::PeepholePPC64() {
6553   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6554 
6555   while (Position != CurDAG->allnodes_begin()) {
6556     SDNode *N = &*--Position;
6557     // Skip dead nodes and any non-machine opcodes.
6558     if (N->use_empty() || !N->isMachineOpcode())
6559       continue;
6560 
6561     unsigned FirstOp;
6562     unsigned StorageOpcode = N->getMachineOpcode();
6563     bool RequiresMod4Offset = false;
6564 
6565     switch (StorageOpcode) {
6566     default: continue;
6567 
6568     case PPC::LWA:
6569     case PPC::LD:
6570     case PPC::DFLOADf64:
6571     case PPC::DFLOADf32:
6572       RequiresMod4Offset = true;
6573       LLVM_FALLTHROUGH;
6574     case PPC::LBZ:
6575     case PPC::LBZ8:
6576     case PPC::LFD:
6577     case PPC::LFS:
6578     case PPC::LHA:
6579     case PPC::LHA8:
6580     case PPC::LHZ:
6581     case PPC::LHZ8:
6582     case PPC::LWZ:
6583     case PPC::LWZ8:
6584       FirstOp = 0;
6585       break;
6586 
6587     case PPC::STD:
6588     case PPC::DFSTOREf64:
6589     case PPC::DFSTOREf32:
6590       RequiresMod4Offset = true;
6591       LLVM_FALLTHROUGH;
6592     case PPC::STB:
6593     case PPC::STB8:
6594     case PPC::STFD:
6595     case PPC::STFS:
6596     case PPC::STH:
6597     case PPC::STH8:
6598     case PPC::STW:
6599     case PPC::STW8:
6600       FirstOp = 1;
6601       break;
6602     }
6603 
6604     // If this is a load or store with a zero offset, or within the alignment,
6605     // we may be able to fold an add-immediate into the memory operation.
6606     // The check against alignment is below, as it can't occur until we check
6607     // the arguments to N
6608     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
6609       continue;
6610 
6611     SDValue Base = N->getOperand(FirstOp + 1);
6612     if (!Base.isMachineOpcode())
6613       continue;
6614 
6615     unsigned Flags = 0;
6616     bool ReplaceFlags = true;
6617 
6618     // When the feeding operation is an add-immediate of some sort,
6619     // determine whether we need to add relocation information to the
6620     // target flags on the immediate operand when we fold it into the
6621     // load instruction.
6622     //
6623     // For something like ADDItocL, the relocation information is
6624     // inferred from the opcode; when we process it in the AsmPrinter,
6625     // we add the necessary relocation there.  A load, though, can receive
6626     // relocation from various flavors of ADDIxxx, so we need to carry
6627     // the relocation information in the target flags.
6628     switch (Base.getMachineOpcode()) {
6629     default: continue;
6630 
6631     case PPC::ADDI8:
6632     case PPC::ADDI:
6633       // In some cases (such as TLS) the relocation information
6634       // is already in place on the operand, so copying the operand
6635       // is sufficient.
6636       ReplaceFlags = false;
6637       // For these cases, the immediate may not be divisible by 4, in
6638       // which case the fold is illegal for DS-form instructions.  (The
6639       // other cases provide aligned addresses and are always safe.)
6640       if (RequiresMod4Offset &&
6641           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
6642            Base.getConstantOperandVal(1) % 4 != 0))
6643         continue;
6644       break;
6645     case PPC::ADDIdtprelL:
6646       Flags = PPCII::MO_DTPREL_LO;
6647       break;
6648     case PPC::ADDItlsldL:
6649       Flags = PPCII::MO_TLSLD_LO;
6650       break;
6651     case PPC::ADDItocL:
6652       Flags = PPCII::MO_TOC_LO;
6653       break;
6654     }
6655 
6656     SDValue ImmOpnd = Base.getOperand(1);
6657 
6658     // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
6659     // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
6660     // we might have needed different @ha relocation values for the offset
6661     // pointers).
6662     int MaxDisplacement = 7;
6663     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
6664       const GlobalValue *GV = GA->getGlobal();
6665       Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
6666       MaxDisplacement = std::min((int)Alignment.value() - 1, MaxDisplacement);
6667     }
6668 
6669     bool UpdateHBase = false;
6670     SDValue HBase = Base.getOperand(0);
6671 
6672     int Offset = N->getConstantOperandVal(FirstOp);
6673     if (ReplaceFlags) {
6674       if (Offset < 0 || Offset > MaxDisplacement) {
6675         // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
6676         // one use, then we can do this for any offset, we just need to also
6677         // update the offset (i.e. the symbol addend) on the addis also.
6678         if (Base.getMachineOpcode() != PPC::ADDItocL)
6679           continue;
6680 
6681         if (!HBase.isMachineOpcode() ||
6682             HBase.getMachineOpcode() != PPC::ADDIStocHA8)
6683           continue;
6684 
6685         if (!Base.hasOneUse() || !HBase.hasOneUse())
6686           continue;
6687 
6688         SDValue HImmOpnd = HBase.getOperand(1);
6689         if (HImmOpnd != ImmOpnd)
6690           continue;
6691 
6692         UpdateHBase = true;
6693       }
6694     } else {
6695       // If we're directly folding the addend from an addi instruction, then:
6696       //  1. In general, the offset on the memory access must be zero.
6697       //  2. If the addend is a constant, then it can be combined with a
6698       //     non-zero offset, but only if the result meets the encoding
6699       //     requirements.
6700       if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
6701         Offset += C->getSExtValue();
6702 
6703         if (RequiresMod4Offset && (Offset % 4) != 0)
6704           continue;
6705 
6706         if (!isInt<16>(Offset))
6707           continue;
6708 
6709         ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
6710                                             ImmOpnd.getValueType());
6711       } else if (Offset != 0) {
6712         continue;
6713       }
6714     }
6715 
6716     // We found an opportunity.  Reverse the operands from the add
6717     // immediate and substitute them into the load or store.  If
6718     // needed, update the target flags for the immediate operand to
6719     // reflect the necessary relocation information.
6720     LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
6721     LLVM_DEBUG(Base->dump(CurDAG));
6722     LLVM_DEBUG(dbgs() << "\nN: ");
6723     LLVM_DEBUG(N->dump(CurDAG));
6724     LLVM_DEBUG(dbgs() << "\n");
6725 
6726     // If the relocation information isn't already present on the
6727     // immediate operand, add it now.
6728     if (ReplaceFlags) {
6729       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
6730         SDLoc dl(GA);
6731         const GlobalValue *GV = GA->getGlobal();
6732         Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
6733         // We can't perform this optimization for data whose alignment
6734         // is insufficient for the instruction encoding.
6735         if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) {
6736           LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
6737           continue;
6738         }
6739         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
6740       } else if (ConstantPoolSDNode *CP =
6741                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
6742         const Constant *C = CP->getConstVal();
6743         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, CP->getAlign(),
6744                                                 Offset, Flags);
6745       }
6746     }
6747 
6748     if (FirstOp == 1) // Store
6749       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
6750                                        Base.getOperand(0), N->getOperand(3));
6751     else // Load
6752       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
6753                                        N->getOperand(2));
6754 
6755     if (UpdateHBase)
6756       (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
6757                                        ImmOpnd);
6758 
6759     // The add-immediate may now be dead, in which case remove it.
6760     if (Base.getNode()->use_empty())
6761       CurDAG->RemoveDeadNode(Base.getNode());
6762   }
6763 }
6764 
6765 /// createPPCISelDag - This pass converts a legalized DAG into a
6766 /// PowerPC-specific DAG, ready for instruction scheduling.
6767 ///
6768 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
6769                                      CodeGenOpt::Level OptLevel) {
6770   return new PPCDAGToDAGISel(TM, OptLevel);
6771 }
6772