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