1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
13 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/Analysis/BranchProbabilityInfo.h"
20 #include "llvm/CodeGen/FunctionLoweringInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetOptions.h"
41 #define DEBUG_TYPE "ppc-codegen"
43 // FIXME: Remove this once the bug has been fixed!
44 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
45 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
48 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
49 cl::desc("use aggressive ppc isel for bit permutations"),
51 static cl::opt<bool> BPermRewriterNoMasking(
52 "ppc-bit-perm-rewriter-stress-rotates",
53 cl::desc("stress rotate selection in aggressive ppc isel for "
57 static cl::opt<bool> EnableBranchHint(
58 "ppc-use-branch-hint", cl::init(true),
59 cl::desc("Enable static hinting of branches on ppc"),
63 void initializePPCDAGToDAGISelPass(PassRegistry&);
67 //===--------------------------------------------------------------------===//
68 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
69 /// instructions for SelectionDAG operations.
71 class PPCDAGToDAGISel : public SelectionDAGISel {
72 const PPCTargetMachine &TM;
73 const PPCSubtarget *PPCSubTarget;
74 const PPCTargetLowering *PPCLowering;
75 unsigned GlobalBaseReg;
77 explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
78 : SelectionDAGISel(tm), TM(tm) {
79 initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
82 bool runOnMachineFunction(MachineFunction &MF) override {
83 // Make sure we re-emit a set of the global base reg if necessary
85 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
86 PPCLowering = PPCSubTarget->getTargetLowering();
87 SelectionDAGISel::runOnMachineFunction(MF);
89 if (!PPCSubTarget->isSVR4ABI())
95 void PreprocessISelDAG() override;
96 void PostprocessISelDAG() override;
98 /// getI32Imm - Return a target constant with the specified value, of type
100 inline SDValue getI32Imm(unsigned Imm, SDLoc dl) {
101 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
104 /// getI64Imm - Return a target constant with the specified value, of type
106 inline SDValue getI64Imm(uint64_t Imm, SDLoc dl) {
107 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
110 /// getSmallIPtrImm - Return a target constant of pointer type.
111 inline SDValue getSmallIPtrImm(unsigned Imm, SDLoc dl) {
112 return CurDAG->getTargetConstant(
113 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
116 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
117 /// rotate and mask opcode and mask operation.
118 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
119 unsigned &SH, unsigned &MB, unsigned &ME);
121 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
122 /// base register. Return the virtual register that holds this value.
123 SDNode *getGlobalBaseReg();
125 SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
127 // Select - Convert the specified operand from a target-independent to a
128 // target-specific node if it hasn't already been changed.
129 SDNode *Select(SDNode *N) override;
131 SDNode *SelectBitfieldInsert(SDNode *N);
132 SDNode *SelectBitPermutation(SDNode *N);
134 /// SelectCC - Select a comparison of the specified values with the
135 /// specified condition code, returning the CR# of the expression.
136 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
138 /// SelectAddrImm - Returns true if the address N can be represented by
139 /// a base register plus a signed 16-bit displacement [r+imm].
140 bool SelectAddrImm(SDValue N, SDValue &Disp,
142 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
145 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
146 /// immediate field. Note that the operand at this point is already the
147 /// result of a prior SelectAddressRegImm call.
148 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
149 if (N.getOpcode() == ISD::TargetConstant ||
150 N.getOpcode() == ISD::TargetGlobalAddress) {
158 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
159 /// represented as an indexed [r+r] operation. Returns false if it can
160 /// be represented by [r+imm], which are preferred.
161 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
162 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
165 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
166 /// represented as an indexed [r+r] operation.
167 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
168 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
171 /// SelectAddrImmX4 - Returns true if the address N can be represented by
172 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
173 /// Suitable for use by STD and friends.
174 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
175 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
178 // Select an address into a single register.
179 bool SelectAddr(SDValue N, SDValue &Base) {
184 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
185 /// inline asm expressions. It is always correct to compute the value into
186 /// a register. The case of adding a (possibly relocatable) constant to a
187 /// register can be improved, but it is wrong to substitute Reg+Reg for
188 /// Reg in an asm, because the load or store opcode would have to change.
189 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
190 unsigned ConstraintID,
191 std::vector<SDValue> &OutOps) override {
193 switch(ConstraintID) {
195 errs() << "ConstraintID: " << ConstraintID << "\n";
196 llvm_unreachable("Unexpected asm memory constraint");
197 case InlineAsm::Constraint_es:
198 case InlineAsm::Constraint_i:
199 case InlineAsm::Constraint_m:
200 case InlineAsm::Constraint_o:
201 case InlineAsm::Constraint_Q:
202 case InlineAsm::Constraint_Z:
203 case InlineAsm::Constraint_Zy:
204 // We need to make sure that this one operand does not end up in r0
205 // (because we might end up lowering this as 0(%op)).
206 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
207 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
209 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
211 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
212 dl, Op.getValueType(),
215 OutOps.push_back(NewOp);
221 void InsertVRSaveCode(MachineFunction &MF);
223 const char *getPassName() const override {
224 return "PowerPC DAG->DAG Pattern Instruction Selection";
227 // Include the pieces autogenerated from the target description.
228 #include "PPCGenDAGISel.inc"
231 SDNode *SelectSETCC(SDNode *N);
233 void PeepholePPC64();
234 void PeepholePPC64ZExt();
235 void PeepholeCROps();
237 SDValue combineToCMPB(SDNode *N);
238 void foldBoolExts(SDValue &Res, SDNode *&N);
240 bool AllUsersSelectZero(SDNode *N);
241 void SwapAllSelectUsers(SDNode *N);
243 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
247 /// InsertVRSaveCode - Once the entire function has been instruction selected,
248 /// all virtual registers are created and all machine instructions are built,
249 /// check to see if we need to save/restore VRSAVE. If so, do it.
250 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
251 // Check to see if this function uses vector registers, which means we have to
252 // save and restore the VRSAVE register and update it with the regs we use.
254 // In this case, there will be virtual registers of vector type created
255 // by the scheduler. Detect them now.
256 bool HasVectorVReg = false;
257 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
258 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
259 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
260 HasVectorVReg = true;
264 if (!HasVectorVReg) return; // nothing to do.
266 // If we have a vector register, we want to emit code into the entry and exit
267 // blocks to save and restore the VRSAVE register. We do this here (instead
268 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
270 // 1. This (trivially) reduces the load on the register allocator, by not
271 // having to represent the live range of the VRSAVE register.
272 // 2. This (more significantly) allows us to create a temporary virtual
273 // register to hold the saved VRSAVE value, allowing this temporary to be
274 // register allocated, instead of forcing it to be spilled to the stack.
276 // Create two vregs - one to hold the VRSAVE register that is live-in to the
277 // function and one for the value after having bits or'd into it.
278 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
279 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
281 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
282 MachineBasicBlock &EntryBB = *Fn.begin();
284 // Emit the following code into the entry block:
285 // InVRSAVE = MFVRSAVE
286 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
287 // MTVRSAVE UpdatedVRSAVE
288 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
289 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
290 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
291 UpdatedVRSAVE).addReg(InVRSAVE);
292 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
294 // Find all return blocks, outputting a restore in each epilog.
295 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
296 if (BB->isReturnBlock()) {
297 IP = BB->end(); --IP;
299 // Skip over all terminator instructions, which are part of the return
301 MachineBasicBlock::iterator I2 = IP;
302 while (I2 != BB->begin() && (--I2)->isTerminator())
305 // Emit: MTVRSAVE InVRSave
306 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
312 /// getGlobalBaseReg - Output the instructions required to put the
313 /// base address to use for accessing globals into a register.
315 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
316 if (!GlobalBaseReg) {
317 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
318 // Insert the set of GlobalBaseReg into the first MBB of the function
319 MachineBasicBlock &FirstMBB = MF->front();
320 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
321 const Module *M = MF->getFunction()->getParent();
324 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
325 if (PPCSubTarget->isTargetELF()) {
326 GlobalBaseReg = PPC::R30;
327 if (M->getPICLevel() == PICLevel::Small) {
328 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
329 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
330 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
332 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
333 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
334 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
335 BuildMI(FirstMBB, MBBI, dl,
336 TII.get(PPC::UpdateGBR), GlobalBaseReg)
337 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
338 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
342 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
343 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
344 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
347 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
348 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
349 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
352 return CurDAG->getRegister(GlobalBaseReg,
353 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
357 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
358 /// or 64-bit immediate, and if the value can be accurately represented as a
359 /// sign extension from a 16-bit value. If so, this returns true and the
361 static bool isIntS16Immediate(SDNode *N, short &Imm) {
362 if (N->getOpcode() != ISD::Constant)
365 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
366 if (N->getValueType(0) == MVT::i32)
367 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
369 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
372 static bool isIntS16Immediate(SDValue Op, short &Imm) {
373 return isIntS16Immediate(Op.getNode(), Imm);
377 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
378 /// operand. If so Imm will receive the 32-bit value.
379 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
380 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
381 Imm = cast<ConstantSDNode>(N)->getZExtValue();
387 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
388 /// operand. If so Imm will receive the 64-bit value.
389 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
390 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
391 Imm = cast<ConstantSDNode>(N)->getZExtValue();
397 // isInt32Immediate - This method tests to see if a constant operand.
398 // If so Imm will receive the 32 bit value.
399 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
400 return isInt32Immediate(N.getNode(), Imm);
403 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
404 const SDValue &DestMBB) {
405 assert(isa<BasicBlockSDNode>(DestMBB));
407 if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
409 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
410 const TerminatorInst *BBTerm = BB->getTerminator();
412 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
414 const BasicBlock *TBB = BBTerm->getSuccessor(0);
415 const BasicBlock *FBB = BBTerm->getSuccessor(1);
417 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
418 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
420 // We only want to handle cases which are easy to predict at static time, e.g.
421 // C++ throw statement, that is very likely not taken, or calling never
422 // returned function, e.g. stdlib exit(). So we set Threshold to filter
425 // Below is LLVM branch weight table, we only want to handle case 1, 2
427 // Case Taken:Nontaken Example
428 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
429 // 2. Invoke-terminating 1:1048575
430 // 3. Coldblock 4:64 __builtin_expect
431 // 4. Loop Branch 124:4 For loop
432 // 5. PH/ZH/FPH 20:12
433 const uint32_t Threshold = 10000;
435 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
436 return PPC::BR_NO_HINT;
438 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
439 << BB->getName() << "'\n"
440 << " -> " << TBB->getName() << ": " << TProb << "\n"
441 << " -> " << FBB->getName() << ": " << FProb << "\n");
443 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
445 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
446 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
447 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
448 std::swap(TProb, FProb);
450 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
453 // isOpcWithIntImmediate - This method tests to see if the node is a specific
454 // opcode and that it has a immediate integer right operand.
455 // If so Imm will receive the 32 bit value.
456 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
457 return N->getOpcode() == Opc
458 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
461 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
463 int FI = cast<FrameIndexSDNode>(N)->getIndex();
464 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
465 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
467 return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
468 getSmallIPtrImm(Offset, dl));
469 return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
470 getSmallIPtrImm(Offset, dl));
473 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
474 bool isShiftMask, unsigned &SH,
475 unsigned &MB, unsigned &ME) {
476 // Don't even go down this path for i64, since different logic will be
477 // necessary for rldicl/rldicr/rldimi.
478 if (N->getValueType(0) != MVT::i32)
482 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
483 unsigned Opcode = N->getOpcode();
484 if (N->getNumOperands() != 2 ||
485 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
488 if (Opcode == ISD::SHL) {
489 // apply shift left to mask if it comes first
490 if (isShiftMask) Mask = Mask << Shift;
491 // determine which bits are made indeterminant by shift
492 Indeterminant = ~(0xFFFFFFFFu << Shift);
493 } else if (Opcode == ISD::SRL) {
494 // apply shift right to mask if it comes first
495 if (isShiftMask) Mask = Mask >> Shift;
496 // determine which bits are made indeterminant by shift
497 Indeterminant = ~(0xFFFFFFFFu >> Shift);
498 // adjust for the left rotate
500 } else if (Opcode == ISD::ROTL) {
506 // if the mask doesn't intersect any Indeterminant bits
507 if (Mask && !(Mask & Indeterminant)) {
509 // make sure the mask is still a mask (wrap arounds may not be)
510 return isRunOfOnes(Mask, MB, ME);
515 /// SelectBitfieldInsert - turn an or of two masked values into
516 /// the rotate left word immediate then mask insert (rlwimi) instruction.
517 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
518 SDValue Op0 = N->getOperand(0);
519 SDValue Op1 = N->getOperand(1);
522 APInt LKZ, LKO, RKZ, RKO;
523 CurDAG->computeKnownBits(Op0, LKZ, LKO);
524 CurDAG->computeKnownBits(Op1, RKZ, RKO);
526 unsigned TargetMask = LKZ.getZExtValue();
527 unsigned InsertMask = RKZ.getZExtValue();
529 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
530 unsigned Op0Opc = Op0.getOpcode();
531 unsigned Op1Opc = Op1.getOpcode();
532 unsigned Value, SH = 0;
533 TargetMask = ~TargetMask;
534 InsertMask = ~InsertMask;
536 // If the LHS has a foldable shift and the RHS does not, then swap it to the
537 // RHS so that we can fold the shift into the insert.
538 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
539 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
540 Op0.getOperand(0).getOpcode() == ISD::SRL) {
541 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
542 Op1.getOperand(0).getOpcode() != ISD::SRL) {
544 std::swap(Op0Opc, Op1Opc);
545 std::swap(TargetMask, InsertMask);
548 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
549 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
550 Op1.getOperand(0).getOpcode() != ISD::SRL) {
552 std::swap(Op0Opc, Op1Opc);
553 std::swap(TargetMask, InsertMask);
558 if (isRunOfOnes(InsertMask, MB, ME)) {
561 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
562 isInt32Immediate(Op1.getOperand(1), Value)) {
563 Op1 = Op1.getOperand(0);
564 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
566 if (Op1Opc == ISD::AND) {
567 // The AND mask might not be a constant, and we need to make sure that
568 // if we're going to fold the masking with the insert, all bits not
569 // know to be zero in the mask are known to be one.
571 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
572 bool CanFoldMask = InsertMask == MKO.getZExtValue();
574 unsigned SHOpc = Op1.getOperand(0).getOpcode();
575 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
576 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
577 // Note that Value must be in range here (less than 32) because
578 // otherwise there would not be any bits set in InsertMask.
579 Op1 = Op1.getOperand(0).getOperand(0);
580 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
585 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
587 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
593 // Predict the number of instructions that would be generated by calling
595 static unsigned SelectInt64CountDirect(int64_t Imm) {
596 // Assume no remaining bits.
597 unsigned Remainder = 0;
598 // Assume no shift required.
601 // If it can't be represented as a 32 bit value.
602 if (!isInt<32>(Imm)) {
603 Shift = countTrailingZeros<uint64_t>(Imm);
604 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
606 // If the shifted value fits 32 bits.
607 if (isInt<32>(ImmSh)) {
608 // Go with the shifted value.
611 // Still stuck with a 64 bit value.
618 // Intermediate operand.
621 // Handle first 32 bits.
622 unsigned Lo = Imm & 0xFFFF;
625 if (isInt<16>(Imm)) {
629 // Handle the Hi bits and Lo bits.
636 // If no shift, we're done.
637 if (!Shift) return Result;
639 // Shift for next step if the upper 32-bits were not zero.
643 // Add in the last bits as required.
644 if ((Remainder >> 16) & 0xFFFF)
646 if (Remainder & 0xFFFF)
652 static uint64_t Rot64(uint64_t Imm, unsigned R) {
653 return (Imm << R) | (Imm >> (64 - R));
656 static unsigned SelectInt64Count(int64_t Imm) {
657 unsigned Count = SelectInt64CountDirect(Imm);
661 for (unsigned r = 1; r < 63; ++r) {
662 uint64_t RImm = Rot64(Imm, r);
663 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
664 Count = std::min(Count, RCount);
666 // See comments in SelectInt64 for an explanation of the logic below.
667 unsigned LS = findLastSet(RImm);
671 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
672 uint64_t RImmWithOnes = RImm | OnesMask;
674 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
675 Count = std::min(Count, RCount);
681 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
682 // (above) needs to be kept in sync with this function.
683 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
684 // Assume no remaining bits.
685 unsigned Remainder = 0;
686 // Assume no shift required.
689 // If it can't be represented as a 32 bit value.
690 if (!isInt<32>(Imm)) {
691 Shift = countTrailingZeros<uint64_t>(Imm);
692 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
694 // If the shifted value fits 32 bits.
695 if (isInt<32>(ImmSh)) {
696 // Go with the shifted value.
699 // Still stuck with a 64 bit value.
706 // Intermediate operand.
709 // Handle first 32 bits.
710 unsigned Lo = Imm & 0xFFFF;
711 unsigned Hi = (Imm >> 16) & 0xFFFF;
713 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
714 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
718 if (isInt<16>(Imm)) {
720 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
722 // Handle the Hi bits.
723 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
724 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
726 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
727 SDValue(Result, 0), getI32Imm(Lo));
730 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
733 // If no shift, we're done.
734 if (!Shift) return Result;
736 // Shift for next step if the upper 32-bits were not zero.
738 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
741 getI32Imm(63 - Shift));
744 // Add in the last bits as required.
745 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
746 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
747 SDValue(Result, 0), getI32Imm(Hi));
749 if ((Lo = Remainder & 0xFFFF)) {
750 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
751 SDValue(Result, 0), getI32Imm(Lo));
757 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
758 unsigned Count = SelectInt64CountDirect(Imm);
760 return SelectInt64Direct(CurDAG, dl, Imm);
767 for (unsigned r = 1; r < 63; ++r) {
768 uint64_t RImm = Rot64(Imm, r);
769 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
770 if (RCount < Count) {
777 // If the immediate to generate has many trailing zeros, it might be
778 // worthwhile to generate a rotated value with too many leading ones
779 // (because that's free with li/lis's sign-extension semantics), and then
780 // mask them off after rotation.
782 unsigned LS = findLastSet(RImm);
783 // We're adding (63-LS) higher-order ones, and we expect to mask them off
784 // after performing the inverse rotation by (64-r). So we need that:
785 // 63-LS == 64-r => LS == r-1
789 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
790 uint64_t RImmWithOnes = RImm | OnesMask;
792 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
793 if (RCount < Count) {
796 MatImm = RImmWithOnes;
802 return SelectInt64Direct(CurDAG, dl, Imm);
804 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
805 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
808 SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, MatImm), 0);
809 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
810 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
813 // Select a 64-bit constant.
814 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
818 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
819 return SelectInt64(CurDAG, dl, Imm);
823 class BitPermutationSelector {
827 // The bit number in the value, using a convention where bit 0 is the
836 ValueBit(SDValue V, unsigned I, Kind K = Variable)
837 : V(V), Idx(I), K(K) {}
838 ValueBit(Kind K = Variable)
839 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
841 bool isZero() const {
842 return K == ConstZero;
845 bool hasValue() const {
846 return K == Variable;
849 SDValue getValue() const {
850 assert(hasValue() && "Cannot get the value of a constant bit");
854 unsigned getValueBitIndex() const {
855 assert(hasValue() && "Cannot get the value bit index of a constant bit");
860 // A bit group has the same underlying value and the same rotate factor.
864 unsigned StartIdx, EndIdx;
866 // This rotation amount assumes that the lower 32 bits of the quantity are
867 // replicated in the high 32 bits by the rotation operator (which is done
868 // by rlwinm and friends in 64-bit mode).
870 // Did converting to Repl32 == true change the rotation factor? If it did,
871 // it decreased it by 32.
873 // Was this group coalesced after setting Repl32 to true?
874 bool Repl32Coalesced;
876 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
877 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
878 Repl32Coalesced(false) {
879 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
880 " [" << S << ", " << E << "]\n");
884 // Information on each (Value, RLAmt) pair (like the number of groups
885 // associated with each) used to choose the lowering method.
886 struct ValueRotInfo {
890 unsigned FirstGroupStartIdx;
894 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
897 // For sorting (in reverse order) by NumGroups, and then by
898 // FirstGroupStartIdx.
899 bool operator < (const ValueRotInfo &Other) const {
900 // We need to sort so that the non-Repl32 come first because, when we're
901 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
902 // masking operation.
903 if (Repl32 < Other.Repl32)
905 else if (Repl32 > Other.Repl32)
907 else if (NumGroups > Other.NumGroups)
909 else if (NumGroups < Other.NumGroups)
911 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
917 // Return true if something interesting was deduced, return false if we're
918 // providing only a generic representation of V (or something else likewise
919 // uninteresting for instruction selection).
920 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
921 switch (V.getOpcode()) {
924 if (isa<ConstantSDNode>(V.getOperand(1))) {
925 unsigned RotAmt = V.getConstantOperandVal(1);
927 SmallVector<ValueBit, 64> LHSBits(Bits.size());
928 getValueBits(V.getOperand(0), LHSBits);
930 for (unsigned i = 0; i < Bits.size(); ++i)
931 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
937 if (isa<ConstantSDNode>(V.getOperand(1))) {
938 unsigned ShiftAmt = V.getConstantOperandVal(1);
940 SmallVector<ValueBit, 64> LHSBits(Bits.size());
941 getValueBits(V.getOperand(0), LHSBits);
943 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
944 Bits[i] = LHSBits[i - ShiftAmt];
946 for (unsigned i = 0; i < ShiftAmt; ++i)
947 Bits[i] = ValueBit(ValueBit::ConstZero);
953 if (isa<ConstantSDNode>(V.getOperand(1))) {
954 unsigned ShiftAmt = V.getConstantOperandVal(1);
956 SmallVector<ValueBit, 64> LHSBits(Bits.size());
957 getValueBits(V.getOperand(0), LHSBits);
959 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
960 Bits[i] = LHSBits[i + ShiftAmt];
962 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
963 Bits[i] = ValueBit(ValueBit::ConstZero);
969 if (isa<ConstantSDNode>(V.getOperand(1))) {
970 uint64_t Mask = V.getConstantOperandVal(1);
972 SmallVector<ValueBit, 64> LHSBits(Bits.size());
973 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
975 for (unsigned i = 0; i < Bits.size(); ++i)
976 if (((Mask >> i) & 1) == 1)
977 Bits[i] = LHSBits[i];
979 Bits[i] = ValueBit(ValueBit::ConstZero);
981 // Mark this as interesting, only if the LHS was also interesting. This
982 // prevents the overall procedure from matching a single immediate 'and'
983 // (which is non-optimal because such an and might be folded with other
984 // things if we don't select it here).
989 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
990 getValueBits(V.getOperand(0), LHSBits);
991 getValueBits(V.getOperand(1), RHSBits);
993 bool AllDisjoint = true;
994 for (unsigned i = 0; i < Bits.size(); ++i)
995 if (LHSBits[i].isZero())
996 Bits[i] = RHSBits[i];
997 else if (RHSBits[i].isZero())
998 Bits[i] = LHSBits[i];
1000 AllDisjoint = false;
1011 for (unsigned i = 0; i < Bits.size(); ++i)
1012 Bits[i] = ValueBit(V, i);
1017 // For each value (except the constant ones), compute the left-rotate amount
1018 // to get it from its original to final position.
1019 void computeRotationAmounts() {
1021 RLAmt.resize(Bits.size());
1022 for (unsigned i = 0; i < Bits.size(); ++i)
1023 if (Bits[i].hasValue()) {
1024 unsigned VBI = Bits[i].getValueBitIndex();
1028 RLAmt[i] = Bits.size() - (VBI - i);
1029 } else if (Bits[i].isZero()) {
1031 RLAmt[i] = UINT32_MAX;
1033 llvm_unreachable("Unknown value bit type");
1037 // Collect groups of consecutive bits with the same underlying value and
1038 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1039 // they break up groups.
1040 void collectBitGroups(bool LateMask) {
1043 unsigned LastRLAmt = RLAmt[0];
1044 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1045 unsigned LastGroupStartIdx = 0;
1046 for (unsigned i = 1; i < Bits.size(); ++i) {
1047 unsigned ThisRLAmt = RLAmt[i];
1048 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1049 if (LateMask && !ThisValue) {
1050 ThisValue = LastValue;
1051 ThisRLAmt = LastRLAmt;
1052 // If we're doing late masking, then the first bit group always starts
1053 // at zero (even if the first bits were zero).
1054 if (BitGroups.empty())
1055 LastGroupStartIdx = 0;
1058 // If this bit has the same underlying value and the same rotate factor as
1059 // the last one, then they're part of the same group.
1060 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1063 if (LastValue.getNode())
1064 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1066 LastRLAmt = ThisRLAmt;
1067 LastValue = ThisValue;
1068 LastGroupStartIdx = i;
1070 if (LastValue.getNode())
1071 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1074 if (BitGroups.empty())
1077 // We might be able to combine the first and last groups.
1078 if (BitGroups.size() > 1) {
1079 // If the first and last groups are the same, then remove the first group
1080 // in favor of the last group, making the ending index of the last group
1081 // equal to the ending index of the to-be-removed first group.
1082 if (BitGroups[0].StartIdx == 0 &&
1083 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1084 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1085 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1086 DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1087 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1088 BitGroups.erase(BitGroups.begin());
1093 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1094 // associated with each. If there is a degeneracy, pick the one that occurs
1095 // first (in the final value).
1096 void collectValueRotInfo() {
1099 for (auto &BG : BitGroups) {
1100 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1101 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1103 VRI.RLAmt = BG.RLAmt;
1104 VRI.Repl32 = BG.Repl32;
1106 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1109 // Now that we've collected the various ValueRotInfo instances, we need to
1111 ValueRotsVec.clear();
1112 for (auto &I : ValueRots) {
1113 ValueRotsVec.push_back(I.second);
1115 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1118 // In 64-bit mode, rlwinm and friends have a rotation operator that
1119 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1120 // indices of these instructions can only be in the lower 32 bits, so they
1121 // can only represent some 64-bit bit groups. However, when they can be used,
1122 // the 32-bit replication can be used to represent, as a single bit group,
1123 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1124 // groups when possible. Returns true if any of the bit groups were
1126 void assignRepl32BitGroups() {
1127 // If we have bits like this:
1129 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1130 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1131 // Groups: | RLAmt = 8 | RLAmt = 40 |
1133 // But, making use of a 32-bit operation that replicates the low-order 32
1134 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1137 auto IsAllLow32 = [this](BitGroup & BG) {
1138 if (BG.StartIdx <= BG.EndIdx) {
1139 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1140 if (!Bits[i].hasValue())
1142 if (Bits[i].getValueBitIndex() >= 32)
1146 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1147 if (!Bits[i].hasValue())
1149 if (Bits[i].getValueBitIndex() >= 32)
1152 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1153 if (!Bits[i].hasValue())
1155 if (Bits[i].getValueBitIndex() >= 32)
1163 for (auto &BG : BitGroups) {
1164 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1165 if (IsAllLow32(BG)) {
1166 if (BG.RLAmt >= 32) {
1173 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1174 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1175 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1180 // Now walk through the bit groups, consolidating where possible.
1181 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1182 // We might want to remove this bit group by merging it with the previous
1183 // group (which might be the ending group).
1184 auto IP = (I == BitGroups.begin()) ?
1185 std::prev(BitGroups.end()) : std::prev(I);
1186 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1187 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1189 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1190 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1191 " [" << I->StartIdx << ", " << I->EndIdx <<
1192 "] with group with range [" <<
1193 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1195 IP->EndIdx = I->EndIdx;
1196 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1197 IP->Repl32Coalesced = true;
1198 I = BitGroups.erase(I);
1201 // There is a special case worth handling: If there is a single group
1202 // covering the entire upper 32 bits, and it can be merged with both
1203 // the next and previous groups (which might be the same group), then
1204 // do so. If it is the same group (so there will be only one group in
1205 // total), then we need to reverse the order of the range so that it
1206 // covers the entire 64 bits.
1207 if (I->StartIdx == 32 && I->EndIdx == 63) {
1208 assert(std::next(I) == BitGroups.end() &&
1209 "bit group ends at index 63 but there is another?");
1210 auto IN = BitGroups.begin();
1212 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1213 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1214 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1217 DEBUG(dbgs() << "\tcombining bit group for " <<
1218 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1219 " [" << I->StartIdx << ", " << I->EndIdx <<
1220 "] with 32-bit replicated groups with ranges [" <<
1221 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1222 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1225 // There is only one other group; change it to cover the whole
1226 // range (backward, so that it can still be Repl32 but cover the
1227 // whole 64-bit range).
1230 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1231 IP->Repl32Coalesced = true;
1232 I = BitGroups.erase(I);
1234 // There are two separate groups, one before this group and one
1235 // after us (at the beginning). We're going to remove this group,
1236 // but also the group at the very beginning.
1237 IP->EndIdx = IN->EndIdx;
1238 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1239 IP->Repl32Coalesced = true;
1240 I = BitGroups.erase(I);
1241 BitGroups.erase(BitGroups.begin());
1244 // This must be the last group in the vector (and we might have
1245 // just invalidated the iterator above), so break here.
1255 SDValue getI32Imm(unsigned Imm, SDLoc dl) {
1256 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1259 uint64_t getZerosMask() {
1261 for (unsigned i = 0; i < Bits.size(); ++i) {
1262 if (Bits[i].hasValue())
1264 Mask |= (UINT64_C(1) << i);
1270 // Depending on the number of groups for a particular value, it might be
1271 // better to rotate, mask explicitly (using andi/andis), and then or the
1272 // result. Select this part of the result first.
1273 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1274 if (BPermRewriterNoMasking)
1277 for (ValueRotInfo &VRI : ValueRotsVec) {
1279 for (unsigned i = 0; i < Bits.size(); ++i) {
1280 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1282 if (RLAmt[i] != VRI.RLAmt)
1287 // Compute the masks for andi/andis that would be necessary.
1288 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1289 assert((ANDIMask != 0 || ANDISMask != 0) &&
1290 "No set bits in mask for value bit groups");
1291 bool NeedsRotate = VRI.RLAmt != 0;
1293 // We're trying to minimize the number of instructions. If we have one
1294 // group, using one of andi/andis can break even. If we have three
1295 // groups, we can use both andi and andis and break even (to use both
1296 // andi and andis we also need to or the results together). We need four
1297 // groups if we also need to rotate. To use andi/andis we need to do more
1298 // than break even because rotate-and-mask instructions tend to be easier
1301 // FIXME: We've biased here against using andi/andis, which is right for
1302 // POWER cores, but not optimal everywhere. For example, on the A2,
1303 // andi/andis have single-cycle latency whereas the rotate-and-mask
1304 // instructions take two cycles, and it would be better to bias toward
1305 // andi/andis in break-even cases.
1307 unsigned NumAndInsts = (unsigned) NeedsRotate +
1308 (unsigned) (ANDIMask != 0) +
1309 (unsigned) (ANDISMask != 0) +
1310 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1311 (unsigned) (bool) Res;
1313 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1314 " RL: " << VRI.RLAmt << ":" <<
1315 "\n\t\t\tisel using masking: " << NumAndInsts <<
1316 " using rotates: " << VRI.NumGroups << "\n");
1318 if (NumAndInsts >= VRI.NumGroups)
1321 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1323 if (InstCnt) *InstCnt += NumAndInsts;
1328 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1329 getI32Imm(31, dl) };
1330 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1336 SDValue ANDIVal, ANDISVal;
1338 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1339 VRot, getI32Imm(ANDIMask, dl)), 0);
1341 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1342 VRot, getI32Imm(ANDISMask, dl)), 0);
1346 TotalVal = ANDISVal;
1350 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1351 ANDIVal, ANDISVal), 0);
1356 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1359 // Now, remove all groups with this underlying value and rotation
1361 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1362 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1367 // Instruction selection for the 32-bit case.
1368 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1372 if (InstCnt) *InstCnt = 0;
1374 // Take care of cases that should use andi/andis first.
1375 SelectAndParts32(dl, Res, InstCnt);
1377 // If we've not yet selected a 'starting' instruction, and we have no zeros
1378 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1379 // number of groups), and start with this rotated value.
1380 if ((!HasZeros || LateMask) && !Res) {
1381 ValueRotInfo &VRI = ValueRotsVec[0];
1383 if (InstCnt) *InstCnt += 1;
1385 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1386 getI32Imm(31, dl) };
1387 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1393 // Now, remove all groups with this underlying value and rotation factor.
1394 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1395 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1399 if (InstCnt) *InstCnt += BitGroups.size();
1401 // Insert the other groups (one at a time).
1402 for (auto &BG : BitGroups) {
1405 { BG.V, getI32Imm(BG.RLAmt, dl),
1406 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1407 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1408 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1411 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1412 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1413 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1414 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1419 unsigned Mask = (unsigned) getZerosMask();
1421 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1422 assert((ANDIMask != 0 || ANDISMask != 0) &&
1423 "No set bits in zeros mask?");
1425 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1426 (unsigned) (ANDISMask != 0) +
1427 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1429 SDValue ANDIVal, ANDISVal;
1431 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1432 Res, getI32Imm(ANDIMask, dl)), 0);
1434 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1435 Res, getI32Imm(ANDISMask, dl)), 0);
1442 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1443 ANDIVal, ANDISVal), 0);
1446 return Res.getNode();
1449 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1450 unsigned MaskStart, unsigned MaskEnd,
1452 // In the notation used by the instructions, 'start' and 'end' are reversed
1453 // because bits are counted from high to low order.
1454 unsigned InstMaskStart = 64 - MaskEnd - 1,
1455 InstMaskEnd = 64 - MaskStart - 1;
1460 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1461 InstMaskEnd == 63 - RLAmt)
1467 // For 64-bit values, not all combinations of rotates and masks are
1468 // available. Produce one if it is available.
1469 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1470 unsigned MaskStart, unsigned MaskEnd,
1471 unsigned *InstCnt = nullptr) {
1472 // In the notation used by the instructions, 'start' and 'end' are reversed
1473 // because bits are counted from high to low order.
1474 unsigned InstMaskStart = 64 - MaskEnd - 1,
1475 InstMaskEnd = 64 - MaskStart - 1;
1477 if (InstCnt) *InstCnt += 1;
1480 // This rotation amount assumes that the lower 32 bits of the quantity
1481 // are replicated in the high 32 bits by the rotation operator (which is
1482 // done by rlwinm and friends).
1483 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1484 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1486 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1487 getI32Imm(InstMaskEnd - 32, dl) };
1488 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1492 if (InstMaskEnd == 63) {
1494 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1495 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1498 if (InstMaskStart == 0) {
1500 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1501 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1504 if (InstMaskEnd == 63 - RLAmt) {
1506 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1507 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1510 // We cannot do this with a single instruction, so we'll use two. The
1511 // problem is that we're not free to choose both a rotation amount and mask
1512 // start and end independently. We can choose an arbitrary mask start and
1513 // end, but then the rotation amount is fixed. Rotation, however, can be
1514 // inverted, and so by applying an "inverse" rotation first, we can get the
1516 if (InstCnt) *InstCnt += 1;
1518 // The rotation mask for the second instruction must be MaskStart.
1519 unsigned RLAmt2 = MaskStart;
1520 // The first instruction must rotate V so that the overall rotation amount
1522 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1524 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1525 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1528 // For 64-bit values, not all combinations of rotates and masks are
1529 // available. Produce a rotate-mask-and-insert if one is available.
1530 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1531 bool Repl32, unsigned MaskStart,
1532 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1533 // In the notation used by the instructions, 'start' and 'end' are reversed
1534 // because bits are counted from high to low order.
1535 unsigned InstMaskStart = 64 - MaskEnd - 1,
1536 InstMaskEnd = 64 - MaskStart - 1;
1538 if (InstCnt) *InstCnt += 1;
1541 // This rotation amount assumes that the lower 32 bits of the quantity
1542 // are replicated in the high 32 bits by the rotation operator (which is
1543 // done by rlwinm and friends).
1544 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1545 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1547 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1548 getI32Imm(InstMaskEnd - 32, dl) };
1549 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1553 if (InstMaskEnd == 63 - RLAmt) {
1555 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1556 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1559 // We cannot do this with a single instruction, so we'll use two. The
1560 // problem is that we're not free to choose both a rotation amount and mask
1561 // start and end independently. We can choose an arbitrary mask start and
1562 // end, but then the rotation amount is fixed. Rotation, however, can be
1563 // inverted, and so by applying an "inverse" rotation first, we can get the
1565 if (InstCnt) *InstCnt += 1;
1567 // The rotation mask for the second instruction must be MaskStart.
1568 unsigned RLAmt2 = MaskStart;
1569 // The first instruction must rotate V so that the overall rotation amount
1571 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1573 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1574 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1577 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1578 if (BPermRewriterNoMasking)
1581 // The idea here is the same as in the 32-bit version, but with additional
1582 // complications from the fact that Repl32 might be true. Because we
1583 // aggressively convert bit groups to Repl32 form (which, for small
1584 // rotation factors, involves no other change), and then coalesce, it might
1585 // be the case that a single 64-bit masking operation could handle both
1586 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1587 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1588 // completely capture the new combined bit group.
1590 for (ValueRotInfo &VRI : ValueRotsVec) {
1593 // We need to add to the mask all bits from the associated bit groups.
1594 // If Repl32 is false, we need to add bits from bit groups that have
1595 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1596 // group is trivially convertable if it overlaps only with the lower 32
1597 // bits, and the group has not been coalesced.
1598 auto MatchingBG = [VRI](const BitGroup &BG) {
1602 unsigned EffRLAmt = BG.RLAmt;
1603 if (!VRI.Repl32 && BG.Repl32) {
1604 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1605 !BG.Repl32Coalesced) {
1611 } else if (VRI.Repl32 != BG.Repl32) {
1615 if (VRI.RLAmt != EffRLAmt)
1621 for (auto &BG : BitGroups) {
1622 if (!MatchingBG(BG))
1625 if (BG.StartIdx <= BG.EndIdx) {
1626 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1627 Mask |= (UINT64_C(1) << i);
1629 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1630 Mask |= (UINT64_C(1) << i);
1631 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1632 Mask |= (UINT64_C(1) << i);
1636 // We can use the 32-bit andi/andis technique if the mask does not
1637 // require any higher-order bits. This can save an instruction compared
1638 // to always using the general 64-bit technique.
1639 bool Use32BitInsts = isUInt<32>(Mask);
1640 // Compute the masks for andi/andis that would be necessary.
1641 unsigned ANDIMask = (Mask & UINT16_MAX),
1642 ANDISMask = (Mask >> 16) & UINT16_MAX;
1644 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1646 unsigned NumAndInsts = (unsigned) NeedsRotate +
1647 (unsigned) (bool) Res;
1649 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1650 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1652 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1654 unsigned NumRLInsts = 0;
1655 bool FirstBG = true;
1656 for (auto &BG : BitGroups) {
1657 if (!MatchingBG(BG))
1660 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1665 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1666 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1667 "\n\t\t\tisel using masking: " << NumAndInsts <<
1668 " using rotates: " << NumRLInsts << "\n");
1670 // When we'd use andi/andis, we bias toward using the rotates (andi only
1671 // has a record form, and is cracked on POWER cores). However, when using
1672 // general 64-bit constant formation, bias toward the constant form,
1673 // because that exposes more opportunities for CSE.
1674 if (NumAndInsts > NumRLInsts)
1676 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1679 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1681 if (InstCnt) *InstCnt += NumAndInsts;
1684 // We actually need to generate a rotation if we have a non-zero rotation
1685 // factor or, in the Repl32 case, if we care about any of the
1686 // higher-order replicated bits. In the latter case, we generate a mask
1687 // backward so that it actually includes the entire 64 bits.
1688 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1689 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1690 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1695 if (Use32BitInsts) {
1696 assert((ANDIMask != 0 || ANDISMask != 0) &&
1697 "No set bits in mask when using 32-bit ands for 64-bit value");
1699 SDValue ANDIVal, ANDISVal;
1701 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1702 VRot, getI32Imm(ANDIMask, dl)), 0);
1704 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1705 VRot, getI32Imm(ANDISMask, dl)), 0);
1708 TotalVal = ANDISVal;
1712 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1713 ANDIVal, ANDISVal), 0);
1715 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1717 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1718 VRot, TotalVal), 0);
1724 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1727 // Now, remove all groups with this underlying value and rotation
1729 eraseMatchingBitGroups(MatchingBG);
1733 // Instruction selection for the 64-bit case.
1734 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1738 if (InstCnt) *InstCnt = 0;
1740 // Take care of cases that should use andi/andis first.
1741 SelectAndParts64(dl, Res, InstCnt);
1743 // If we've not yet selected a 'starting' instruction, and we have no zeros
1744 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1745 // number of groups), and start with this rotated value.
1746 if ((!HasZeros || LateMask) && !Res) {
1747 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1748 // groups will come first, and so the VRI representing the largest number
1749 // of groups might not be first (it might be the first Repl32 groups).
1750 unsigned MaxGroupsIdx = 0;
1751 if (!ValueRotsVec[0].Repl32) {
1752 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1753 if (ValueRotsVec[i].Repl32) {
1754 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1760 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1761 bool NeedsRotate = false;
1764 } else if (VRI.Repl32) {
1765 for (auto &BG : BitGroups) {
1766 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1767 BG.Repl32 != VRI.Repl32)
1770 // We don't need a rotate if the bit group is confined to the lower
1772 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1781 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1782 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1787 // Now, remove all groups with this underlying value and rotation factor.
1789 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1790 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1791 BG.Repl32 == VRI.Repl32;
1795 // Because 64-bit rotates are more flexible than inserts, we might have a
1796 // preference regarding which one we do first (to save one instruction).
1798 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1799 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1801 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1803 if (I != BitGroups.begin()) {
1806 BitGroups.insert(BitGroups.begin(), BG);
1813 // Insert the other groups (one at a time).
1814 for (auto &BG : BitGroups) {
1816 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1817 BG.EndIdx, InstCnt);
1819 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1820 BG.StartIdx, BG.EndIdx, InstCnt);
1824 uint64_t Mask = getZerosMask();
1826 // We can use the 32-bit andi/andis technique if the mask does not
1827 // require any higher-order bits. This can save an instruction compared
1828 // to always using the general 64-bit technique.
1829 bool Use32BitInsts = isUInt<32>(Mask);
1830 // Compute the masks for andi/andis that would be necessary.
1831 unsigned ANDIMask = (Mask & UINT16_MAX),
1832 ANDISMask = (Mask >> 16) & UINT16_MAX;
1834 if (Use32BitInsts) {
1835 assert((ANDIMask != 0 || ANDISMask != 0) &&
1836 "No set bits in mask when using 32-bit ands for 64-bit value");
1838 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1839 (unsigned) (ANDISMask != 0) +
1840 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1842 SDValue ANDIVal, ANDISVal;
1844 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1845 Res, getI32Imm(ANDIMask, dl)), 0);
1847 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1848 Res, getI32Imm(ANDISMask, dl)), 0);
1855 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1856 ANDIVal, ANDISVal), 0);
1858 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1860 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1862 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1867 return Res.getNode();
1870 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1871 // Fill in BitGroups.
1872 collectBitGroups(LateMask);
1873 if (BitGroups.empty())
1876 // For 64-bit values, figure out when we can use 32-bit instructions.
1877 if (Bits.size() == 64)
1878 assignRepl32BitGroups();
1880 // Fill in ValueRotsVec.
1881 collectValueRotInfo();
1883 if (Bits.size() == 32) {
1884 return Select32(N, LateMask, InstCnt);
1886 assert(Bits.size() == 64 && "Not 64 bits here?");
1887 return Select64(N, LateMask, InstCnt);
1893 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1894 BitGroups.erase(std::remove_if(BitGroups.begin(), BitGroups.end(), F),
1898 SmallVector<ValueBit, 64> Bits;
1901 SmallVector<unsigned, 64> RLAmt;
1903 SmallVector<BitGroup, 16> BitGroups;
1905 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1906 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1908 SelectionDAG *CurDAG;
1911 BitPermutationSelector(SelectionDAG *DAG)
1914 // Here we try to match complex bit permutations into a set of
1915 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1916 // known to produce optimial code for common cases (like i32 byte swapping).
1917 SDNode *Select(SDNode *N) {
1918 Bits.resize(N->getValueType(0).getSizeInBits());
1919 if (!getValueBits(SDValue(N, 0), Bits))
1922 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1923 " selection for: ");
1924 DEBUG(N->dump(CurDAG));
1926 // Fill it RLAmt and set HasZeros.
1927 computeRotationAmounts();
1930 return Select(N, false);
1932 // We currently have two techniques for handling results with zeros: early
1933 // masking (the default) and late masking. Late masking is sometimes more
1934 // efficient, but because the structure of the bit groups is different, it
1935 // is hard to tell without generating both and comparing the results. With
1936 // late masking, we ignore zeros in the resulting value when inserting each
1937 // set of bit groups, and then mask in the zeros at the end. With early
1938 // masking, we only insert the non-zero parts of the result at every step.
1940 unsigned InstCnt, InstCntLateMask;
1941 DEBUG(dbgs() << "\tEarly masking:\n");
1942 SDNode *RN = Select(N, false, &InstCnt);
1943 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1945 DEBUG(dbgs() << "\tLate masking:\n");
1946 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1947 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1950 if (InstCnt <= InstCntLateMask) {
1951 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1955 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1959 } // anonymous namespace
1961 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1962 if (N->getValueType(0) != MVT::i32 &&
1963 N->getValueType(0) != MVT::i64)
1966 if (!UseBitPermRewriter)
1969 switch (N->getOpcode()) {
1976 BitPermutationSelector BPS(CurDAG);
1977 return BPS.Select(N);
1984 /// SelectCC - Select a comparison of the specified values with the specified
1985 /// condition code, returning the CR# of the expression.
1986 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1987 ISD::CondCode CC, SDLoc dl) {
1988 // Always select the LHS.
1991 if (LHS.getValueType() == MVT::i32) {
1993 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1994 if (isInt32Immediate(RHS, Imm)) {
1995 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1996 if (isUInt<16>(Imm))
1997 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1998 getI32Imm(Imm & 0xFFFF, dl)),
2000 // If this is a 16-bit signed immediate, fold it.
2001 if (isInt<16>((int)Imm))
2002 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2003 getI32Imm(Imm & 0xFFFF, dl)),
2006 // For non-equality comparisons, the default code would materialize the
2007 // constant, then compare against it, like this:
2009 // ori r2, r2, 22136
2011 // Since we are just comparing for equality, we can emit this instead:
2012 // xoris r0,r3,0x1234
2013 // cmplwi cr0,r0,0x5678
2015 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2016 getI32Imm(Imm >> 16, dl)), 0);
2017 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2018 getI32Imm(Imm & 0xFFFF, dl)), 0);
2021 } else if (ISD::isUnsignedIntSetCC(CC)) {
2022 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2023 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2024 getI32Imm(Imm & 0xFFFF, dl)), 0);
2028 if (isIntS16Immediate(RHS, SImm))
2029 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2030 getI32Imm((int)SImm & 0xFFFF,
2035 } else if (LHS.getValueType() == MVT::i64) {
2037 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2038 if (isInt64Immediate(RHS.getNode(), Imm)) {
2039 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2040 if (isUInt<16>(Imm))
2041 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2042 getI32Imm(Imm & 0xFFFF, dl)),
2044 // If this is a 16-bit signed immediate, fold it.
2046 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2047 getI32Imm(Imm & 0xFFFF, dl)),
2050 // For non-equality comparisons, the default code would materialize the
2051 // constant, then compare against it, like this:
2053 // ori r2, r2, 22136
2055 // Since we are just comparing for equality, we can emit this instead:
2056 // xoris r0,r3,0x1234
2057 // cmpldi cr0,r0,0x5678
2059 if (isUInt<32>(Imm)) {
2060 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2061 getI64Imm(Imm >> 16, dl)), 0);
2062 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2063 getI64Imm(Imm & 0xFFFF, dl)),
2068 } else if (ISD::isUnsignedIntSetCC(CC)) {
2069 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2070 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2071 getI64Imm(Imm & 0xFFFF, dl)), 0);
2075 if (isIntS16Immediate(RHS, SImm))
2076 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2077 getI64Imm(SImm & 0xFFFF, dl)),
2081 } else if (LHS.getValueType() == MVT::f32) {
2084 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2085 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2087 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2090 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2096 llvm_unreachable("Should be lowered by legalize!");
2097 default: llvm_unreachable("Unknown condition!");
2099 case ISD::SETEQ: return PPC::PRED_EQ;
2101 case ISD::SETNE: return PPC::PRED_NE;
2103 case ISD::SETLT: return PPC::PRED_LT;
2105 case ISD::SETLE: return PPC::PRED_LE;
2107 case ISD::SETGT: return PPC::PRED_GT;
2109 case ISD::SETGE: return PPC::PRED_GE;
2110 case ISD::SETO: return PPC::PRED_NU;
2111 case ISD::SETUO: return PPC::PRED_UN;
2112 // These two are invalid for floating point. Assume we have int.
2113 case ISD::SETULT: return PPC::PRED_LT;
2114 case ISD::SETUGT: return PPC::PRED_GT;
2118 /// getCRIdxForSetCC - Return the index of the condition register field
2119 /// associated with the SetCC condition, and whether or not the field is
2120 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2121 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2124 default: llvm_unreachable("Unknown condition!");
2126 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2128 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2130 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2131 case ISD::SETUO: return 3; // Bit #3 = SETUO
2133 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2135 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2137 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2138 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2143 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2144 // These are invalid for floating point. Assume integer.
2145 case ISD::SETULT: return 0;
2146 case ISD::SETUGT: return 1;
2150 // getVCmpInst: return the vector compare instruction for the specified
2151 // vector type and condition code. Since this is for altivec specific code,
2152 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2153 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2154 bool HasVSX, bool &Swap, bool &Negate) {
2158 if (VecVT.isFloatingPoint()) {
2159 /* Handle some cases by swapping input operands. */
2161 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2162 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2163 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2164 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2165 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2166 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2169 /* Handle some cases by negating the result. */
2171 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2172 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2173 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2174 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2177 /* We have instructions implementing the remaining cases. */
2181 if (VecVT == MVT::v4f32)
2182 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2183 else if (VecVT == MVT::v2f64)
2184 return PPC::XVCMPEQDP;
2188 if (VecVT == MVT::v4f32)
2189 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2190 else if (VecVT == MVT::v2f64)
2191 return PPC::XVCMPGTDP;
2195 if (VecVT == MVT::v4f32)
2196 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2197 else if (VecVT == MVT::v2f64)
2198 return PPC::XVCMPGEDP;
2203 llvm_unreachable("Invalid floating-point vector compare condition");
2205 /* Handle some cases by swapping input operands. */
2207 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2208 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2209 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2210 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2213 /* Handle some cases by negating the result. */
2215 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2216 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2217 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2218 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2221 /* We have instructions implementing the remaining cases. */
2225 if (VecVT == MVT::v16i8)
2226 return PPC::VCMPEQUB;
2227 else if (VecVT == MVT::v8i16)
2228 return PPC::VCMPEQUH;
2229 else if (VecVT == MVT::v4i32)
2230 return PPC::VCMPEQUW;
2231 else if (VecVT == MVT::v2i64)
2232 return PPC::VCMPEQUD;
2235 if (VecVT == MVT::v16i8)
2236 return PPC::VCMPGTSB;
2237 else if (VecVT == MVT::v8i16)
2238 return PPC::VCMPGTSH;
2239 else if (VecVT == MVT::v4i32)
2240 return PPC::VCMPGTSW;
2241 else if (VecVT == MVT::v2i64)
2242 return PPC::VCMPGTSD;
2245 if (VecVT == MVT::v16i8)
2246 return PPC::VCMPGTUB;
2247 else if (VecVT == MVT::v8i16)
2248 return PPC::VCMPGTUH;
2249 else if (VecVT == MVT::v4i32)
2250 return PPC::VCMPGTUW;
2251 else if (VecVT == MVT::v2i64)
2252 return PPC::VCMPGTUD;
2257 llvm_unreachable("Invalid integer vector compare condition");
2261 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2264 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2266 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2267 bool isPPC64 = (PtrVT == MVT::i64);
2269 if (!PPCSubTarget->useCRBits() &&
2270 isInt32Immediate(N->getOperand(1), Imm)) {
2271 // We can codegen setcc op, imm very efficiently compared to a brcond.
2272 // Check for those cases here.
2275 SDValue Op = N->getOperand(0);
2279 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2280 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2281 getI32Imm(31, dl) };
2282 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2287 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2288 Op, getI32Imm(~0U, dl)), 0);
2289 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2293 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2294 getI32Imm(31, dl) };
2295 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2299 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2300 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2301 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2302 getI32Imm(31, dl) };
2303 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2306 } else if (Imm == ~0U) { // setcc op, -1
2307 SDValue Op = N->getOperand(0);
2312 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2313 Op, getI32Imm(1, dl)), 0);
2314 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2315 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2318 0), Op.getValue(1));
2321 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2322 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2323 Op, getI32Imm(~0U, dl));
2324 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2325 Op, SDValue(AD, 1));
2328 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2329 getI32Imm(1, dl)), 0);
2330 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2332 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2333 getI32Imm(31, dl) };
2334 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2337 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2338 getI32Imm(31, dl) };
2339 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2340 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2347 SDValue LHS = N->getOperand(0);
2348 SDValue RHS = N->getOperand(1);
2350 // Altivec Vector compare instructions do not set any CR register by default and
2351 // vector compare operations return the same type as the operands.
2352 if (LHS.getValueType().isVector()) {
2353 if (PPCSubTarget->hasQPX())
2356 EVT VecVT = LHS.getValueType();
2358 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2359 PPCSubTarget->hasVSX(), Swap, Negate);
2361 std::swap(LHS, RHS);
2363 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2365 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2366 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2371 return CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2374 if (PPCSubTarget->useCRBits())
2378 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2379 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2382 // Force the ccreg into CR7.
2383 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2385 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2386 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2387 InFlag).getValue(1);
2389 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2392 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2393 getI32Imm(31, dl), getI32Imm(31, dl) };
2395 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2397 // Get the specified bit.
2399 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2400 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2403 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2404 // Transfer memoperands.
2405 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2406 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2407 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2412 // Select - Convert the specified operand from a target-independent to a
2413 // target-specific node if it hasn't already been changed.
2414 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2416 if (N->isMachineOpcode()) {
2418 return nullptr; // Already selected.
2421 // In case any misguided DAG-level optimizations form an ADD with a
2422 // TargetConstant operand, crash here instead of miscompiling (by selecting
2423 // an r+r add instead of some kind of r+i add).
2424 if (N->getOpcode() == ISD::ADD &&
2425 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2426 llvm_unreachable("Invalid ADD with TargetConstant operand");
2428 // Try matching complex bit permutations before doing anything else.
2429 if (SDNode *NN = SelectBitPermutation(N))
2432 switch (N->getOpcode()) {
2435 case ISD::Constant: {
2436 if (N->getValueType(0) == MVT::i64)
2437 return SelectInt64(CurDAG, N);
2442 SDNode *SN = SelectSETCC(N);
2447 case PPCISD::GlobalBaseReg:
2448 return getGlobalBaseReg();
2450 case ISD::FrameIndex:
2451 return getFrameIndex(N, N);
2453 case PPCISD::MFOCRF: {
2454 SDValue InFlag = N->getOperand(1);
2455 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2456 N->getOperand(0), InFlag);
2459 case PPCISD::READ_TIME_BASE: {
2460 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2461 MVT::Other, N->getOperand(0));
2464 case PPCISD::SRA_ADDZE: {
2465 SDValue N0 = N->getOperand(0);
2467 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2468 getConstantIntValue(), dl,
2469 N->getValueType(0));
2470 if (N->getValueType(0) == MVT::i64) {
2472 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2474 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2475 SDValue(Op, 0), SDValue(Op, 1));
2477 assert(N->getValueType(0) == MVT::i32 &&
2478 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2480 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2482 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2483 SDValue(Op, 0), SDValue(Op, 1));
2488 // Handle preincrement loads.
2489 LoadSDNode *LD = cast<LoadSDNode>(N);
2490 EVT LoadedVT = LD->getMemoryVT();
2492 // Normal loads are handled by code generated from the .td file.
2493 if (LD->getAddressingMode() != ISD::PRE_INC)
2496 SDValue Offset = LD->getOffset();
2497 if (Offset.getOpcode() == ISD::TargetConstant ||
2498 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2501 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2502 if (LD->getValueType(0) != MVT::i64) {
2503 // Handle PPC32 integer and normal FP loads.
2504 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2505 switch (LoadedVT.getSimpleVT().SimpleTy) {
2506 default: llvm_unreachable("Invalid PPC load type!");
2507 case MVT::f64: Opcode = PPC::LFDU; break;
2508 case MVT::f32: Opcode = PPC::LFSU; break;
2509 case MVT::i32: Opcode = PPC::LWZU; break;
2510 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2512 case MVT::i8: Opcode = PPC::LBZU; break;
2515 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2516 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2517 switch (LoadedVT.getSimpleVT().SimpleTy) {
2518 default: llvm_unreachable("Invalid PPC load type!");
2519 case MVT::i64: Opcode = PPC::LDU; break;
2520 case MVT::i32: Opcode = PPC::LWZU8; break;
2521 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2523 case MVT::i8: Opcode = PPC::LBZU8; break;
2527 SDValue Chain = LD->getChain();
2528 SDValue Base = LD->getBasePtr();
2529 SDValue Ops[] = { Offset, Base, Chain };
2530 return transferMemOperands(
2531 N, CurDAG->getMachineNode(
2532 Opcode, dl, LD->getValueType(0),
2533 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other,
2537 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2538 if (LD->getValueType(0) != MVT::i64) {
2539 // Handle PPC32 integer and normal FP loads.
2540 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2541 switch (LoadedVT.getSimpleVT().SimpleTy) {
2542 default: llvm_unreachable("Invalid PPC load type!");
2543 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2544 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2545 case MVT::f64: Opcode = PPC::LFDUX; break;
2546 case MVT::f32: Opcode = PPC::LFSUX; break;
2547 case MVT::i32: Opcode = PPC::LWZUX; break;
2548 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2550 case MVT::i8: Opcode = PPC::LBZUX; break;
2553 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2554 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2555 "Invalid sext update load");
2556 switch (LoadedVT.getSimpleVT().SimpleTy) {
2557 default: llvm_unreachable("Invalid PPC load type!");
2558 case MVT::i64: Opcode = PPC::LDUX; break;
2559 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2560 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2562 case MVT::i8: Opcode = PPC::LBZUX8; break;
2566 SDValue Chain = LD->getChain();
2567 SDValue Base = LD->getBasePtr();
2568 SDValue Ops[] = { Base, Offset, Chain };
2569 return transferMemOperands(
2570 N, CurDAG->getMachineNode(
2571 Opcode, dl, LD->getValueType(0),
2572 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other,
2578 unsigned Imm, Imm2, SH, MB, ME;
2581 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2582 // with a mask, emit rlwinm
2583 if (isInt32Immediate(N->getOperand(1), Imm) &&
2584 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2585 SDValue Val = N->getOperand(0).getOperand(0);
2586 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2587 getI32Imm(ME, dl) };
2588 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2590 // If this is just a masked value where the input is not handled above, and
2591 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2592 if (isInt32Immediate(N->getOperand(1), Imm) &&
2593 isRunOfOnes(Imm, MB, ME) &&
2594 N->getOperand(0).getOpcode() != ISD::ROTL) {
2595 SDValue Val = N->getOperand(0);
2596 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2597 getI32Imm(ME, dl) };
2598 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2600 // If this is a 64-bit zero-extension mask, emit rldicl.
2601 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2603 SDValue Val = N->getOperand(0);
2604 MB = 64 - countTrailingOnes(Imm64);
2607 // If the operand is a logical right shift, we can fold it into this
2608 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2609 // for n <= mb. The right shift is really a left rotate followed by a
2610 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2612 if (Val.getOpcode() == ISD::SRL &&
2613 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2614 assert(Imm < 64 && "Illegal shift amount");
2615 Val = Val.getOperand(0);
2619 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2620 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2622 // AND X, 0 -> 0, not "rlwinm 32".
2623 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2624 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2627 // ISD::OR doesn't get all the bitfield insertion fun.
2628 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
2630 if (isInt32Immediate(N->getOperand(1), Imm) &&
2631 N->getOperand(0).getOpcode() == ISD::OR &&
2632 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2633 // The idea here is to check whether this is equivalent to:
2634 // (c1 & m) | (x & ~m)
2635 // where m is a run-of-ones mask. The logic here is that, for each bit in
2637 // - if both are 1, then the output will be 1.
2638 // - if both are 0, then the output will be 0.
2639 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
2641 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
2643 // If that last condition is never the case, then we can form m from the
2644 // bits that are the same between c1 and c2.
2646 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
2647 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2648 N->getOperand(0).getOperand(1),
2649 getI32Imm(0, dl), getI32Imm(MB, dl),
2650 getI32Imm(ME, dl) };
2651 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2655 // Other cases are autogenerated.
2659 if (N->getValueType(0) == MVT::i32)
2660 if (SDNode *I = SelectBitfieldInsert(N))
2664 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2665 isIntS16Immediate(N->getOperand(1), Imm)) {
2666 APInt LHSKnownZero, LHSKnownOne;
2667 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2669 // If this is equivalent to an add, then we can fold it with the
2670 // FrameIndex calculation.
2671 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2672 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2675 // Other cases are autogenerated.
2680 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2681 isIntS16Immediate(N->getOperand(1), Imm))
2682 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2687 unsigned Imm, SH, MB, ME;
2688 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2689 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2690 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2691 getI32Imm(SH, dl), getI32Imm(MB, dl),
2692 getI32Imm(ME, dl) };
2693 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2696 // Other cases are autogenerated.
2700 unsigned Imm, SH, MB, ME;
2701 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2702 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2703 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2704 getI32Imm(SH, dl), getI32Imm(MB, dl),
2705 getI32Imm(ME, dl) };
2706 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2709 // Other cases are autogenerated.
2712 // FIXME: Remove this once the ANDI glue bug is fixed:
2713 case PPCISD::ANDIo_1_EQ_BIT:
2714 case PPCISD::ANDIo_1_GT_BIT: {
2718 EVT InVT = N->getOperand(0).getValueType();
2719 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2720 "Invalid input type for ANDIo_1_EQ_BIT");
2722 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2723 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2725 CurDAG->getTargetConstant(1, dl, InVT)),
2727 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2729 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2730 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2732 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2734 SDValue(AndI.getNode(), 1) /* glue */);
2736 case ISD::SELECT_CC: {
2737 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2739 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2740 bool isPPC64 = (PtrVT == MVT::i64);
2742 // If this is a select of i1 operands, we'll pattern match it.
2743 if (PPCSubTarget->useCRBits() &&
2744 N->getOperand(0).getValueType() == MVT::i1)
2747 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2749 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2750 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2751 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2752 if (N1C->isNullValue() && N3C->isNullValue() &&
2753 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2754 // FIXME: Implement this optzn for PPC64.
2755 N->getValueType(0) == MVT::i32) {
2757 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2758 N->getOperand(0), getI32Imm(~0U, dl));
2759 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2760 SDValue(Tmp, 0), N->getOperand(0),
2764 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2766 if (N->getValueType(0) == MVT::i1) {
2767 // An i1 select is: (c & t) | (!c & f).
2769 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2773 default: llvm_unreachable("Invalid CC index");
2774 case 0: SRI = PPC::sub_lt; break;
2775 case 1: SRI = PPC::sub_gt; break;
2776 case 2: SRI = PPC::sub_eq; break;
2777 case 3: SRI = PPC::sub_un; break;
2780 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2782 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2784 SDValue C = Inv ? NotCCBit : CCBit,
2785 NotC = Inv ? CCBit : NotCCBit;
2787 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2788 C, N->getOperand(2)), 0);
2789 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2790 NotC, N->getOperand(3)), 0);
2792 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2795 unsigned BROpc = getPredicateForSetCC(CC);
2797 unsigned SelectCCOp;
2798 if (N->getValueType(0) == MVT::i32)
2799 SelectCCOp = PPC::SELECT_CC_I4;
2800 else if (N->getValueType(0) == MVT::i64)
2801 SelectCCOp = PPC::SELECT_CC_I8;
2802 else if (N->getValueType(0) == MVT::f32)
2803 if (PPCSubTarget->hasP8Vector())
2804 SelectCCOp = PPC::SELECT_CC_VSSRC;
2806 SelectCCOp = PPC::SELECT_CC_F4;
2807 else if (N->getValueType(0) == MVT::f64)
2808 if (PPCSubTarget->hasVSX())
2809 SelectCCOp = PPC::SELECT_CC_VSFRC;
2811 SelectCCOp = PPC::SELECT_CC_F8;
2812 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2813 SelectCCOp = PPC::SELECT_CC_QFRC;
2814 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2815 SelectCCOp = PPC::SELECT_CC_QSRC;
2816 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2817 SelectCCOp = PPC::SELECT_CC_QBRC;
2818 else if (N->getValueType(0) == MVT::v2f64 ||
2819 N->getValueType(0) == MVT::v2i64)
2820 SelectCCOp = PPC::SELECT_CC_VSRC;
2822 SelectCCOp = PPC::SELECT_CC_VRRC;
2824 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2825 getI32Imm(BROpc, dl) };
2826 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2829 if (PPCSubTarget->hasVSX()) {
2830 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2831 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2835 case ISD::VECTOR_SHUFFLE:
2836 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2837 N->getValueType(0) == MVT::v2i64)) {
2838 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2840 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2841 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2844 for (int i = 0; i < 2; ++i)
2845 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2850 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2851 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2852 isa<LoadSDNode>(Op1.getOperand(0))) {
2853 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2854 SDValue Base, Offset;
2856 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
2857 (LD->getMemoryVT() == MVT::f64 ||
2858 LD->getMemoryVT() == MVT::i64) &&
2859 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2860 SDValue Chain = LD->getChain();
2861 SDValue Ops[] = { Base, Offset, Chain };
2862 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2863 N->getValueType(0), Ops);
2867 // For little endian, we must swap the input operands and adjust
2868 // the mask elements (reverse and invert them).
2869 if (PPCSubTarget->isLittleEndian()) {
2870 std::swap(Op1, Op2);
2871 unsigned tmp = DM[0];
2876 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
2878 SDValue Ops[] = { Op1, Op2, DMV };
2879 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2885 bool IsPPC64 = PPCSubTarget->isPPC64();
2886 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2887 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2888 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2889 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2892 case PPCISD::COND_BRANCH: {
2893 // Op #0 is the Chain.
2894 // Op #1 is the PPC::PRED_* number.
2896 // Op #3 is the Dest MBB
2897 // Op #4 is the Flag.
2898 // Prevent PPC::PRED_* from being selected into LI.
2899 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2900 if (EnableBranchHint)
2901 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
2903 SDValue Pred = getI32Imm(PCC, dl);
2904 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2905 N->getOperand(0), N->getOperand(4) };
2906 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2909 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2910 unsigned PCC = getPredicateForSetCC(CC);
2912 if (N->getOperand(2).getValueType() == MVT::i1) {
2916 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2917 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2918 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2919 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2920 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2921 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2922 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2925 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2926 N->getOperand(Swap ? 3 : 2),
2927 N->getOperand(Swap ? 2 : 3)), 0);
2928 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2929 BitComp, N->getOperand(4), N->getOperand(0));
2932 if (EnableBranchHint)
2933 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
2935 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2936 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
2937 N->getOperand(4), N->getOperand(0) };
2938 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2941 // FIXME: Should custom lower this.
2942 SDValue Chain = N->getOperand(0);
2943 SDValue Target = N->getOperand(1);
2944 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2945 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2946 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2948 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2950 case PPCISD::TOC_ENTRY: {
2951 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2952 "Only supported for 64-bit ABI and 32-bit SVR4");
2953 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2954 SDValue GA = N->getOperand(0);
2955 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2956 MVT::i32, GA, N->getOperand(1)));
2959 // For medium and large code model, we generate two instructions as
2960 // described below. Otherwise we allow SelectCodeCommon to handle this,
2961 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2962 CodeModel::Model CModel = TM.getCodeModel();
2963 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2966 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2967 // If it must be toc-referenced according to PPCSubTarget, we generate:
2968 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2969 // Otherwise we generate:
2970 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2971 SDValue GA = N->getOperand(0);
2972 SDValue TOCbase = N->getOperand(1);
2973 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2976 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2977 CModel == CodeModel::Large)
2978 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2979 MVT::i64, GA, SDValue(Tmp, 0)));
2981 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2982 const GlobalValue *GV = G->getGlobal();
2983 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
2984 if (GVFlags & PPCII::MO_NLP_FLAG) {
2985 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2986 MVT::i64, GA, SDValue(Tmp, 0)));
2990 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2991 SDValue(Tmp, 0), GA);
2993 case PPCISD::PPC32_PICGOT: {
2994 // Generate a PIC-safe GOT reference.
2995 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2996 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2997 return CurDAG->SelectNodeTo(
2998 N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(CurDAG->getDataLayout()),
3001 case PPCISD::VADD_SPLAT: {
3002 // This expands into one of three sequences, depending on whether
3003 // the first operand is odd or even, positive or negative.
3004 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3005 isa<ConstantSDNode>(N->getOperand(1)) &&
3006 "Invalid operand on VADD_SPLAT!");
3008 int Elt = N->getConstantOperandVal(0);
3009 int EltSize = N->getConstantOperandVal(1);
3010 unsigned Opc1, Opc2, Opc3;
3014 Opc1 = PPC::VSPLTISB;
3015 Opc2 = PPC::VADDUBM;
3016 Opc3 = PPC::VSUBUBM;
3018 } else if (EltSize == 2) {
3019 Opc1 = PPC::VSPLTISH;
3020 Opc2 = PPC::VADDUHM;
3021 Opc3 = PPC::VSUBUHM;
3024 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3025 Opc1 = PPC::VSPLTISW;
3026 Opc2 = PPC::VADDUWM;
3027 Opc3 = PPC::VSUBUWM;
3031 if ((Elt & 1) == 0) {
3032 // Elt is even, in the range [-32,-18] + [16,30].
3034 // Convert: VADD_SPLAT elt, size
3035 // Into: tmp = VSPLTIS[BHW] elt
3036 // VADDU[BHW]M tmp, tmp
3037 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
3038 SDValue EltVal = getI32Imm(Elt >> 1, dl);
3039 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3040 SDValue TmpVal = SDValue(Tmp, 0);
3041 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
3043 } else if (Elt > 0) {
3044 // Elt is odd and positive, in the range [17,31].
3046 // Convert: VADD_SPLAT elt, size
3047 // Into: tmp1 = VSPLTIS[BHW] elt-16
3048 // tmp2 = VSPLTIS[BHW] -16
3049 // VSUBU[BHW]M tmp1, tmp2
3050 SDValue EltVal = getI32Imm(Elt - 16, dl);
3051 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3052 EltVal = getI32Imm(-16, dl);
3053 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3054 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3058 // Elt is odd and negative, in the range [-31,-17].
3060 // Convert: VADD_SPLAT elt, size
3061 // Into: tmp1 = VSPLTIS[BHW] elt+16
3062 // tmp2 = VSPLTIS[BHW] -16
3063 // VADDU[BHW]M tmp1, tmp2
3064 SDValue EltVal = getI32Imm(Elt + 16, dl);
3065 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3066 EltVal = getI32Imm(-16, dl);
3067 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3068 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3074 return SelectCode(N);
3077 // If the target supports the cmpb instruction, do the idiom recognition here.
3078 // We don't do this as a DAG combine because we don't want to do it as nodes
3079 // are being combined (because we might miss part of the eventual idiom). We
3080 // don't want to do it during instruction selection because we want to reuse
3081 // the logic for lowering the masking operations already part of the
3082 // instruction selector.
3083 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3086 assert(N->getOpcode() == ISD::OR &&
3087 "Only OR nodes are supported for CMPB");
3090 if (!PPCSubTarget->hasCMPB())
3093 if (N->getValueType(0) != MVT::i32 &&
3094 N->getValueType(0) != MVT::i64)
3097 EVT VT = N->getValueType(0);
3100 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3101 uint64_t Mask = 0, Alt = 0;
3103 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3104 uint64_t &Mask, uint64_t &Alt,
3105 SDValue &LHS, SDValue &RHS) {
3106 if (O.getOpcode() != ISD::SELECT_CC)
3108 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3110 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3111 !isa<ConstantSDNode>(O.getOperand(3)))
3114 uint64_t PM = O.getConstantOperandVal(2);
3115 uint64_t PAlt = O.getConstantOperandVal(3);
3116 for (b = 0; b < 8; ++b) {
3117 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3118 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3127 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3128 O.getConstantOperandVal(1) != 0) {
3129 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3130 if (Op0.getOpcode() == ISD::TRUNCATE)
3131 Op0 = Op0.getOperand(0);
3132 if (Op1.getOpcode() == ISD::TRUNCATE)
3133 Op1 = Op1.getOperand(0);
3135 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3136 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3137 isa<ConstantSDNode>(Op0.getOperand(1))) {
3139 unsigned Bits = Op0.getValueType().getSizeInBits();
3142 if (Op0.getConstantOperandVal(1) != Bits-8)
3145 LHS = Op0.getOperand(0);
3146 RHS = Op1.getOperand(0);
3150 // When we have small integers (i16 to be specific), the form present
3151 // post-legalization uses SETULT in the SELECT_CC for the
3152 // higher-order byte, depending on the fact that the
3153 // even-higher-order bytes are known to all be zero, for example:
3154 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3155 // (so when the second byte is the same, because all higher-order
3156 // bits from bytes 3 and 4 are known to be zero, the result of the
3157 // xor can be at most 255)
3158 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3159 isa<ConstantSDNode>(O.getOperand(1))) {
3161 uint64_t ULim = O.getConstantOperandVal(1);
3162 if (ULim != (UINT64_C(1) << b*8))
3165 // Now we need to make sure that the upper bytes are known to be
3167 unsigned Bits = Op0.getValueType().getSizeInBits();
3168 if (!CurDAG->MaskedValueIsZero(Op0,
3169 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3172 LHS = Op0.getOperand(0);
3173 RHS = Op0.getOperand(1);
3180 if (CC != ISD::SETEQ)
3183 SDValue Op = O.getOperand(0);
3184 if (Op.getOpcode() == ISD::AND) {
3185 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3187 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3190 SDValue XOR = Op.getOperand(0);
3191 if (XOR.getOpcode() == ISD::TRUNCATE)
3192 XOR = XOR.getOperand(0);
3193 if (XOR.getOpcode() != ISD::XOR)
3196 LHS = XOR.getOperand(0);
3197 RHS = XOR.getOperand(1);
3199 } else if (Op.getOpcode() == ISD::SRL) {
3200 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3202 unsigned Bits = Op.getValueType().getSizeInBits();
3205 if (Op.getConstantOperandVal(1) != Bits-8)
3208 SDValue XOR = Op.getOperand(0);
3209 if (XOR.getOpcode() == ISD::TRUNCATE)
3210 XOR = XOR.getOperand(0);
3211 if (XOR.getOpcode() != ISD::XOR)
3214 LHS = XOR.getOperand(0);
3215 RHS = XOR.getOperand(1);
3222 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3223 while (!Queue.empty()) {
3224 SDValue V = Queue.pop_back_val();
3226 for (const SDValue &O : V.getNode()->ops()) {
3228 uint64_t M = 0, A = 0;
3230 if (O.getOpcode() == ISD::OR) {
3232 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3236 BytesFound[b] = true;
3239 } else if ((LHS == ORHS && RHS == OLHS) ||
3240 (RHS == ORHS && LHS == OLHS)) {
3241 BytesFound[b] = true;
3253 unsigned LastB = 0, BCnt = 0;
3254 for (unsigned i = 0; i < 8; ++i)
3255 if (BytesFound[LastB]) {
3260 if (!LastB || BCnt < 2)
3263 // Because we'll be zero-extending the output anyway if don't have a specific
3264 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3265 if (LHS.getValueType() != VT) {
3266 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3267 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3270 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3272 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3273 if (NonTrivialMask && !Alt) {
3274 // Res = Mask & CMPB
3275 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3276 CurDAG->getConstant(Mask, dl, VT));
3278 // Res = (CMPB & Mask) | (~CMPB & Alt)
3279 // Which, as suggested here:
3280 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3281 // can be written as:
3282 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3283 // useful because the (Alt ^ Mask) can be pre-computed.
3284 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3285 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3286 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3287 CurDAG->getConstant(Alt, dl, VT));
3293 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3294 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3295 // involves constant materialization of a 0 or a 1 or both. If the result of
3296 // the extension is then operated upon by some operator that can be constant
3297 // folded with a constant 0 or 1, and that constant can be materialized using
3298 // only one instruction (like a zero or one), then we should fold in those
3299 // operations with the select.
3300 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3301 if (!PPCSubTarget->useCRBits())
3304 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3305 N->getOpcode() != ISD::SIGN_EXTEND &&
3306 N->getOpcode() != ISD::ANY_EXTEND)
3309 if (N->getOperand(0).getValueType() != MVT::i1)
3312 if (!N->hasOneUse())
3316 EVT VT = N->getValueType(0);
3317 SDValue Cond = N->getOperand(0);
3319 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3320 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3323 SDNode *User = *N->use_begin();
3324 if (User->getNumOperands() != 2)
3327 auto TryFold = [this, N, User, dl](SDValue Val) {
3328 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3329 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3330 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3332 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3333 User->getValueType(0),
3334 O0.getNode(), O1.getNode());
3337 SDValue TrueRes = TryFold(ConstTrue);
3340 SDValue FalseRes = TryFold(ConstFalse);
3344 // For us to materialize these using one instruction, we must be able to
3345 // represent them as signed 16-bit integers.
3346 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3347 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3348 if (!isInt<16>(True) || !isInt<16>(False))
3351 // We can replace User with a new SELECT node, and try again to see if we
3352 // can fold the select with its user.
3353 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3355 ConstTrue = TrueRes;
3356 ConstFalse = FalseRes;
3357 } while (N->hasOneUse());
3360 void PPCDAGToDAGISel::PreprocessISelDAG() {
3361 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3364 bool MadeChange = false;
3365 while (Position != CurDAG->allnodes_begin()) {
3366 SDNode *N = &*--Position;
3371 switch (N->getOpcode()) {
3374 Res = combineToCMPB(N);
3379 foldBoolExts(Res, N);
3382 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3383 DEBUG(N->dump(CurDAG));
3384 DEBUG(dbgs() << "\nNew: ");
3385 DEBUG(Res.getNode()->dump(CurDAG));
3386 DEBUG(dbgs() << "\n");
3388 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3394 CurDAG->RemoveDeadNodes();
3397 /// PostprocessISelDAG - Perform some late peephole optimizations
3398 /// on the DAG representation.
3399 void PPCDAGToDAGISel::PostprocessISelDAG() {
3401 // Skip peepholes at -O0.
3402 if (TM.getOptLevel() == CodeGenOpt::None)
3407 PeepholePPC64ZExt();
3410 // Check if all users of this node will become isel where the second operand
3411 // is the constant zero. If this is so, and if we can negate the condition,
3412 // then we can flip the true and false operands. This will allow the zero to
3413 // be folded with the isel so that we don't need to materialize a register
3415 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3416 // If we're not using isel, then this does not matter.
3417 if (!PPCSubTarget->hasISEL())
3420 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3423 if (!User->isMachineOpcode())
3425 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3426 User->getMachineOpcode() != PPC::SELECT_I8)
3429 SDNode *Op2 = User->getOperand(2).getNode();
3430 if (!Op2->isMachineOpcode())
3433 if (Op2->getMachineOpcode() != PPC::LI &&
3434 Op2->getMachineOpcode() != PPC::LI8)
3437 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3441 if (!C->isNullValue())
3448 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3449 SmallVector<SDNode *, 4> ToReplace;
3450 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3453 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3454 User->getMachineOpcode() == PPC::SELECT_I8) &&
3455 "Must have all select users");
3456 ToReplace.push_back(User);
3459 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3460 UE = ToReplace.end(); UI != UE; ++UI) {
3463 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3464 User->getValueType(0), User->getOperand(0),
3465 User->getOperand(2),
3466 User->getOperand(1));
3468 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3469 DEBUG(User->dump(CurDAG));
3470 DEBUG(dbgs() << "\nNew: ");
3471 DEBUG(ResNode->dump(CurDAG));
3472 DEBUG(dbgs() << "\n");
3474 ReplaceUses(User, ResNode);
3478 void PPCDAGToDAGISel::PeepholeCROps() {
3482 for (SDNode &Node : CurDAG->allnodes()) {
3483 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
3484 if (!MachineNode || MachineNode->use_empty())
3486 SDNode *ResNode = MachineNode;
3488 bool Op1Set = false, Op1Unset = false,
3490 Op2Set = false, Op2Unset = false,
3493 unsigned Opcode = MachineNode->getMachineOpcode();
3504 SDValue Op = MachineNode->getOperand(1);
3505 if (Op.isMachineOpcode()) {
3506 if (Op.getMachineOpcode() == PPC::CRSET)
3508 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3510 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3511 Op.getOperand(0) == Op.getOperand(1))
3517 case PPC::SELECT_I4:
3518 case PPC::SELECT_I8:
3519 case PPC::SELECT_F4:
3520 case PPC::SELECT_F8:
3521 case PPC::SELECT_QFRC:
3522 case PPC::SELECT_QSRC:
3523 case PPC::SELECT_QBRC:
3524 case PPC::SELECT_VRRC:
3525 case PPC::SELECT_VSFRC:
3526 case PPC::SELECT_VSSRC:
3527 case PPC::SELECT_VSRC: {
3528 SDValue Op = MachineNode->getOperand(0);
3529 if (Op.isMachineOpcode()) {
3530 if (Op.getMachineOpcode() == PPC::CRSET)
3532 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3534 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3535 Op.getOperand(0) == Op.getOperand(1))
3542 bool SelectSwap = false;
3546 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3548 ResNode = MachineNode->getOperand(0).getNode();
3551 ResNode = MachineNode->getOperand(1).getNode();
3554 ResNode = MachineNode->getOperand(0).getNode();
3555 else if (Op1Unset || Op2Unset)
3556 // x & 0 = 0 & y = 0
3557 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3560 // ~x & y = andc(y, x)
3561 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3562 MVT::i1, MachineNode->getOperand(1),
3563 MachineNode->getOperand(0).
3566 // x & ~y = andc(x, y)
3567 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3568 MVT::i1, MachineNode->getOperand(0),
3569 MachineNode->getOperand(1).
3571 else if (AllUsersSelectZero(MachineNode))
3572 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3573 MVT::i1, MachineNode->getOperand(0),
3574 MachineNode->getOperand(1)),
3578 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3579 // nand(x, x) -> nor(x, x)
3580 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3581 MVT::i1, MachineNode->getOperand(0),
3582 MachineNode->getOperand(0));
3584 // nand(1, y) -> nor(y, y)
3585 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3586 MVT::i1, MachineNode->getOperand(1),
3587 MachineNode->getOperand(1));
3589 // nand(x, 1) -> nor(x, x)
3590 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3591 MVT::i1, MachineNode->getOperand(0),
3592 MachineNode->getOperand(0));
3593 else if (Op1Unset || Op2Unset)
3594 // nand(x, 0) = nand(0, y) = 1
3595 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3598 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3599 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3600 MVT::i1, MachineNode->getOperand(0).
3602 MachineNode->getOperand(1));
3604 // nand(x, ~y) = ~x | y = orc(y, x)
3605 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3606 MVT::i1, MachineNode->getOperand(1).
3608 MachineNode->getOperand(0));
3609 else if (AllUsersSelectZero(MachineNode))
3610 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3611 MVT::i1, MachineNode->getOperand(0),
3612 MachineNode->getOperand(1)),
3616 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3618 ResNode = MachineNode->getOperand(0).getNode();
3619 else if (Op1Set || Op2Set)
3620 // x | 1 = 1 | y = 1
3621 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3625 ResNode = MachineNode->getOperand(1).getNode();
3628 ResNode = MachineNode->getOperand(0).getNode();
3630 // ~x | y = orc(y, x)
3631 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3632 MVT::i1, MachineNode->getOperand(1),
3633 MachineNode->getOperand(0).
3636 // x | ~y = orc(x, y)
3637 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3638 MVT::i1, MachineNode->getOperand(0),
3639 MachineNode->getOperand(1).
3641 else if (AllUsersSelectZero(MachineNode))
3642 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3643 MVT::i1, MachineNode->getOperand(0),
3644 MachineNode->getOperand(1)),
3648 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3650 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3653 // xor(1, y) -> nor(y, y)
3654 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3655 MVT::i1, MachineNode->getOperand(1),
3656 MachineNode->getOperand(1));
3658 // xor(x, 1) -> nor(x, x)
3659 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3660 MVT::i1, MachineNode->getOperand(0),
3661 MachineNode->getOperand(0));
3664 ResNode = MachineNode->getOperand(1).getNode();
3667 ResNode = MachineNode->getOperand(0).getNode();
3669 // xor(~x, y) = eqv(x, y)
3670 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3671 MVT::i1, MachineNode->getOperand(0).
3673 MachineNode->getOperand(1));
3675 // xor(x, ~y) = eqv(x, y)
3676 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3677 MVT::i1, MachineNode->getOperand(0),
3678 MachineNode->getOperand(1).
3680 else if (AllUsersSelectZero(MachineNode))
3681 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3682 MVT::i1, MachineNode->getOperand(0),
3683 MachineNode->getOperand(1)),
3687 if (Op1Set || Op2Set)
3689 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3692 // nor(0, y) = ~y -> nor(y, y)
3693 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3694 MVT::i1, MachineNode->getOperand(1),
3695 MachineNode->getOperand(1));
3698 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3699 MVT::i1, MachineNode->getOperand(0),
3700 MachineNode->getOperand(0));
3702 // nor(~x, y) = andc(x, y)
3703 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3704 MVT::i1, MachineNode->getOperand(0).
3706 MachineNode->getOperand(1));
3708 // nor(x, ~y) = andc(y, x)
3709 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3710 MVT::i1, MachineNode->getOperand(1).
3712 MachineNode->getOperand(0));
3713 else if (AllUsersSelectZero(MachineNode))
3714 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3715 MVT::i1, MachineNode->getOperand(0),
3716 MachineNode->getOperand(1)),
3720 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3722 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3726 ResNode = MachineNode->getOperand(1).getNode();
3729 ResNode = MachineNode->getOperand(0).getNode();
3731 // eqv(0, y) = ~y -> nor(y, y)
3732 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3733 MVT::i1, MachineNode->getOperand(1),
3734 MachineNode->getOperand(1));
3737 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3738 MVT::i1, MachineNode->getOperand(0),
3739 MachineNode->getOperand(0));
3741 // eqv(~x, y) = xor(x, y)
3742 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3743 MVT::i1, MachineNode->getOperand(0).
3745 MachineNode->getOperand(1));
3747 // eqv(x, ~y) = xor(x, y)
3748 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3749 MVT::i1, MachineNode->getOperand(0),
3750 MachineNode->getOperand(1).
3752 else if (AllUsersSelectZero(MachineNode))
3753 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3754 MVT::i1, MachineNode->getOperand(0),
3755 MachineNode->getOperand(1)),
3759 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3761 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3765 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3766 MVT::i1, MachineNode->getOperand(1),
3767 MachineNode->getOperand(1));
3768 else if (Op1Unset || Op2Set)
3769 // andc(0, y) = andc(x, 1) = 0
3770 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3774 ResNode = MachineNode->getOperand(0).getNode();
3776 // andc(~x, y) = ~(x | y) = nor(x, y)
3777 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3778 MVT::i1, MachineNode->getOperand(0).
3780 MachineNode->getOperand(1));
3782 // andc(x, ~y) = x & y
3783 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3784 MVT::i1, MachineNode->getOperand(0),
3785 MachineNode->getOperand(1).
3787 else if (AllUsersSelectZero(MachineNode))
3788 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3789 MVT::i1, MachineNode->getOperand(1),
3790 MachineNode->getOperand(0)),
3794 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3796 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3798 else if (Op1Set || Op2Unset)
3799 // orc(1, y) = orc(x, 0) = 1
3800 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3804 ResNode = MachineNode->getOperand(0).getNode();
3807 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3808 MVT::i1, MachineNode->getOperand(1),
3809 MachineNode->getOperand(1));
3811 // orc(~x, y) = ~(x & y) = nand(x, y)
3812 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3813 MVT::i1, MachineNode->getOperand(0).
3815 MachineNode->getOperand(1));
3817 // orc(x, ~y) = x | y
3818 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3819 MVT::i1, MachineNode->getOperand(0),
3820 MachineNode->getOperand(1).
3822 else if (AllUsersSelectZero(MachineNode))
3823 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3824 MVT::i1, MachineNode->getOperand(1),
3825 MachineNode->getOperand(0)),
3828 case PPC::SELECT_I4:
3829 case PPC::SELECT_I8:
3830 case PPC::SELECT_F4:
3831 case PPC::SELECT_F8:
3832 case PPC::SELECT_QFRC:
3833 case PPC::SELECT_QSRC:
3834 case PPC::SELECT_QBRC:
3835 case PPC::SELECT_VRRC:
3836 case PPC::SELECT_VSFRC:
3837 case PPC::SELECT_VSSRC:
3838 case PPC::SELECT_VSRC:
3840 ResNode = MachineNode->getOperand(1).getNode();
3842 ResNode = MachineNode->getOperand(2).getNode();
3844 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3846 MachineNode->getValueType(0),
3847 MachineNode->getOperand(0).
3849 MachineNode->getOperand(2),
3850 MachineNode->getOperand(1));
3855 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3859 MachineNode->getOperand(0).
3861 MachineNode->getOperand(1),
3862 MachineNode->getOperand(2));
3863 // FIXME: Handle Op1Set, Op1Unset here too.
3867 // If we're inverting this node because it is used only by selects that
3868 // we'd like to swap, then swap the selects before the node replacement.
3870 SwapAllSelectUsers(MachineNode);
3872 if (ResNode != MachineNode) {
3873 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3874 DEBUG(MachineNode->dump(CurDAG));
3875 DEBUG(dbgs() << "\nNew: ");
3876 DEBUG(ResNode->dump(CurDAG));
3877 DEBUG(dbgs() << "\n");
3879 ReplaceUses(MachineNode, ResNode);
3884 CurDAG->RemoveDeadNodes();
3885 } while (IsModified);
3888 // Gather the set of 32-bit operations that are known to have their
3889 // higher-order 32 bits zero, where ToPromote contains all such operations.
3890 static bool PeepholePPC64ZExtGather(SDValue Op32,
3891 SmallPtrSetImpl<SDNode *> &ToPromote) {
3892 if (!Op32.isMachineOpcode())
3895 // First, check for the "frontier" instructions (those that will clear the
3896 // higher-order 32 bits.
3898 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3899 // around. If it does not, then these instructions will clear the
3900 // higher-order bits.
3901 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3902 Op32.getMachineOpcode() == PPC::RLWNM) &&
3903 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3904 ToPromote.insert(Op32.getNode());
3908 // SLW and SRW always clear the higher-order bits.
3909 if (Op32.getMachineOpcode() == PPC::SLW ||
3910 Op32.getMachineOpcode() == PPC::SRW) {
3911 ToPromote.insert(Op32.getNode());
3915 // For LI and LIS, we need the immediate to be positive (so that it is not
3917 if (Op32.getMachineOpcode() == PPC::LI ||
3918 Op32.getMachineOpcode() == PPC::LIS) {
3919 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3922 ToPromote.insert(Op32.getNode());
3926 // LHBRX and LWBRX always clear the higher-order bits.
3927 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3928 Op32.getMachineOpcode() == PPC::LWBRX) {
3929 ToPromote.insert(Op32.getNode());
3933 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3934 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3935 ToPromote.insert(Op32.getNode());
3939 // Next, check for those instructions we can look through.
3941 // Assuming the mask does not wrap around, then the higher-order bits are
3942 // taken directly from the first operand.
3943 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3944 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3945 SmallPtrSet<SDNode *, 16> ToPromote1;
3946 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3949 ToPromote.insert(Op32.getNode());
3950 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3954 // For OR, the higher-order bits are zero if that is true for both operands.
3955 // For SELECT_I4, the same is true (but the relevant operand numbers are
3957 if (Op32.getMachineOpcode() == PPC::OR ||
3958 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3959 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3960 SmallPtrSet<SDNode *, 16> ToPromote1;
3961 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3963 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3966 ToPromote.insert(Op32.getNode());
3967 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3971 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3972 // zero, and also for the constant to be positive (so that it is not sign
3974 if (Op32.getMachineOpcode() == PPC::ORI ||
3975 Op32.getMachineOpcode() == PPC::ORIS) {
3976 SmallPtrSet<SDNode *, 16> ToPromote1;
3977 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3979 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3982 ToPromote.insert(Op32.getNode());
3983 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3987 // The higher-order bits of AND are zero if that is true for at least one of
3989 if (Op32.getMachineOpcode() == PPC::AND) {
3990 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3992 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3994 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3995 if (!Op0OK && !Op1OK)
3998 ToPromote.insert(Op32.getNode());
4001 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4004 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4009 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4010 // of the first operand, or if the second operand is positive (so that it is
4011 // not sign extended).
4012 if (Op32.getMachineOpcode() == PPC::ANDIo ||
4013 Op32.getMachineOpcode() == PPC::ANDISo) {
4014 SmallPtrSet<SDNode *, 16> ToPromote1;
4016 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4017 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4018 if (!Op0OK && !Op1OK)
4021 ToPromote.insert(Op32.getNode());
4024 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4032 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4033 if (!PPCSubTarget->isPPC64())
4036 // When we zero-extend from i32 to i64, we use a pattern like this:
4037 // def : Pat<(i64 (zext i32:$in)),
4038 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4040 // There are several 32-bit shift/rotate instructions, however, that will
4041 // clear the higher-order bits of their output, rendering the RLDICL
4042 // unnecessary. When that happens, we remove it here, and redefine the
4043 // relevant 32-bit operation to be a 64-bit operation.
4045 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4048 bool MadeChange = false;
4049 while (Position != CurDAG->allnodes_begin()) {
4050 SDNode *N = &*--Position;
4051 // Skip dead nodes and any non-machine opcodes.
4052 if (N->use_empty() || !N->isMachineOpcode())
4055 if (N->getMachineOpcode() != PPC::RLDICL)
4058 if (N->getConstantOperandVal(1) != 0 ||
4059 N->getConstantOperandVal(2) != 32)
4062 SDValue ISR = N->getOperand(0);
4063 if (!ISR.isMachineOpcode() ||
4064 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4067 if (!ISR.hasOneUse())
4070 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4073 SDValue IDef = ISR.getOperand(0);
4074 if (!IDef.isMachineOpcode() ||
4075 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4078 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4079 // can get rid of it.
4081 SDValue Op32 = ISR->getOperand(1);
4082 if (!Op32.isMachineOpcode())
4085 // There are some 32-bit instructions that always clear the high-order 32
4086 // bits, there are also some instructions (like AND) that we can look
4088 SmallPtrSet<SDNode *, 16> ToPromote;
4089 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4092 // If the ToPromote set contains nodes that have uses outside of the set
4093 // (except for the original INSERT_SUBREG), then abort the transformation.
4094 bool OutsideUse = false;
4095 for (SDNode *PN : ToPromote) {
4096 for (SDNode *UN : PN->uses()) {
4097 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4111 // We now know that this zero extension can be removed by promoting to
4112 // nodes in ToPromote to 64-bit operations, where for operations in the
4113 // frontier of the set, we need to insert INSERT_SUBREGs for their
4115 for (SDNode *PN : ToPromote) {
4117 switch (PN->getMachineOpcode()) {
4119 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4120 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4121 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4122 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4123 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4124 case PPC::LI: NewOpcode = PPC::LI8; break;
4125 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4126 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4127 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4128 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4129 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4130 case PPC::OR: NewOpcode = PPC::OR8; break;
4131 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4132 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4133 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4134 case PPC::AND: NewOpcode = PPC::AND8; break;
4135 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4136 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4139 // Note: During the replacement process, the nodes will be in an
4140 // inconsistent state (some instructions will have operands with values
4141 // of the wrong type). Once done, however, everything should be right
4144 SmallVector<SDValue, 4> Ops;
4145 for (const SDValue &V : PN->ops()) {
4146 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4147 !isa<ConstantSDNode>(V)) {
4148 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4150 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4151 ISR.getNode()->getVTList(), ReplOpOps);
4152 Ops.push_back(SDValue(ReplOp, 0));
4158 // Because all to-be-promoted nodes only have users that are other
4159 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4160 // the i32 result value type with i64.
4162 SmallVector<EVT, 2> NewVTs;
4163 SDVTList VTs = PN->getVTList();
4164 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4165 if (VTs.VTs[i] == MVT::i32)
4166 NewVTs.push_back(MVT::i64);
4168 NewVTs.push_back(VTs.VTs[i]);
4170 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4171 DEBUG(PN->dump(CurDAG));
4173 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4175 DEBUG(dbgs() << "\nNew: ");
4176 DEBUG(PN->dump(CurDAG));
4177 DEBUG(dbgs() << "\n");
4180 // Now we replace the original zero extend and its associated INSERT_SUBREG
4181 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4184 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4185 DEBUG(N->dump(CurDAG));
4186 DEBUG(dbgs() << "\nNew: ");
4187 DEBUG(Op32.getNode()->dump(CurDAG));
4188 DEBUG(dbgs() << "\n");
4190 ReplaceUses(N, Op32.getNode());
4194 CurDAG->RemoveDeadNodes();
4197 void PPCDAGToDAGISel::PeepholePPC64() {
4198 // These optimizations are currently supported only for 64-bit SVR4.
4199 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4202 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4205 while (Position != CurDAG->allnodes_begin()) {
4206 SDNode *N = &*--Position;
4207 // Skip dead nodes and any non-machine opcodes.
4208 if (N->use_empty() || !N->isMachineOpcode())
4212 unsigned StorageOpcode = N->getMachineOpcode();
4214 switch (StorageOpcode) {
4245 // If this is a load or store with a zero offset, or within the alignment,
4246 // we may be able to fold an add-immediate into the memory operation.
4247 // The check against alignment is below, as it can't occur until we check
4248 // the arguments to N
4249 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4252 SDValue Base = N->getOperand(FirstOp + 1);
4253 if (!Base.isMachineOpcode())
4256 // On targets with fusion, we don't want this to fire and remove a fusion
4257 // opportunity, unless a) it results in another fusion opportunity or
4258 // b) optimizing for size.
4259 if (PPCSubTarget->hasFusion() &&
4260 (!MF->getFunction()->optForSize() && !Base.hasOneUse()))
4264 bool ReplaceFlags = true;
4266 // When the feeding operation is an add-immediate of some sort,
4267 // determine whether we need to add relocation information to the
4268 // target flags on the immediate operand when we fold it into the
4269 // load instruction.
4271 // For something like ADDItocL, the relocation information is
4272 // inferred from the opcode; when we process it in the AsmPrinter,
4273 // we add the necessary relocation there. A load, though, can receive
4274 // relocation from various flavors of ADDIxxx, so we need to carry
4275 // the relocation information in the target flags.
4276 switch (Base.getMachineOpcode()) {
4281 // In some cases (such as TLS) the relocation information
4282 // is already in place on the operand, so copying the operand
4284 ReplaceFlags = false;
4285 // For these cases, the immediate may not be divisible by 4, in
4286 // which case the fold is illegal for DS-form instructions. (The
4287 // other cases provide aligned addresses and are always safe.)
4288 if ((StorageOpcode == PPC::LWA ||
4289 StorageOpcode == PPC::LD ||
4290 StorageOpcode == PPC::STD) &&
4291 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4292 Base.getConstantOperandVal(1) % 4 != 0))
4295 case PPC::ADDIdtprelL:
4296 Flags = PPCII::MO_DTPREL_LO;
4298 case PPC::ADDItlsldL:
4299 Flags = PPCII::MO_TLSLD_LO;
4302 Flags = PPCII::MO_TOC_LO;
4306 SDValue ImmOpnd = Base.getOperand(1);
4307 int MaxDisplacement = 0;
4308 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4309 const GlobalValue *GV = GA->getGlobal();
4310 MaxDisplacement = GV->getAlignment() - 1;
4313 int Offset = N->getConstantOperandVal(FirstOp);
4314 if (Offset < 0 || Offset > MaxDisplacement)
4317 // We found an opportunity. Reverse the operands from the add
4318 // immediate and substitute them into the load or store. If
4319 // needed, update the target flags for the immediate operand to
4320 // reflect the necessary relocation information.
4321 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4322 DEBUG(Base->dump(CurDAG));
4323 DEBUG(dbgs() << "\nN: ");
4324 DEBUG(N->dump(CurDAG));
4325 DEBUG(dbgs() << "\n");
4327 // If the relocation information isn't already present on the
4328 // immediate operand, add it now.
4330 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4332 const GlobalValue *GV = GA->getGlobal();
4333 // We can't perform this optimization for data whose alignment
4334 // is insufficient for the instruction encoding.
4335 if (GV->getAlignment() < 4 &&
4336 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4337 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
4338 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4341 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
4342 } else if (ConstantPoolSDNode *CP =
4343 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4344 const Constant *C = CP->getConstVal();
4345 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4351 if (FirstOp == 1) // Store
4352 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4353 Base.getOperand(0), N->getOperand(3));
4355 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4358 // The add-immediate may now be dead, in which case remove it.
4359 if (Base.getNode()->use_empty())
4360 CurDAG->RemoveDeadNode(Base.getNode());
4365 /// createPPCISelDag - This pass converts a legalized DAG into a
4366 /// PowerPC-specific DAG, ready for instruction scheduling.
4368 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4369 return new PPCDAGToDAGISel(TM);
4372 static void initializePassOnce(PassRegistry &Registry) {
4373 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4374 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4375 nullptr, false, false);
4376 Registry.registerPass(*PI, true);
4379 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4380 CALL_ONCE_INITIALIZATION(initializePassOnce);