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