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