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 return VRI.RLAmt == EffRLAmt;
1618 for (auto &BG : BitGroups) {
1619 if (!MatchingBG(BG))
1622 if (BG.StartIdx <= BG.EndIdx) {
1623 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1624 Mask |= (UINT64_C(1) << i);
1626 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1627 Mask |= (UINT64_C(1) << i);
1628 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1629 Mask |= (UINT64_C(1) << i);
1633 // We can use the 32-bit andi/andis technique if the mask does not
1634 // require any higher-order bits. This can save an instruction compared
1635 // to always using the general 64-bit technique.
1636 bool Use32BitInsts = isUInt<32>(Mask);
1637 // Compute the masks for andi/andis that would be necessary.
1638 unsigned ANDIMask = (Mask & UINT16_MAX),
1639 ANDISMask = (Mask >> 16) & UINT16_MAX;
1641 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1643 unsigned NumAndInsts = (unsigned) NeedsRotate +
1644 (unsigned) (bool) Res;
1646 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1647 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1649 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1651 unsigned NumRLInsts = 0;
1652 bool FirstBG = true;
1653 for (auto &BG : BitGroups) {
1654 if (!MatchingBG(BG))
1657 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1662 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1663 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1664 "\n\t\t\tisel using masking: " << NumAndInsts <<
1665 " using rotates: " << NumRLInsts << "\n");
1667 // When we'd use andi/andis, we bias toward using the rotates (andi only
1668 // has a record form, and is cracked on POWER cores). However, when using
1669 // general 64-bit constant formation, bias toward the constant form,
1670 // because that exposes more opportunities for CSE.
1671 if (NumAndInsts > NumRLInsts)
1673 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1676 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1678 if (InstCnt) *InstCnt += NumAndInsts;
1681 // We actually need to generate a rotation if we have a non-zero rotation
1682 // factor or, in the Repl32 case, if we care about any of the
1683 // higher-order replicated bits. In the latter case, we generate a mask
1684 // backward so that it actually includes the entire 64 bits.
1685 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1686 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1687 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1692 if (Use32BitInsts) {
1693 assert((ANDIMask != 0 || ANDISMask != 0) &&
1694 "No set bits in mask when using 32-bit ands for 64-bit value");
1696 SDValue ANDIVal, ANDISVal;
1698 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1699 VRot, getI32Imm(ANDIMask, dl)), 0);
1701 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1702 VRot, getI32Imm(ANDISMask, dl)), 0);
1705 TotalVal = ANDISVal;
1709 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1710 ANDIVal, ANDISVal), 0);
1712 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1714 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1715 VRot, TotalVal), 0);
1721 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1724 // Now, remove all groups with this underlying value and rotation
1726 eraseMatchingBitGroups(MatchingBG);
1730 // Instruction selection for the 64-bit case.
1731 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1735 if (InstCnt) *InstCnt = 0;
1737 // Take care of cases that should use andi/andis first.
1738 SelectAndParts64(dl, Res, InstCnt);
1740 // If we've not yet selected a 'starting' instruction, and we have no zeros
1741 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1742 // number of groups), and start with this rotated value.
1743 if ((!HasZeros || LateMask) && !Res) {
1744 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1745 // groups will come first, and so the VRI representing the largest number
1746 // of groups might not be first (it might be the first Repl32 groups).
1747 unsigned MaxGroupsIdx = 0;
1748 if (!ValueRotsVec[0].Repl32) {
1749 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1750 if (ValueRotsVec[i].Repl32) {
1751 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1757 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1758 bool NeedsRotate = false;
1761 } else if (VRI.Repl32) {
1762 for (auto &BG : BitGroups) {
1763 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1764 BG.Repl32 != VRI.Repl32)
1767 // We don't need a rotate if the bit group is confined to the lower
1769 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1778 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1779 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1784 // Now, remove all groups with this underlying value and rotation factor.
1786 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1787 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1788 BG.Repl32 == VRI.Repl32;
1792 // Because 64-bit rotates are more flexible than inserts, we might have a
1793 // preference regarding which one we do first (to save one instruction).
1795 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1796 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1798 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1800 if (I != BitGroups.begin()) {
1803 BitGroups.insert(BitGroups.begin(), BG);
1810 // Insert the other groups (one at a time).
1811 for (auto &BG : BitGroups) {
1813 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1814 BG.EndIdx, InstCnt);
1816 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1817 BG.StartIdx, BG.EndIdx, InstCnt);
1821 uint64_t Mask = getZerosMask();
1823 // We can use the 32-bit andi/andis technique if the mask does not
1824 // require any higher-order bits. This can save an instruction compared
1825 // to always using the general 64-bit technique.
1826 bool Use32BitInsts = isUInt<32>(Mask);
1827 // Compute the masks for andi/andis that would be necessary.
1828 unsigned ANDIMask = (Mask & UINT16_MAX),
1829 ANDISMask = (Mask >> 16) & UINT16_MAX;
1831 if (Use32BitInsts) {
1832 assert((ANDIMask != 0 || ANDISMask != 0) &&
1833 "No set bits in mask when using 32-bit ands for 64-bit value");
1835 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1836 (unsigned) (ANDISMask != 0) +
1837 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1839 SDValue ANDIVal, ANDISVal;
1841 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1842 Res, getI32Imm(ANDIMask, dl)), 0);
1844 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1845 Res, getI32Imm(ANDISMask, dl)), 0);
1852 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1853 ANDIVal, ANDISVal), 0);
1855 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1857 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1859 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1864 return Res.getNode();
1867 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1868 // Fill in BitGroups.
1869 collectBitGroups(LateMask);
1870 if (BitGroups.empty())
1873 // For 64-bit values, figure out when we can use 32-bit instructions.
1874 if (Bits.size() == 64)
1875 assignRepl32BitGroups();
1877 // Fill in ValueRotsVec.
1878 collectValueRotInfo();
1880 if (Bits.size() == 32) {
1881 return Select32(N, LateMask, InstCnt);
1883 assert(Bits.size() == 64 && "Not 64 bits here?");
1884 return Select64(N, LateMask, InstCnt);
1890 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1891 BitGroups.erase(std::remove_if(BitGroups.begin(), BitGroups.end(), F),
1895 SmallVector<ValueBit, 64> Bits;
1898 SmallVector<unsigned, 64> RLAmt;
1900 SmallVector<BitGroup, 16> BitGroups;
1902 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1903 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1905 SelectionDAG *CurDAG;
1908 BitPermutationSelector(SelectionDAG *DAG)
1911 // Here we try to match complex bit permutations into a set of
1912 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1913 // known to produce optimial code for common cases (like i32 byte swapping).
1914 SDNode *Select(SDNode *N) {
1915 Bits.resize(N->getValueType(0).getSizeInBits());
1916 if (!getValueBits(SDValue(N, 0), Bits))
1919 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1920 " selection for: ");
1921 DEBUG(N->dump(CurDAG));
1923 // Fill it RLAmt and set HasZeros.
1924 computeRotationAmounts();
1927 return Select(N, false);
1929 // We currently have two techniques for handling results with zeros: early
1930 // masking (the default) and late masking. Late masking is sometimes more
1931 // efficient, but because the structure of the bit groups is different, it
1932 // is hard to tell without generating both and comparing the results. With
1933 // late masking, we ignore zeros in the resulting value when inserting each
1934 // set of bit groups, and then mask in the zeros at the end. With early
1935 // masking, we only insert the non-zero parts of the result at every step.
1937 unsigned InstCnt, InstCntLateMask;
1938 DEBUG(dbgs() << "\tEarly masking:\n");
1939 SDNode *RN = Select(N, false, &InstCnt);
1940 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1942 DEBUG(dbgs() << "\tLate masking:\n");
1943 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1944 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1947 if (InstCnt <= InstCntLateMask) {
1948 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1952 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1956 } // anonymous namespace
1958 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1959 if (N->getValueType(0) != MVT::i32 &&
1960 N->getValueType(0) != MVT::i64)
1963 if (!UseBitPermRewriter)
1966 switch (N->getOpcode()) {
1973 BitPermutationSelector BPS(CurDAG);
1974 return BPS.Select(N);
1981 /// SelectCC - Select a comparison of the specified values with the specified
1982 /// condition code, returning the CR# of the expression.
1983 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1984 ISD::CondCode CC, SDLoc dl) {
1985 // Always select the LHS.
1988 if (LHS.getValueType() == MVT::i32) {
1990 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1991 if (isInt32Immediate(RHS, Imm)) {
1992 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1993 if (isUInt<16>(Imm))
1994 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1995 getI32Imm(Imm & 0xFFFF, dl)),
1997 // If this is a 16-bit signed immediate, fold it.
1998 if (isInt<16>((int)Imm))
1999 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2000 getI32Imm(Imm & 0xFFFF, dl)),
2003 // For non-equality comparisons, the default code would materialize the
2004 // constant, then compare against it, like this:
2006 // ori r2, r2, 22136
2008 // Since we are just comparing for equality, we can emit this instead:
2009 // xoris r0,r3,0x1234
2010 // cmplwi cr0,r0,0x5678
2012 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2013 getI32Imm(Imm >> 16, dl)), 0);
2014 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2015 getI32Imm(Imm & 0xFFFF, dl)), 0);
2018 } else if (ISD::isUnsignedIntSetCC(CC)) {
2019 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2020 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2021 getI32Imm(Imm & 0xFFFF, dl)), 0);
2025 if (isIntS16Immediate(RHS, SImm))
2026 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2027 getI32Imm((int)SImm & 0xFFFF,
2032 } else if (LHS.getValueType() == MVT::i64) {
2034 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2035 if (isInt64Immediate(RHS.getNode(), Imm)) {
2036 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2037 if (isUInt<16>(Imm))
2038 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2039 getI32Imm(Imm & 0xFFFF, dl)),
2041 // If this is a 16-bit signed immediate, fold it.
2043 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2044 getI32Imm(Imm & 0xFFFF, dl)),
2047 // For non-equality comparisons, the default code would materialize the
2048 // constant, then compare against it, like this:
2050 // ori r2, r2, 22136
2052 // Since we are just comparing for equality, we can emit this instead:
2053 // xoris r0,r3,0x1234
2054 // cmpldi cr0,r0,0x5678
2056 if (isUInt<32>(Imm)) {
2057 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2058 getI64Imm(Imm >> 16, dl)), 0);
2059 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2060 getI64Imm(Imm & 0xFFFF, dl)),
2065 } else if (ISD::isUnsignedIntSetCC(CC)) {
2066 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2067 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2068 getI64Imm(Imm & 0xFFFF, dl)), 0);
2072 if (isIntS16Immediate(RHS, SImm))
2073 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2074 getI64Imm(SImm & 0xFFFF, dl)),
2078 } else if (LHS.getValueType() == MVT::f32) {
2081 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2082 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2084 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2087 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2093 llvm_unreachable("Should be lowered by legalize!");
2094 default: llvm_unreachable("Unknown condition!");
2096 case ISD::SETEQ: return PPC::PRED_EQ;
2098 case ISD::SETNE: return PPC::PRED_NE;
2100 case ISD::SETLT: return PPC::PRED_LT;
2102 case ISD::SETLE: return PPC::PRED_LE;
2104 case ISD::SETGT: return PPC::PRED_GT;
2106 case ISD::SETGE: return PPC::PRED_GE;
2107 case ISD::SETO: return PPC::PRED_NU;
2108 case ISD::SETUO: return PPC::PRED_UN;
2109 // These two are invalid for floating point. Assume we have int.
2110 case ISD::SETULT: return PPC::PRED_LT;
2111 case ISD::SETUGT: return PPC::PRED_GT;
2115 /// getCRIdxForSetCC - Return the index of the condition register field
2116 /// associated with the SetCC condition, and whether or not the field is
2117 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2118 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2121 default: llvm_unreachable("Unknown condition!");
2123 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2125 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2127 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2128 case ISD::SETUO: return 3; // Bit #3 = SETUO
2130 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2132 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2134 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2135 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2140 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2141 // These are invalid for floating point. Assume integer.
2142 case ISD::SETULT: return 0;
2143 case ISD::SETUGT: return 1;
2147 // getVCmpInst: return the vector compare instruction for the specified
2148 // vector type and condition code. Since this is for altivec specific code,
2149 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2150 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2151 bool HasVSX, bool &Swap, bool &Negate) {
2155 if (VecVT.isFloatingPoint()) {
2156 /* Handle some cases by swapping input operands. */
2158 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2159 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2160 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2161 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2162 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2163 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2166 /* Handle some cases by negating the result. */
2168 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2169 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2170 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2171 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2174 /* We have instructions implementing the remaining cases. */
2178 if (VecVT == MVT::v4f32)
2179 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2180 else if (VecVT == MVT::v2f64)
2181 return PPC::XVCMPEQDP;
2185 if (VecVT == MVT::v4f32)
2186 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2187 else if (VecVT == MVT::v2f64)
2188 return PPC::XVCMPGTDP;
2192 if (VecVT == MVT::v4f32)
2193 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2194 else if (VecVT == MVT::v2f64)
2195 return PPC::XVCMPGEDP;
2200 llvm_unreachable("Invalid floating-point vector compare condition");
2202 /* Handle some cases by swapping input operands. */
2204 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2205 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2206 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2207 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2210 /* Handle some cases by negating the result. */
2212 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2213 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2214 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2215 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2218 /* We have instructions implementing the remaining cases. */
2222 if (VecVT == MVT::v16i8)
2223 return PPC::VCMPEQUB;
2224 else if (VecVT == MVT::v8i16)
2225 return PPC::VCMPEQUH;
2226 else if (VecVT == MVT::v4i32)
2227 return PPC::VCMPEQUW;
2228 else if (VecVT == MVT::v2i64)
2229 return PPC::VCMPEQUD;
2232 if (VecVT == MVT::v16i8)
2233 return PPC::VCMPGTSB;
2234 else if (VecVT == MVT::v8i16)
2235 return PPC::VCMPGTSH;
2236 else if (VecVT == MVT::v4i32)
2237 return PPC::VCMPGTSW;
2238 else if (VecVT == MVT::v2i64)
2239 return PPC::VCMPGTSD;
2242 if (VecVT == MVT::v16i8)
2243 return PPC::VCMPGTUB;
2244 else if (VecVT == MVT::v8i16)
2245 return PPC::VCMPGTUH;
2246 else if (VecVT == MVT::v4i32)
2247 return PPC::VCMPGTUW;
2248 else if (VecVT == MVT::v2i64)
2249 return PPC::VCMPGTUD;
2254 llvm_unreachable("Invalid integer vector compare condition");
2258 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2261 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2263 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2264 bool isPPC64 = (PtrVT == MVT::i64);
2266 if (!PPCSubTarget->useCRBits() &&
2267 isInt32Immediate(N->getOperand(1), Imm)) {
2268 // We can codegen setcc op, imm very efficiently compared to a brcond.
2269 // Check for those cases here.
2272 SDValue Op = N->getOperand(0);
2276 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2277 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2278 getI32Imm(31, dl) };
2279 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2284 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2285 Op, getI32Imm(~0U, dl)), 0);
2286 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2290 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2291 getI32Imm(31, dl) };
2292 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2296 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2297 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2298 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2299 getI32Imm(31, dl) };
2300 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2303 } else if (Imm == ~0U) { // setcc op, -1
2304 SDValue Op = N->getOperand(0);
2309 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2310 Op, getI32Imm(1, dl)), 0);
2311 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2312 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2315 0), Op.getValue(1));
2318 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2319 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2320 Op, getI32Imm(~0U, dl));
2321 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2322 Op, SDValue(AD, 1));
2325 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2326 getI32Imm(1, dl)), 0);
2327 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2329 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2330 getI32Imm(31, dl) };
2331 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2334 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2335 getI32Imm(31, dl) };
2336 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2337 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2344 SDValue LHS = N->getOperand(0);
2345 SDValue RHS = N->getOperand(1);
2347 // Altivec Vector compare instructions do not set any CR register by default and
2348 // vector compare operations return the same type as the operands.
2349 if (LHS.getValueType().isVector()) {
2350 if (PPCSubTarget->hasQPX())
2353 EVT VecVT = LHS.getValueType();
2355 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2356 PPCSubTarget->hasVSX(), Swap, Negate);
2358 std::swap(LHS, RHS);
2360 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2362 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2363 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2368 return CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2371 if (PPCSubTarget->useCRBits())
2375 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2376 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2379 // Force the ccreg into CR7.
2380 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2382 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2383 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2384 InFlag).getValue(1);
2386 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2389 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2390 getI32Imm(31, dl), getI32Imm(31, dl) };
2392 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2394 // Get the specified bit.
2396 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2397 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2400 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2401 // Transfer memoperands.
2402 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2403 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2404 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2409 // Select - Convert the specified operand from a target-independent to a
2410 // target-specific node if it hasn't already been changed.
2411 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2413 if (N->isMachineOpcode()) {
2415 return nullptr; // Already selected.
2418 // In case any misguided DAG-level optimizations form an ADD with a
2419 // TargetConstant operand, crash here instead of miscompiling (by selecting
2420 // an r+r add instead of some kind of r+i add).
2421 if (N->getOpcode() == ISD::ADD &&
2422 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2423 llvm_unreachable("Invalid ADD with TargetConstant operand");
2425 // Try matching complex bit permutations before doing anything else.
2426 if (SDNode *NN = SelectBitPermutation(N))
2429 switch (N->getOpcode()) {
2432 case ISD::Constant: {
2433 if (N->getValueType(0) == MVT::i64)
2434 return SelectInt64(CurDAG, N);
2439 SDNode *SN = SelectSETCC(N);
2444 case PPCISD::GlobalBaseReg:
2445 return getGlobalBaseReg();
2447 case ISD::FrameIndex:
2448 return getFrameIndex(N, N);
2450 case PPCISD::MFOCRF: {
2451 SDValue InFlag = N->getOperand(1);
2452 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2453 N->getOperand(0), InFlag);
2456 case PPCISD::READ_TIME_BASE: {
2457 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2458 MVT::Other, N->getOperand(0));
2461 case PPCISD::SRA_ADDZE: {
2462 SDValue N0 = N->getOperand(0);
2464 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2465 getConstantIntValue(), dl,
2466 N->getValueType(0));
2467 if (N->getValueType(0) == MVT::i64) {
2469 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2471 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2472 SDValue(Op, 0), SDValue(Op, 1));
2474 assert(N->getValueType(0) == MVT::i32 &&
2475 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2477 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2479 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2480 SDValue(Op, 0), SDValue(Op, 1));
2485 // Handle preincrement loads.
2486 LoadSDNode *LD = cast<LoadSDNode>(N);
2487 EVT LoadedVT = LD->getMemoryVT();
2489 // Normal loads are handled by code generated from the .td file.
2490 if (LD->getAddressingMode() != ISD::PRE_INC)
2493 SDValue Offset = LD->getOffset();
2494 if (Offset.getOpcode() == ISD::TargetConstant ||
2495 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2498 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2499 if (LD->getValueType(0) != MVT::i64) {
2500 // Handle PPC32 integer and normal FP loads.
2501 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2502 switch (LoadedVT.getSimpleVT().SimpleTy) {
2503 default: llvm_unreachable("Invalid PPC load type!");
2504 case MVT::f64: Opcode = PPC::LFDU; break;
2505 case MVT::f32: Opcode = PPC::LFSU; break;
2506 case MVT::i32: Opcode = PPC::LWZU; break;
2507 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2509 case MVT::i8: Opcode = PPC::LBZU; break;
2512 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2513 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2514 switch (LoadedVT.getSimpleVT().SimpleTy) {
2515 default: llvm_unreachable("Invalid PPC load type!");
2516 case MVT::i64: Opcode = PPC::LDU; break;
2517 case MVT::i32: Opcode = PPC::LWZU8; break;
2518 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2520 case MVT::i8: Opcode = PPC::LBZU8; break;
2524 SDValue Chain = LD->getChain();
2525 SDValue Base = LD->getBasePtr();
2526 SDValue Ops[] = { Offset, Base, Chain };
2527 return transferMemOperands(
2528 N, CurDAG->getMachineNode(
2529 Opcode, dl, LD->getValueType(0),
2530 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other,
2534 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2535 if (LD->getValueType(0) != MVT::i64) {
2536 // Handle PPC32 integer and normal FP loads.
2537 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2538 switch (LoadedVT.getSimpleVT().SimpleTy) {
2539 default: llvm_unreachable("Invalid PPC load type!");
2540 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2541 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2542 case MVT::f64: Opcode = PPC::LFDUX; break;
2543 case MVT::f32: Opcode = PPC::LFSUX; break;
2544 case MVT::i32: Opcode = PPC::LWZUX; break;
2545 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2547 case MVT::i8: Opcode = PPC::LBZUX; break;
2550 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2551 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2552 "Invalid sext update load");
2553 switch (LoadedVT.getSimpleVT().SimpleTy) {
2554 default: llvm_unreachable("Invalid PPC load type!");
2555 case MVT::i64: Opcode = PPC::LDUX; break;
2556 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2557 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2559 case MVT::i8: Opcode = PPC::LBZUX8; break;
2563 SDValue Chain = LD->getChain();
2564 SDValue Base = LD->getBasePtr();
2565 SDValue Ops[] = { Base, Offset, Chain };
2566 return transferMemOperands(
2567 N, CurDAG->getMachineNode(
2568 Opcode, dl, LD->getValueType(0),
2569 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other,
2575 unsigned Imm, Imm2, SH, MB, ME;
2578 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2579 // with a mask, emit rlwinm
2580 if (isInt32Immediate(N->getOperand(1), Imm) &&
2581 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2582 SDValue Val = N->getOperand(0).getOperand(0);
2583 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2584 getI32Imm(ME, dl) };
2585 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2587 // If this is just a masked value where the input is not handled above, and
2588 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2589 if (isInt32Immediate(N->getOperand(1), Imm) &&
2590 isRunOfOnes(Imm, MB, ME) &&
2591 N->getOperand(0).getOpcode() != ISD::ROTL) {
2592 SDValue Val = N->getOperand(0);
2593 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2594 getI32Imm(ME, dl) };
2595 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2597 // If this is a 64-bit zero-extension mask, emit rldicl.
2598 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2600 SDValue Val = N->getOperand(0);
2601 MB = 64 - countTrailingOnes(Imm64);
2604 // If the operand is a logical right shift, we can fold it into this
2605 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2606 // for n <= mb. The right shift is really a left rotate followed by a
2607 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2609 if (Val.getOpcode() == ISD::SRL &&
2610 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2611 assert(Imm < 64 && "Illegal shift amount");
2612 Val = Val.getOperand(0);
2616 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2617 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2619 // AND X, 0 -> 0, not "rlwinm 32".
2620 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2621 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2624 // ISD::OR doesn't get all the bitfield insertion fun.
2625 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
2627 if (isInt32Immediate(N->getOperand(1), Imm) &&
2628 N->getOperand(0).getOpcode() == ISD::OR &&
2629 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2630 // The idea here is to check whether this is equivalent to:
2631 // (c1 & m) | (x & ~m)
2632 // where m is a run-of-ones mask. The logic here is that, for each bit in
2634 // - if both are 1, then the output will be 1.
2635 // - if both are 0, then the output will be 0.
2636 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
2638 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
2640 // If that last condition is never the case, then we can form m from the
2641 // bits that are the same between c1 and c2.
2643 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
2644 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2645 N->getOperand(0).getOperand(1),
2646 getI32Imm(0, dl), getI32Imm(MB, dl),
2647 getI32Imm(ME, dl) };
2648 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2652 // Other cases are autogenerated.
2656 if (N->getValueType(0) == MVT::i32)
2657 if (SDNode *I = SelectBitfieldInsert(N))
2661 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2662 isIntS16Immediate(N->getOperand(1), Imm)) {
2663 APInt LHSKnownZero, LHSKnownOne;
2664 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2666 // If this is equivalent to an add, then we can fold it with the
2667 // FrameIndex calculation.
2668 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2669 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2672 // Other cases are autogenerated.
2677 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2678 isIntS16Immediate(N->getOperand(1), Imm))
2679 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2684 unsigned Imm, SH, MB, ME;
2685 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2686 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2687 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2688 getI32Imm(SH, dl), getI32Imm(MB, dl),
2689 getI32Imm(ME, dl) };
2690 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2693 // Other cases are autogenerated.
2697 unsigned Imm, SH, MB, ME;
2698 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2699 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2700 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2701 getI32Imm(SH, dl), getI32Imm(MB, dl),
2702 getI32Imm(ME, dl) };
2703 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2706 // Other cases are autogenerated.
2709 // FIXME: Remove this once the ANDI glue bug is fixed:
2710 case PPCISD::ANDIo_1_EQ_BIT:
2711 case PPCISD::ANDIo_1_GT_BIT: {
2715 EVT InVT = N->getOperand(0).getValueType();
2716 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2717 "Invalid input type for ANDIo_1_EQ_BIT");
2719 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2720 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2722 CurDAG->getTargetConstant(1, dl, InVT)),
2724 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2726 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2727 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2729 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2731 SDValue(AndI.getNode(), 1) /* glue */);
2733 case ISD::SELECT_CC: {
2734 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2736 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2737 bool isPPC64 = (PtrVT == MVT::i64);
2739 // If this is a select of i1 operands, we'll pattern match it.
2740 if (PPCSubTarget->useCRBits() &&
2741 N->getOperand(0).getValueType() == MVT::i1)
2744 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2746 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2747 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2748 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2749 if (N1C->isNullValue() && N3C->isNullValue() &&
2750 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2751 // FIXME: Implement this optzn for PPC64.
2752 N->getValueType(0) == MVT::i32) {
2754 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2755 N->getOperand(0), getI32Imm(~0U, dl));
2756 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2757 SDValue(Tmp, 0), N->getOperand(0),
2761 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2763 if (N->getValueType(0) == MVT::i1) {
2764 // An i1 select is: (c & t) | (!c & f).
2766 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2770 default: llvm_unreachable("Invalid CC index");
2771 case 0: SRI = PPC::sub_lt; break;
2772 case 1: SRI = PPC::sub_gt; break;
2773 case 2: SRI = PPC::sub_eq; break;
2774 case 3: SRI = PPC::sub_un; break;
2777 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2779 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2781 SDValue C = Inv ? NotCCBit : CCBit,
2782 NotC = Inv ? CCBit : NotCCBit;
2784 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2785 C, N->getOperand(2)), 0);
2786 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2787 NotC, N->getOperand(3)), 0);
2789 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2792 unsigned BROpc = getPredicateForSetCC(CC);
2794 unsigned SelectCCOp;
2795 if (N->getValueType(0) == MVT::i32)
2796 SelectCCOp = PPC::SELECT_CC_I4;
2797 else if (N->getValueType(0) == MVT::i64)
2798 SelectCCOp = PPC::SELECT_CC_I8;
2799 else if (N->getValueType(0) == MVT::f32)
2800 if (PPCSubTarget->hasP8Vector())
2801 SelectCCOp = PPC::SELECT_CC_VSSRC;
2803 SelectCCOp = PPC::SELECT_CC_F4;
2804 else if (N->getValueType(0) == MVT::f64)
2805 if (PPCSubTarget->hasVSX())
2806 SelectCCOp = PPC::SELECT_CC_VSFRC;
2808 SelectCCOp = PPC::SELECT_CC_F8;
2809 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2810 SelectCCOp = PPC::SELECT_CC_QFRC;
2811 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2812 SelectCCOp = PPC::SELECT_CC_QSRC;
2813 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2814 SelectCCOp = PPC::SELECT_CC_QBRC;
2815 else if (N->getValueType(0) == MVT::v2f64 ||
2816 N->getValueType(0) == MVT::v2i64)
2817 SelectCCOp = PPC::SELECT_CC_VSRC;
2819 SelectCCOp = PPC::SELECT_CC_VRRC;
2821 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2822 getI32Imm(BROpc, dl) };
2823 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2826 if (PPCSubTarget->hasVSX()) {
2827 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2828 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2832 case ISD::VECTOR_SHUFFLE:
2833 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2834 N->getValueType(0) == MVT::v2i64)) {
2835 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2837 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2838 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2841 for (int i = 0; i < 2; ++i)
2842 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2847 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2848 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2849 isa<LoadSDNode>(Op1.getOperand(0))) {
2850 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2851 SDValue Base, Offset;
2853 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
2854 (LD->getMemoryVT() == MVT::f64 ||
2855 LD->getMemoryVT() == MVT::i64) &&
2856 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2857 SDValue Chain = LD->getChain();
2858 SDValue Ops[] = { Base, Offset, Chain };
2859 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2860 N->getValueType(0), Ops);
2864 // For little endian, we must swap the input operands and adjust
2865 // the mask elements (reverse and invert them).
2866 if (PPCSubTarget->isLittleEndian()) {
2867 std::swap(Op1, Op2);
2868 unsigned tmp = DM[0];
2873 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
2875 SDValue Ops[] = { Op1, Op2, DMV };
2876 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2882 bool IsPPC64 = PPCSubTarget->isPPC64();
2883 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2884 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2885 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2886 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2889 case PPCISD::COND_BRANCH: {
2890 // Op #0 is the Chain.
2891 // Op #1 is the PPC::PRED_* number.
2893 // Op #3 is the Dest MBB
2894 // Op #4 is the Flag.
2895 // Prevent PPC::PRED_* from being selected into LI.
2896 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2897 if (EnableBranchHint)
2898 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
2900 SDValue Pred = getI32Imm(PCC, dl);
2901 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2902 N->getOperand(0), N->getOperand(4) };
2903 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2906 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2907 unsigned PCC = getPredicateForSetCC(CC);
2909 if (N->getOperand(2).getValueType() == MVT::i1) {
2913 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2914 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2915 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2916 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2917 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2918 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2919 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2922 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2923 N->getOperand(Swap ? 3 : 2),
2924 N->getOperand(Swap ? 2 : 3)), 0);
2925 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2926 BitComp, N->getOperand(4), N->getOperand(0));
2929 if (EnableBranchHint)
2930 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
2932 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2933 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
2934 N->getOperand(4), N->getOperand(0) };
2935 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2938 // FIXME: Should custom lower this.
2939 SDValue Chain = N->getOperand(0);
2940 SDValue Target = N->getOperand(1);
2941 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2942 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2943 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2945 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2947 case PPCISD::TOC_ENTRY: {
2948 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2949 "Only supported for 64-bit ABI and 32-bit SVR4");
2950 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2951 SDValue GA = N->getOperand(0);
2952 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2953 MVT::i32, GA, N->getOperand(1)));
2956 // For medium and large code model, we generate two instructions as
2957 // described below. Otherwise we allow SelectCodeCommon to handle this,
2958 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2959 CodeModel::Model CModel = TM.getCodeModel();
2960 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2963 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2964 // If it must be toc-referenced according to PPCSubTarget, we generate:
2965 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2966 // Otherwise we generate:
2967 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2968 SDValue GA = N->getOperand(0);
2969 SDValue TOCbase = N->getOperand(1);
2970 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2973 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2974 CModel == CodeModel::Large)
2975 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2976 MVT::i64, GA, SDValue(Tmp, 0)));
2978 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2979 const GlobalValue *GV = G->getGlobal();
2980 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
2981 if (GVFlags & PPCII::MO_NLP_FLAG) {
2982 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2983 MVT::i64, GA, SDValue(Tmp, 0)));
2987 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2988 SDValue(Tmp, 0), GA);
2990 case PPCISD::PPC32_PICGOT: {
2991 // Generate a PIC-safe GOT reference.
2992 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2993 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2994 return CurDAG->SelectNodeTo(
2995 N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(CurDAG->getDataLayout()),
2998 case PPCISD::VADD_SPLAT: {
2999 // This expands into one of three sequences, depending on whether
3000 // the first operand is odd or even, positive or negative.
3001 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3002 isa<ConstantSDNode>(N->getOperand(1)) &&
3003 "Invalid operand on VADD_SPLAT!");
3005 int Elt = N->getConstantOperandVal(0);
3006 int EltSize = N->getConstantOperandVal(1);
3007 unsigned Opc1, Opc2, Opc3;
3011 Opc1 = PPC::VSPLTISB;
3012 Opc2 = PPC::VADDUBM;
3013 Opc3 = PPC::VSUBUBM;
3015 } else if (EltSize == 2) {
3016 Opc1 = PPC::VSPLTISH;
3017 Opc2 = PPC::VADDUHM;
3018 Opc3 = PPC::VSUBUHM;
3021 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3022 Opc1 = PPC::VSPLTISW;
3023 Opc2 = PPC::VADDUWM;
3024 Opc3 = PPC::VSUBUWM;
3028 if ((Elt & 1) == 0) {
3029 // Elt is even, in the range [-32,-18] + [16,30].
3031 // Convert: VADD_SPLAT elt, size
3032 // Into: tmp = VSPLTIS[BHW] elt
3033 // VADDU[BHW]M tmp, tmp
3034 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
3035 SDValue EltVal = getI32Imm(Elt >> 1, dl);
3036 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3037 SDValue TmpVal = SDValue(Tmp, 0);
3038 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
3040 } else if (Elt > 0) {
3041 // Elt is odd and positive, in the range [17,31].
3043 // Convert: VADD_SPLAT elt, size
3044 // Into: tmp1 = VSPLTIS[BHW] elt-16
3045 // tmp2 = VSPLTIS[BHW] -16
3046 // VSUBU[BHW]M tmp1, tmp2
3047 SDValue EltVal = getI32Imm(Elt - 16, dl);
3048 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3049 EltVal = getI32Imm(-16, dl);
3050 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3051 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3055 // Elt is odd and negative, in the range [-31,-17].
3057 // Convert: VADD_SPLAT elt, size
3058 // Into: tmp1 = VSPLTIS[BHW] elt+16
3059 // tmp2 = VSPLTIS[BHW] -16
3060 // VADDU[BHW]M tmp1, tmp2
3061 SDValue EltVal = getI32Imm(Elt + 16, dl);
3062 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3063 EltVal = getI32Imm(-16, dl);
3064 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3065 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3071 return SelectCode(N);
3074 // If the target supports the cmpb instruction, do the idiom recognition here.
3075 // We don't do this as a DAG combine because we don't want to do it as nodes
3076 // are being combined (because we might miss part of the eventual idiom). We
3077 // don't want to do it during instruction selection because we want to reuse
3078 // the logic for lowering the masking operations already part of the
3079 // instruction selector.
3080 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3083 assert(N->getOpcode() == ISD::OR &&
3084 "Only OR nodes are supported for CMPB");
3087 if (!PPCSubTarget->hasCMPB())
3090 if (N->getValueType(0) != MVT::i32 &&
3091 N->getValueType(0) != MVT::i64)
3094 EVT VT = N->getValueType(0);
3097 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3098 uint64_t Mask = 0, Alt = 0;
3100 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3101 uint64_t &Mask, uint64_t &Alt,
3102 SDValue &LHS, SDValue &RHS) {
3103 if (O.getOpcode() != ISD::SELECT_CC)
3105 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3107 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3108 !isa<ConstantSDNode>(O.getOperand(3)))
3111 uint64_t PM = O.getConstantOperandVal(2);
3112 uint64_t PAlt = O.getConstantOperandVal(3);
3113 for (b = 0; b < 8; ++b) {
3114 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3115 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3124 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3125 O.getConstantOperandVal(1) != 0) {
3126 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3127 if (Op0.getOpcode() == ISD::TRUNCATE)
3128 Op0 = Op0.getOperand(0);
3129 if (Op1.getOpcode() == ISD::TRUNCATE)
3130 Op1 = Op1.getOperand(0);
3132 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3133 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3134 isa<ConstantSDNode>(Op0.getOperand(1))) {
3136 unsigned Bits = Op0.getValueType().getSizeInBits();
3139 if (Op0.getConstantOperandVal(1) != Bits-8)
3142 LHS = Op0.getOperand(0);
3143 RHS = Op1.getOperand(0);
3147 // When we have small integers (i16 to be specific), the form present
3148 // post-legalization uses SETULT in the SELECT_CC for the
3149 // higher-order byte, depending on the fact that the
3150 // even-higher-order bytes are known to all be zero, for example:
3151 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3152 // (so when the second byte is the same, because all higher-order
3153 // bits from bytes 3 and 4 are known to be zero, the result of the
3154 // xor can be at most 255)
3155 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3156 isa<ConstantSDNode>(O.getOperand(1))) {
3158 uint64_t ULim = O.getConstantOperandVal(1);
3159 if (ULim != (UINT64_C(1) << b*8))
3162 // Now we need to make sure that the upper bytes are known to be
3164 unsigned Bits = Op0.getValueType().getSizeInBits();
3165 if (!CurDAG->MaskedValueIsZero(Op0,
3166 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3169 LHS = Op0.getOperand(0);
3170 RHS = Op0.getOperand(1);
3177 if (CC != ISD::SETEQ)
3180 SDValue Op = O.getOperand(0);
3181 if (Op.getOpcode() == ISD::AND) {
3182 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3184 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3187 SDValue XOR = Op.getOperand(0);
3188 if (XOR.getOpcode() == ISD::TRUNCATE)
3189 XOR = XOR.getOperand(0);
3190 if (XOR.getOpcode() != ISD::XOR)
3193 LHS = XOR.getOperand(0);
3194 RHS = XOR.getOperand(1);
3196 } else if (Op.getOpcode() == ISD::SRL) {
3197 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3199 unsigned Bits = Op.getValueType().getSizeInBits();
3202 if (Op.getConstantOperandVal(1) != Bits-8)
3205 SDValue XOR = Op.getOperand(0);
3206 if (XOR.getOpcode() == ISD::TRUNCATE)
3207 XOR = XOR.getOperand(0);
3208 if (XOR.getOpcode() != ISD::XOR)
3211 LHS = XOR.getOperand(0);
3212 RHS = XOR.getOperand(1);
3219 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3220 while (!Queue.empty()) {
3221 SDValue V = Queue.pop_back_val();
3223 for (const SDValue &O : V.getNode()->ops()) {
3225 uint64_t M = 0, A = 0;
3227 if (O.getOpcode() == ISD::OR) {
3229 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3233 BytesFound[b] = true;
3236 } else if ((LHS == ORHS && RHS == OLHS) ||
3237 (RHS == ORHS && LHS == OLHS)) {
3238 BytesFound[b] = true;
3250 unsigned LastB = 0, BCnt = 0;
3251 for (unsigned i = 0; i < 8; ++i)
3252 if (BytesFound[LastB]) {
3257 if (!LastB || BCnt < 2)
3260 // Because we'll be zero-extending the output anyway if don't have a specific
3261 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3262 if (LHS.getValueType() != VT) {
3263 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3264 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3267 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3269 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3270 if (NonTrivialMask && !Alt) {
3271 // Res = Mask & CMPB
3272 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3273 CurDAG->getConstant(Mask, dl, VT));
3275 // Res = (CMPB & Mask) | (~CMPB & Alt)
3276 // Which, as suggested here:
3277 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3278 // can be written as:
3279 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3280 // useful because the (Alt ^ Mask) can be pre-computed.
3281 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3282 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3283 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3284 CurDAG->getConstant(Alt, dl, VT));
3290 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3291 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3292 // involves constant materialization of a 0 or a 1 or both. If the result of
3293 // the extension is then operated upon by some operator that can be constant
3294 // folded with a constant 0 or 1, and that constant can be materialized using
3295 // only one instruction (like a zero or one), then we should fold in those
3296 // operations with the select.
3297 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3298 if (!PPCSubTarget->useCRBits())
3301 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3302 N->getOpcode() != ISD::SIGN_EXTEND &&
3303 N->getOpcode() != ISD::ANY_EXTEND)
3306 if (N->getOperand(0).getValueType() != MVT::i1)
3309 if (!N->hasOneUse())
3313 EVT VT = N->getValueType(0);
3314 SDValue Cond = N->getOperand(0);
3316 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3317 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3320 SDNode *User = *N->use_begin();
3321 if (User->getNumOperands() != 2)
3324 auto TryFold = [this, N, User, dl](SDValue Val) {
3325 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3326 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3327 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3329 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3330 User->getValueType(0),
3331 O0.getNode(), O1.getNode());
3334 SDValue TrueRes = TryFold(ConstTrue);
3337 SDValue FalseRes = TryFold(ConstFalse);
3341 // For us to materialize these using one instruction, we must be able to
3342 // represent them as signed 16-bit integers.
3343 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3344 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3345 if (!isInt<16>(True) || !isInt<16>(False))
3348 // We can replace User with a new SELECT node, and try again to see if we
3349 // can fold the select with its user.
3350 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3352 ConstTrue = TrueRes;
3353 ConstFalse = FalseRes;
3354 } while (N->hasOneUse());
3357 void PPCDAGToDAGISel::PreprocessISelDAG() {
3358 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3361 bool MadeChange = false;
3362 while (Position != CurDAG->allnodes_begin()) {
3363 SDNode *N = &*--Position;
3368 switch (N->getOpcode()) {
3371 Res = combineToCMPB(N);
3376 foldBoolExts(Res, N);
3379 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3380 DEBUG(N->dump(CurDAG));
3381 DEBUG(dbgs() << "\nNew: ");
3382 DEBUG(Res.getNode()->dump(CurDAG));
3383 DEBUG(dbgs() << "\n");
3385 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3391 CurDAG->RemoveDeadNodes();
3394 /// PostprocessISelDAG - Perform some late peephole optimizations
3395 /// on the DAG representation.
3396 void PPCDAGToDAGISel::PostprocessISelDAG() {
3398 // Skip peepholes at -O0.
3399 if (TM.getOptLevel() == CodeGenOpt::None)
3404 PeepholePPC64ZExt();
3407 // Check if all users of this node will become isel where the second operand
3408 // is the constant zero. If this is so, and if we can negate the condition,
3409 // then we can flip the true and false operands. This will allow the zero to
3410 // be folded with the isel so that we don't need to materialize a register
3412 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3413 // If we're not using isel, then this does not matter.
3414 if (!PPCSubTarget->hasISEL())
3417 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3420 if (!User->isMachineOpcode())
3422 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3423 User->getMachineOpcode() != PPC::SELECT_I8)
3426 SDNode *Op2 = User->getOperand(2).getNode();
3427 if (!Op2->isMachineOpcode())
3430 if (Op2->getMachineOpcode() != PPC::LI &&
3431 Op2->getMachineOpcode() != PPC::LI8)
3434 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3438 if (!C->isNullValue())
3445 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3446 SmallVector<SDNode *, 4> ToReplace;
3447 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3450 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3451 User->getMachineOpcode() == PPC::SELECT_I8) &&
3452 "Must have all select users");
3453 ToReplace.push_back(User);
3456 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3457 UE = ToReplace.end(); UI != UE; ++UI) {
3460 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3461 User->getValueType(0), User->getOperand(0),
3462 User->getOperand(2),
3463 User->getOperand(1));
3465 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3466 DEBUG(User->dump(CurDAG));
3467 DEBUG(dbgs() << "\nNew: ");
3468 DEBUG(ResNode->dump(CurDAG));
3469 DEBUG(dbgs() << "\n");
3471 ReplaceUses(User, ResNode);
3475 void PPCDAGToDAGISel::PeepholeCROps() {
3479 for (SDNode &Node : CurDAG->allnodes()) {
3480 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
3481 if (!MachineNode || MachineNode->use_empty())
3483 SDNode *ResNode = MachineNode;
3485 bool Op1Set = false, Op1Unset = false,
3487 Op2Set = false, Op2Unset = false,
3490 unsigned Opcode = MachineNode->getMachineOpcode();
3501 SDValue Op = MachineNode->getOperand(1);
3502 if (Op.isMachineOpcode()) {
3503 if (Op.getMachineOpcode() == PPC::CRSET)
3505 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3507 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3508 Op.getOperand(0) == Op.getOperand(1))
3514 case PPC::SELECT_I4:
3515 case PPC::SELECT_I8:
3516 case PPC::SELECT_F4:
3517 case PPC::SELECT_F8:
3518 case PPC::SELECT_QFRC:
3519 case PPC::SELECT_QSRC:
3520 case PPC::SELECT_QBRC:
3521 case PPC::SELECT_VRRC:
3522 case PPC::SELECT_VSFRC:
3523 case PPC::SELECT_VSSRC:
3524 case PPC::SELECT_VSRC: {
3525 SDValue Op = MachineNode->getOperand(0);
3526 if (Op.isMachineOpcode()) {
3527 if (Op.getMachineOpcode() == PPC::CRSET)
3529 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3531 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3532 Op.getOperand(0) == Op.getOperand(1))
3539 bool SelectSwap = false;
3543 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3545 ResNode = MachineNode->getOperand(0).getNode();
3548 ResNode = MachineNode->getOperand(1).getNode();
3551 ResNode = MachineNode->getOperand(0).getNode();
3552 else if (Op1Unset || Op2Unset)
3553 // x & 0 = 0 & y = 0
3554 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3557 // ~x & y = andc(y, x)
3558 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3559 MVT::i1, MachineNode->getOperand(1),
3560 MachineNode->getOperand(0).
3563 // x & ~y = andc(x, y)
3564 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3565 MVT::i1, MachineNode->getOperand(0),
3566 MachineNode->getOperand(1).
3568 else if (AllUsersSelectZero(MachineNode))
3569 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3570 MVT::i1, MachineNode->getOperand(0),
3571 MachineNode->getOperand(1)),
3575 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3576 // nand(x, x) -> nor(x, x)
3577 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3578 MVT::i1, MachineNode->getOperand(0),
3579 MachineNode->getOperand(0));
3581 // nand(1, y) -> nor(y, y)
3582 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3583 MVT::i1, MachineNode->getOperand(1),
3584 MachineNode->getOperand(1));
3586 // nand(x, 1) -> nor(x, x)
3587 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3588 MVT::i1, MachineNode->getOperand(0),
3589 MachineNode->getOperand(0));
3590 else if (Op1Unset || Op2Unset)
3591 // nand(x, 0) = nand(0, y) = 1
3592 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3595 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3596 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3597 MVT::i1, MachineNode->getOperand(0).
3599 MachineNode->getOperand(1));
3601 // nand(x, ~y) = ~x | y = orc(y, x)
3602 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3603 MVT::i1, MachineNode->getOperand(1).
3605 MachineNode->getOperand(0));
3606 else if (AllUsersSelectZero(MachineNode))
3607 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3608 MVT::i1, MachineNode->getOperand(0),
3609 MachineNode->getOperand(1)),
3613 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3615 ResNode = MachineNode->getOperand(0).getNode();
3616 else if (Op1Set || Op2Set)
3617 // x | 1 = 1 | y = 1
3618 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3622 ResNode = MachineNode->getOperand(1).getNode();
3625 ResNode = MachineNode->getOperand(0).getNode();
3627 // ~x | y = orc(y, x)
3628 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3629 MVT::i1, MachineNode->getOperand(1),
3630 MachineNode->getOperand(0).
3633 // x | ~y = orc(x, y)
3634 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3635 MVT::i1, MachineNode->getOperand(0),
3636 MachineNode->getOperand(1).
3638 else if (AllUsersSelectZero(MachineNode))
3639 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3640 MVT::i1, MachineNode->getOperand(0),
3641 MachineNode->getOperand(1)),
3645 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3647 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3650 // xor(1, y) -> nor(y, y)
3651 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3652 MVT::i1, MachineNode->getOperand(1),
3653 MachineNode->getOperand(1));
3655 // xor(x, 1) -> nor(x, x)
3656 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3657 MVT::i1, MachineNode->getOperand(0),
3658 MachineNode->getOperand(0));
3661 ResNode = MachineNode->getOperand(1).getNode();
3664 ResNode = MachineNode->getOperand(0).getNode();
3666 // xor(~x, y) = eqv(x, y)
3667 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3668 MVT::i1, MachineNode->getOperand(0).
3670 MachineNode->getOperand(1));
3672 // xor(x, ~y) = eqv(x, y)
3673 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3674 MVT::i1, MachineNode->getOperand(0),
3675 MachineNode->getOperand(1).
3677 else if (AllUsersSelectZero(MachineNode))
3678 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3679 MVT::i1, MachineNode->getOperand(0),
3680 MachineNode->getOperand(1)),
3684 if (Op1Set || Op2Set)
3686 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3689 // nor(0, y) = ~y -> nor(y, y)
3690 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3691 MVT::i1, MachineNode->getOperand(1),
3692 MachineNode->getOperand(1));
3695 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3696 MVT::i1, MachineNode->getOperand(0),
3697 MachineNode->getOperand(0));
3699 // nor(~x, y) = andc(x, y)
3700 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3701 MVT::i1, MachineNode->getOperand(0).
3703 MachineNode->getOperand(1));
3705 // nor(x, ~y) = andc(y, x)
3706 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3707 MVT::i1, MachineNode->getOperand(1).
3709 MachineNode->getOperand(0));
3710 else if (AllUsersSelectZero(MachineNode))
3711 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3712 MVT::i1, MachineNode->getOperand(0),
3713 MachineNode->getOperand(1)),
3717 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3719 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3723 ResNode = MachineNode->getOperand(1).getNode();
3726 ResNode = MachineNode->getOperand(0).getNode();
3728 // eqv(0, y) = ~y -> nor(y, y)
3729 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3730 MVT::i1, MachineNode->getOperand(1),
3731 MachineNode->getOperand(1));
3734 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3735 MVT::i1, MachineNode->getOperand(0),
3736 MachineNode->getOperand(0));
3738 // eqv(~x, y) = xor(x, y)
3739 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3740 MVT::i1, MachineNode->getOperand(0).
3742 MachineNode->getOperand(1));
3744 // eqv(x, ~y) = xor(x, y)
3745 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3746 MVT::i1, MachineNode->getOperand(0),
3747 MachineNode->getOperand(1).
3749 else if (AllUsersSelectZero(MachineNode))
3750 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3751 MVT::i1, MachineNode->getOperand(0),
3752 MachineNode->getOperand(1)),
3756 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3758 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3762 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3763 MVT::i1, MachineNode->getOperand(1),
3764 MachineNode->getOperand(1));
3765 else if (Op1Unset || Op2Set)
3766 // andc(0, y) = andc(x, 1) = 0
3767 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3771 ResNode = MachineNode->getOperand(0).getNode();
3773 // andc(~x, y) = ~(x | y) = nor(x, y)
3774 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3775 MVT::i1, MachineNode->getOperand(0).
3777 MachineNode->getOperand(1));
3779 // andc(x, ~y) = x & y
3780 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3781 MVT::i1, MachineNode->getOperand(0),
3782 MachineNode->getOperand(1).
3784 else if (AllUsersSelectZero(MachineNode))
3785 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3786 MVT::i1, MachineNode->getOperand(1),
3787 MachineNode->getOperand(0)),
3791 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3793 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3795 else if (Op1Set || Op2Unset)
3796 // orc(1, y) = orc(x, 0) = 1
3797 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3801 ResNode = MachineNode->getOperand(0).getNode();
3804 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3805 MVT::i1, MachineNode->getOperand(1),
3806 MachineNode->getOperand(1));
3808 // orc(~x, y) = ~(x & y) = nand(x, y)
3809 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3810 MVT::i1, MachineNode->getOperand(0).
3812 MachineNode->getOperand(1));
3814 // orc(x, ~y) = x | y
3815 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3816 MVT::i1, MachineNode->getOperand(0),
3817 MachineNode->getOperand(1).
3819 else if (AllUsersSelectZero(MachineNode))
3820 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3821 MVT::i1, MachineNode->getOperand(1),
3822 MachineNode->getOperand(0)),
3825 case PPC::SELECT_I4:
3826 case PPC::SELECT_I8:
3827 case PPC::SELECT_F4:
3828 case PPC::SELECT_F8:
3829 case PPC::SELECT_QFRC:
3830 case PPC::SELECT_QSRC:
3831 case PPC::SELECT_QBRC:
3832 case PPC::SELECT_VRRC:
3833 case PPC::SELECT_VSFRC:
3834 case PPC::SELECT_VSSRC:
3835 case PPC::SELECT_VSRC:
3837 ResNode = MachineNode->getOperand(1).getNode();
3839 ResNode = MachineNode->getOperand(2).getNode();
3841 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3843 MachineNode->getValueType(0),
3844 MachineNode->getOperand(0).
3846 MachineNode->getOperand(2),
3847 MachineNode->getOperand(1));
3852 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3856 MachineNode->getOperand(0).
3858 MachineNode->getOperand(1),
3859 MachineNode->getOperand(2));
3860 // FIXME: Handle Op1Set, Op1Unset here too.
3864 // If we're inverting this node because it is used only by selects that
3865 // we'd like to swap, then swap the selects before the node replacement.
3867 SwapAllSelectUsers(MachineNode);
3869 if (ResNode != MachineNode) {
3870 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3871 DEBUG(MachineNode->dump(CurDAG));
3872 DEBUG(dbgs() << "\nNew: ");
3873 DEBUG(ResNode->dump(CurDAG));
3874 DEBUG(dbgs() << "\n");
3876 ReplaceUses(MachineNode, ResNode);
3881 CurDAG->RemoveDeadNodes();
3882 } while (IsModified);
3885 // Gather the set of 32-bit operations that are known to have their
3886 // higher-order 32 bits zero, where ToPromote contains all such operations.
3887 static bool PeepholePPC64ZExtGather(SDValue Op32,
3888 SmallPtrSetImpl<SDNode *> &ToPromote) {
3889 if (!Op32.isMachineOpcode())
3892 // First, check for the "frontier" instructions (those that will clear the
3893 // higher-order 32 bits.
3895 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3896 // around. If it does not, then these instructions will clear the
3897 // higher-order bits.
3898 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3899 Op32.getMachineOpcode() == PPC::RLWNM) &&
3900 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3901 ToPromote.insert(Op32.getNode());
3905 // SLW and SRW always clear the higher-order bits.
3906 if (Op32.getMachineOpcode() == PPC::SLW ||
3907 Op32.getMachineOpcode() == PPC::SRW) {
3908 ToPromote.insert(Op32.getNode());
3912 // For LI and LIS, we need the immediate to be positive (so that it is not
3914 if (Op32.getMachineOpcode() == PPC::LI ||
3915 Op32.getMachineOpcode() == PPC::LIS) {
3916 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3919 ToPromote.insert(Op32.getNode());
3923 // LHBRX and LWBRX always clear the higher-order bits.
3924 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3925 Op32.getMachineOpcode() == PPC::LWBRX) {
3926 ToPromote.insert(Op32.getNode());
3930 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3931 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3932 ToPromote.insert(Op32.getNode());
3936 // Next, check for those instructions we can look through.
3938 // Assuming the mask does not wrap around, then the higher-order bits are
3939 // taken directly from the first operand.
3940 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3941 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3942 SmallPtrSet<SDNode *, 16> ToPromote1;
3943 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3946 ToPromote.insert(Op32.getNode());
3947 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3951 // For OR, the higher-order bits are zero if that is true for both operands.
3952 // For SELECT_I4, the same is true (but the relevant operand numbers are
3954 if (Op32.getMachineOpcode() == PPC::OR ||
3955 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3956 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3957 SmallPtrSet<SDNode *, 16> ToPromote1;
3958 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3960 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3963 ToPromote.insert(Op32.getNode());
3964 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3968 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3969 // zero, and also for the constant to be positive (so that it is not sign
3971 if (Op32.getMachineOpcode() == PPC::ORI ||
3972 Op32.getMachineOpcode() == PPC::ORIS) {
3973 SmallPtrSet<SDNode *, 16> ToPromote1;
3974 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3976 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3979 ToPromote.insert(Op32.getNode());
3980 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3984 // The higher-order bits of AND are zero if that is true for at least one of
3986 if (Op32.getMachineOpcode() == PPC::AND) {
3987 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3989 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3991 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3992 if (!Op0OK && !Op1OK)
3995 ToPromote.insert(Op32.getNode());
3998 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4001 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4006 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4007 // of the first operand, or if the second operand is positive (so that it is
4008 // not sign extended).
4009 if (Op32.getMachineOpcode() == PPC::ANDIo ||
4010 Op32.getMachineOpcode() == PPC::ANDISo) {
4011 SmallPtrSet<SDNode *, 16> ToPromote1;
4013 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4014 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4015 if (!Op0OK && !Op1OK)
4018 ToPromote.insert(Op32.getNode());
4021 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4029 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4030 if (!PPCSubTarget->isPPC64())
4033 // When we zero-extend from i32 to i64, we use a pattern like this:
4034 // def : Pat<(i64 (zext i32:$in)),
4035 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4037 // There are several 32-bit shift/rotate instructions, however, that will
4038 // clear the higher-order bits of their output, rendering the RLDICL
4039 // unnecessary. When that happens, we remove it here, and redefine the
4040 // relevant 32-bit operation to be a 64-bit operation.
4042 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4045 bool MadeChange = false;
4046 while (Position != CurDAG->allnodes_begin()) {
4047 SDNode *N = &*--Position;
4048 // Skip dead nodes and any non-machine opcodes.
4049 if (N->use_empty() || !N->isMachineOpcode())
4052 if (N->getMachineOpcode() != PPC::RLDICL)
4055 if (N->getConstantOperandVal(1) != 0 ||
4056 N->getConstantOperandVal(2) != 32)
4059 SDValue ISR = N->getOperand(0);
4060 if (!ISR.isMachineOpcode() ||
4061 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4064 if (!ISR.hasOneUse())
4067 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4070 SDValue IDef = ISR.getOperand(0);
4071 if (!IDef.isMachineOpcode() ||
4072 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4075 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4076 // can get rid of it.
4078 SDValue Op32 = ISR->getOperand(1);
4079 if (!Op32.isMachineOpcode())
4082 // There are some 32-bit instructions that always clear the high-order 32
4083 // bits, there are also some instructions (like AND) that we can look
4085 SmallPtrSet<SDNode *, 16> ToPromote;
4086 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4089 // If the ToPromote set contains nodes that have uses outside of the set
4090 // (except for the original INSERT_SUBREG), then abort the transformation.
4091 bool OutsideUse = false;
4092 for (SDNode *PN : ToPromote) {
4093 for (SDNode *UN : PN->uses()) {
4094 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4108 // We now know that this zero extension can be removed by promoting to
4109 // nodes in ToPromote to 64-bit operations, where for operations in the
4110 // frontier of the set, we need to insert INSERT_SUBREGs for their
4112 for (SDNode *PN : ToPromote) {
4114 switch (PN->getMachineOpcode()) {
4116 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4117 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4118 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4119 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4120 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4121 case PPC::LI: NewOpcode = PPC::LI8; break;
4122 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4123 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4124 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4125 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4126 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4127 case PPC::OR: NewOpcode = PPC::OR8; break;
4128 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4129 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4130 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4131 case PPC::AND: NewOpcode = PPC::AND8; break;
4132 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4133 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4136 // Note: During the replacement process, the nodes will be in an
4137 // inconsistent state (some instructions will have operands with values
4138 // of the wrong type). Once done, however, everything should be right
4141 SmallVector<SDValue, 4> Ops;
4142 for (const SDValue &V : PN->ops()) {
4143 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4144 !isa<ConstantSDNode>(V)) {
4145 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4147 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4148 ISR.getNode()->getVTList(), ReplOpOps);
4149 Ops.push_back(SDValue(ReplOp, 0));
4155 // Because all to-be-promoted nodes only have users that are other
4156 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4157 // the i32 result value type with i64.
4159 SmallVector<EVT, 2> NewVTs;
4160 SDVTList VTs = PN->getVTList();
4161 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4162 if (VTs.VTs[i] == MVT::i32)
4163 NewVTs.push_back(MVT::i64);
4165 NewVTs.push_back(VTs.VTs[i]);
4167 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4168 DEBUG(PN->dump(CurDAG));
4170 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4172 DEBUG(dbgs() << "\nNew: ");
4173 DEBUG(PN->dump(CurDAG));
4174 DEBUG(dbgs() << "\n");
4177 // Now we replace the original zero extend and its associated INSERT_SUBREG
4178 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4181 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4182 DEBUG(N->dump(CurDAG));
4183 DEBUG(dbgs() << "\nNew: ");
4184 DEBUG(Op32.getNode()->dump(CurDAG));
4185 DEBUG(dbgs() << "\n");
4187 ReplaceUses(N, Op32.getNode());
4191 CurDAG->RemoveDeadNodes();
4194 void PPCDAGToDAGISel::PeepholePPC64() {
4195 // These optimizations are currently supported only for 64-bit SVR4.
4196 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4199 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4202 while (Position != CurDAG->allnodes_begin()) {
4203 SDNode *N = &*--Position;
4204 // Skip dead nodes and any non-machine opcodes.
4205 if (N->use_empty() || !N->isMachineOpcode())
4209 unsigned StorageOpcode = N->getMachineOpcode();
4211 switch (StorageOpcode) {
4242 // If this is a load or store with a zero offset, or within the alignment,
4243 // we may be able to fold an add-immediate into the memory operation.
4244 // The check against alignment is below, as it can't occur until we check
4245 // the arguments to N
4246 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4249 SDValue Base = N->getOperand(FirstOp + 1);
4250 if (!Base.isMachineOpcode())
4253 // On targets with fusion, we don't want this to fire and remove a fusion
4254 // opportunity, unless a) it results in another fusion opportunity or
4255 // b) optimizing for size.
4256 if (PPCSubTarget->hasFusion() &&
4257 (!MF->getFunction()->optForSize() && !Base.hasOneUse()))
4261 bool ReplaceFlags = true;
4263 // When the feeding operation is an add-immediate of some sort,
4264 // determine whether we need to add relocation information to the
4265 // target flags on the immediate operand when we fold it into the
4266 // load instruction.
4268 // For something like ADDItocL, the relocation information is
4269 // inferred from the opcode; when we process it in the AsmPrinter,
4270 // we add the necessary relocation there. A load, though, can receive
4271 // relocation from various flavors of ADDIxxx, so we need to carry
4272 // the relocation information in the target flags.
4273 switch (Base.getMachineOpcode()) {
4278 // In some cases (such as TLS) the relocation information
4279 // is already in place on the operand, so copying the operand
4281 ReplaceFlags = false;
4282 // For these cases, the immediate may not be divisible by 4, in
4283 // which case the fold is illegal for DS-form instructions. (The
4284 // other cases provide aligned addresses and are always safe.)
4285 if ((StorageOpcode == PPC::LWA ||
4286 StorageOpcode == PPC::LD ||
4287 StorageOpcode == PPC::STD) &&
4288 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4289 Base.getConstantOperandVal(1) % 4 != 0))
4292 case PPC::ADDIdtprelL:
4293 Flags = PPCII::MO_DTPREL_LO;
4295 case PPC::ADDItlsldL:
4296 Flags = PPCII::MO_TLSLD_LO;
4299 Flags = PPCII::MO_TOC_LO;
4303 SDValue ImmOpnd = Base.getOperand(1);
4304 int MaxDisplacement = 0;
4305 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4306 const GlobalValue *GV = GA->getGlobal();
4307 MaxDisplacement = GV->getAlignment() - 1;
4310 int Offset = N->getConstantOperandVal(FirstOp);
4311 if (Offset < 0 || Offset > MaxDisplacement)
4314 // We found an opportunity. Reverse the operands from the add
4315 // immediate and substitute them into the load or store. If
4316 // needed, update the target flags for the immediate operand to
4317 // reflect the necessary relocation information.
4318 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4319 DEBUG(Base->dump(CurDAG));
4320 DEBUG(dbgs() << "\nN: ");
4321 DEBUG(N->dump(CurDAG));
4322 DEBUG(dbgs() << "\n");
4324 // If the relocation information isn't already present on the
4325 // immediate operand, add it now.
4327 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4329 const GlobalValue *GV = GA->getGlobal();
4330 // We can't perform this optimization for data whose alignment
4331 // is insufficient for the instruction encoding.
4332 if (GV->getAlignment() < 4 &&
4333 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4334 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
4335 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4338 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
4339 } else if (ConstantPoolSDNode *CP =
4340 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4341 const Constant *C = CP->getConstVal();
4342 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4348 if (FirstOp == 1) // Store
4349 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4350 Base.getOperand(0), N->getOperand(3));
4352 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4355 // The add-immediate may now be dead, in which case remove it.
4356 if (Base.getNode()->use_empty())
4357 CurDAG->RemoveDeadNode(Base.getNode());
4362 /// createPPCISelDag - This pass converts a legalized DAG into a
4363 /// PowerPC-specific DAG, ready for instruction scheduling.
4365 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4366 return new PPCDAGToDAGISel(TM);
4369 static void initializePassOnce(PassRegistry &Registry) {
4370 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4371 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4372 nullptr, false, false);
4373 Registry.registerPass(*PI, true);
4376 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4377 CALL_ONCE_INITIALIZATION(initializePassOnce);