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