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