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/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
39 #define DEBUG_TYPE "ppc-codegen"
41 // FIXME: Remove this once the bug has been fixed!
42 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
43 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
46 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
47 cl::desc("use aggressive ppc isel for bit permutations"),
49 static cl::opt<bool> BPermRewriterNoMasking(
50 "ppc-bit-perm-rewriter-stress-rotates",
51 cl::desc("stress rotate selection in aggressive ppc isel for "
56 void initializePPCDAGToDAGISelPass(PassRegistry&);
60 //===--------------------------------------------------------------------===//
61 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
62 /// instructions for SelectionDAG operations.
64 class PPCDAGToDAGISel : public SelectionDAGISel {
65 const PPCTargetMachine &TM;
66 const PPCSubtarget *PPCSubTarget;
67 const PPCTargetLowering *PPCLowering;
68 unsigned GlobalBaseReg;
70 explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
71 : SelectionDAGISel(tm), TM(tm) {
72 initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
75 bool runOnMachineFunction(MachineFunction &MF) override {
76 // Make sure we re-emit a set of the global base reg if necessary
78 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
79 PPCLowering = PPCSubTarget->getTargetLowering();
80 SelectionDAGISel::runOnMachineFunction(MF);
82 if (!PPCSubTarget->isSVR4ABI())
88 void PreprocessISelDAG() override;
89 void PostprocessISelDAG() override;
91 /// getI32Imm - Return a target constant with the specified value, of type
93 inline SDValue getI32Imm(unsigned Imm) {
94 return CurDAG->getTargetConstant(Imm, MVT::i32);
97 /// getI64Imm - Return a target constant with the specified value, of type
99 inline SDValue getI64Imm(uint64_t Imm) {
100 return CurDAG->getTargetConstant(Imm, MVT::i64);
103 /// getSmallIPtrImm - Return a target constant of pointer type.
104 inline SDValue getSmallIPtrImm(unsigned Imm) {
105 return CurDAG->getTargetConstant(Imm, PPCLowering->getPointerTy());
108 /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
109 /// with any number of 0s on either side. The 1s are allowed to wrap from
110 /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
111 /// 0x0F0F0000 is not, since all 1s are not contiguous.
112 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
115 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
116 /// rotate and mask opcode and mask operation.
117 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
118 unsigned &SH, unsigned &MB, unsigned &ME);
120 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
121 /// base register. Return the virtual register that holds this value.
122 SDNode *getGlobalBaseReg();
124 SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
126 // Select - Convert the specified operand from a target-independent to a
127 // target-specific node if it hasn't already been changed.
128 SDNode *Select(SDNode *N) override;
130 SDNode *SelectBitfieldInsert(SDNode *N);
131 SDNode *SelectBitPermutation(SDNode *N);
133 /// SelectCC - Select a comparison of the specified values with the
134 /// specified condition code, returning the CR# of the expression.
135 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
137 /// SelectAddrImm - Returns true if the address N can be represented by
138 /// a base register plus a signed 16-bit displacement [r+imm].
139 bool SelectAddrImm(SDValue N, SDValue &Disp,
141 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
144 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
145 /// immediate field. Note that the operand at this point is already the
146 /// result of a prior SelectAddressRegImm call.
147 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
148 if (N.getOpcode() == ISD::TargetConstant ||
149 N.getOpcode() == ISD::TargetGlobalAddress) {
157 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
158 /// represented as an indexed [r+r] operation. Returns false if it can
159 /// be represented by [r+imm], which are preferred.
160 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
161 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
164 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
165 /// represented as an indexed [r+r] operation.
166 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
167 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
170 /// SelectAddrImmX4 - Returns true if the address N can be represented by
171 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
172 /// Suitable for use by STD and friends.
173 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
174 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
177 // Select an address into a single register.
178 bool SelectAddr(SDValue N, SDValue &Base) {
183 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
184 /// inline asm expressions. It is always correct to compute the value into
185 /// a register. The case of adding a (possibly relocatable) constant to a
186 /// register can be improved, but it is wrong to substitute Reg+Reg for
187 /// Reg in an asm, because the load or store opcode would have to change.
188 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
189 unsigned ConstraintID,
190 std::vector<SDValue> &OutOps) override {
192 switch(ConstraintID) {
194 errs() << "ConstraintID: " << ConstraintID << "\n";
195 llvm_unreachable("Unexpected asm memory constraint");
196 case InlineAsm::Constraint_es:
197 case InlineAsm::Constraint_m:
198 case InlineAsm::Constraint_o:
199 case InlineAsm::Constraint_Q:
200 case InlineAsm::Constraint_Z:
201 case InlineAsm::Constraint_Zy:
202 // We need to make sure that this one operand does not end up in r0
203 // (because we might end up lowering this as 0(%op)).
204 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
205 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
206 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
208 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
209 SDLoc(Op), Op.getValueType(),
212 OutOps.push_back(NewOp);
218 void InsertVRSaveCode(MachineFunction &MF);
220 const char *getPassName() const override {
221 return "PowerPC DAG->DAG Pattern Instruction Selection";
224 // Include the pieces autogenerated from the target description.
225 #include "PPCGenDAGISel.inc"
228 SDNode *SelectSETCC(SDNode *N);
230 void PeepholePPC64();
231 void PeepholePPC64ZExt();
232 void PeepholeCROps();
234 SDValue combineToCMPB(SDNode *N);
235 void foldBoolExts(SDValue &Res, SDNode *&N);
237 bool AllUsersSelectZero(SDNode *N);
238 void SwapAllSelectUsers(SDNode *N);
240 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
244 /// InsertVRSaveCode - Once the entire function has been instruction selected,
245 /// all virtual registers are created and all machine instructions are built,
246 /// check to see if we need to save/restore VRSAVE. If so, do it.
247 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
248 // Check to see if this function uses vector registers, which means we have to
249 // save and restore the VRSAVE register and update it with the regs we use.
251 // In this case, there will be virtual registers of vector type created
252 // by the scheduler. Detect them now.
253 bool HasVectorVReg = false;
254 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
255 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
256 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
257 HasVectorVReg = true;
261 if (!HasVectorVReg) return; // nothing to do.
263 // If we have a vector register, we want to emit code into the entry and exit
264 // blocks to save and restore the VRSAVE register. We do this here (instead
265 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
267 // 1. This (trivially) reduces the load on the register allocator, by not
268 // having to represent the live range of the VRSAVE register.
269 // 2. This (more significantly) allows us to create a temporary virtual
270 // register to hold the saved VRSAVE value, allowing this temporary to be
271 // register allocated, instead of forcing it to be spilled to the stack.
273 // Create two vregs - one to hold the VRSAVE register that is live-in to the
274 // function and one for the value after having bits or'd into it.
275 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
276 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
278 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
279 MachineBasicBlock &EntryBB = *Fn.begin();
281 // Emit the following code into the entry block:
282 // InVRSAVE = MFVRSAVE
283 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
284 // MTVRSAVE UpdatedVRSAVE
285 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
286 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
287 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
288 UpdatedVRSAVE).addReg(InVRSAVE);
289 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
291 // Find all return blocks, outputting a restore in each epilog.
292 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
293 if (!BB->empty() && BB->back().isReturn()) {
294 IP = BB->end(); --IP;
296 // Skip over all terminator instructions, which are part of the return
298 MachineBasicBlock::iterator I2 = IP;
299 while (I2 != BB->begin() && (--I2)->isTerminator())
302 // Emit: MTVRSAVE InVRSave
303 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
309 /// getGlobalBaseReg - Output the instructions required to put the
310 /// base address to use for accessing globals into a register.
312 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
313 if (!GlobalBaseReg) {
314 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
315 // Insert the set of GlobalBaseReg into the first MBB of the function
316 MachineBasicBlock &FirstMBB = MF->front();
317 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
318 const Module *M = MF->getFunction()->getParent();
321 if (PPCLowering->getPointerTy() == MVT::i32) {
322 if (PPCSubTarget->isTargetELF()) {
323 GlobalBaseReg = PPC::R30;
324 if (M->getPICLevel() == PICLevel::Small) {
325 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
326 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
327 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
329 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
330 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
331 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
332 BuildMI(FirstMBB, MBBI, dl,
333 TII.get(PPC::UpdateGBR), GlobalBaseReg)
334 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
335 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
339 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
340 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
341 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
344 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
345 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
346 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
349 return CurDAG->getRegister(GlobalBaseReg,
350 PPCLowering->getPointerTy()).getNode();
353 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
354 /// or 64-bit immediate, and if the value can be accurately represented as a
355 /// sign extension from a 16-bit value. If so, this returns true and the
357 static bool isIntS16Immediate(SDNode *N, short &Imm) {
358 if (N->getOpcode() != ISD::Constant)
361 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
362 if (N->getValueType(0) == MVT::i32)
363 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
365 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
368 static bool isIntS16Immediate(SDValue Op, short &Imm) {
369 return isIntS16Immediate(Op.getNode(), Imm);
373 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
374 /// operand. If so Imm will receive the 32-bit value.
375 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
376 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
377 Imm = cast<ConstantSDNode>(N)->getZExtValue();
383 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
384 /// operand. If so Imm will receive the 64-bit value.
385 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
386 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
387 Imm = cast<ConstantSDNode>(N)->getZExtValue();
393 // isInt32Immediate - This method tests to see if a constant operand.
394 // If so Imm will receive the 32 bit value.
395 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
396 return isInt32Immediate(N.getNode(), Imm);
400 // isOpcWithIntImmediate - This method tests to see if the node is a specific
401 // opcode and that it has a immediate integer right operand.
402 // If so Imm will receive the 32 bit value.
403 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
404 return N->getOpcode() == Opc
405 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
408 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
410 int FI = cast<FrameIndexSDNode>(N)->getIndex();
411 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
412 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
414 return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
415 getSmallIPtrImm(Offset));
416 return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
417 getSmallIPtrImm(Offset));
420 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
424 if (isShiftedMask_32(Val)) {
425 // look for the first non-zero bit
426 MB = countLeadingZeros(Val);
427 // look for the first zero bit after the run of ones
428 ME = countLeadingZeros((Val - 1) ^ Val);
431 Val = ~Val; // invert mask
432 if (isShiftedMask_32(Val)) {
433 // effectively look for the first zero bit
434 ME = countLeadingZeros(Val) - 1;
435 // effectively look for the first one bit after the run of zeros
436 MB = countLeadingZeros((Val - 1) ^ Val) + 1;
444 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
445 bool isShiftMask, unsigned &SH,
446 unsigned &MB, unsigned &ME) {
447 // Don't even go down this path for i64, since different logic will be
448 // necessary for rldicl/rldicr/rldimi.
449 if (N->getValueType(0) != MVT::i32)
453 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
454 unsigned Opcode = N->getOpcode();
455 if (N->getNumOperands() != 2 ||
456 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
459 if (Opcode == ISD::SHL) {
460 // apply shift left to mask if it comes first
461 if (isShiftMask) Mask = Mask << Shift;
462 // determine which bits are made indeterminant by shift
463 Indeterminant = ~(0xFFFFFFFFu << Shift);
464 } else if (Opcode == ISD::SRL) {
465 // apply shift right to mask if it comes first
466 if (isShiftMask) Mask = Mask >> Shift;
467 // determine which bits are made indeterminant by shift
468 Indeterminant = ~(0xFFFFFFFFu >> Shift);
469 // adjust for the left rotate
471 } else if (Opcode == ISD::ROTL) {
477 // if the mask doesn't intersect any Indeterminant bits
478 if (Mask && !(Mask & Indeterminant)) {
480 // make sure the mask is still a mask (wrap arounds may not be)
481 return isRunOfOnes(Mask, MB, ME);
486 /// SelectBitfieldInsert - turn an or of two masked values into
487 /// the rotate left word immediate then mask insert (rlwimi) instruction.
488 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
489 SDValue Op0 = N->getOperand(0);
490 SDValue Op1 = N->getOperand(1);
493 APInt LKZ, LKO, RKZ, RKO;
494 CurDAG->computeKnownBits(Op0, LKZ, LKO);
495 CurDAG->computeKnownBits(Op1, RKZ, RKO);
497 unsigned TargetMask = LKZ.getZExtValue();
498 unsigned InsertMask = RKZ.getZExtValue();
500 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
501 unsigned Op0Opc = Op0.getOpcode();
502 unsigned Op1Opc = Op1.getOpcode();
503 unsigned Value, SH = 0;
504 TargetMask = ~TargetMask;
505 InsertMask = ~InsertMask;
507 // If the LHS has a foldable shift and the RHS does not, then swap it to the
508 // RHS so that we can fold the shift into the insert.
509 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
510 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
511 Op0.getOperand(0).getOpcode() == ISD::SRL) {
512 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
513 Op1.getOperand(0).getOpcode() != ISD::SRL) {
515 std::swap(Op0Opc, Op1Opc);
516 std::swap(TargetMask, InsertMask);
519 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
520 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
521 Op1.getOperand(0).getOpcode() != ISD::SRL) {
523 std::swap(Op0Opc, Op1Opc);
524 std::swap(TargetMask, InsertMask);
529 if (isRunOfOnes(InsertMask, MB, ME)) {
532 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
533 isInt32Immediate(Op1.getOperand(1), Value)) {
534 Op1 = Op1.getOperand(0);
535 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
537 if (Op1Opc == ISD::AND) {
538 // The AND mask might not be a constant, and we need to make sure that
539 // if we're going to fold the masking with the insert, all bits not
540 // know to be zero in the mask are known to be one.
542 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
543 bool CanFoldMask = InsertMask == MKO.getZExtValue();
545 unsigned SHOpc = Op1.getOperand(0).getOpcode();
546 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
547 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
548 // Note that Value must be in range here (less than 32) because
549 // otherwise there would not be any bits set in InsertMask.
550 Op1 = Op1.getOperand(0).getOperand(0);
551 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
556 SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
558 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
564 // Predict the number of instructions that would be generated by calling
566 static unsigned SelectInt64CountDirect(int64_t Imm) {
567 // Assume no remaining bits.
568 unsigned Remainder = 0;
569 // Assume no shift required.
572 // If it can't be represented as a 32 bit value.
573 if (!isInt<32>(Imm)) {
574 Shift = countTrailingZeros<uint64_t>(Imm);
575 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
577 // If the shifted value fits 32 bits.
578 if (isInt<32>(ImmSh)) {
579 // Go with the shifted value.
582 // Still stuck with a 64 bit value.
589 // Intermediate operand.
592 // Handle first 32 bits.
593 unsigned Lo = Imm & 0xFFFF;
594 unsigned Hi = (Imm >> 16) & 0xFFFF;
597 if (isInt<16>(Imm)) {
601 // Handle the Hi bits and Lo bits.
608 // If no shift, we're done.
609 if (!Shift) return Result;
611 // Shift for next step if the upper 32-bits were not zero.
615 // Add in the last bits as required.
616 if ((Hi = (Remainder >> 16) & 0xFFFF))
618 if ((Lo = Remainder & 0xFFFF))
624 static uint64_t Rot64(uint64_t Imm, unsigned R) {
625 return (Imm << R) | (Imm >> (64 - R));
628 static unsigned SelectInt64Count(int64_t Imm) {
629 unsigned Count = SelectInt64CountDirect(Imm);
633 for (unsigned r = 1; r < 63; ++r) {
634 uint64_t RImm = Rot64(Imm, r);
635 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
636 Count = std::min(Count, RCount);
638 // See comments in SelectInt64 for an explanation of the logic below.
639 unsigned LS = findLastSet(RImm);
643 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
644 uint64_t RImmWithOnes = RImm | OnesMask;
646 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
647 Count = std::min(Count, RCount);
653 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
654 // (above) needs to be kept in sync with this function.
655 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
656 // Assume no remaining bits.
657 unsigned Remainder = 0;
658 // Assume no shift required.
661 // If it can't be represented as a 32 bit value.
662 if (!isInt<32>(Imm)) {
663 Shift = countTrailingZeros<uint64_t>(Imm);
664 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
666 // If the shifted value fits 32 bits.
667 if (isInt<32>(ImmSh)) {
668 // Go with the shifted value.
671 // Still stuck with a 64 bit value.
678 // Intermediate operand.
681 // Handle first 32 bits.
682 unsigned Lo = Imm & 0xFFFF;
683 unsigned Hi = (Imm >> 16) & 0xFFFF;
685 auto getI32Imm = [CurDAG](unsigned Imm) {
686 return CurDAG->getTargetConstant(Imm, MVT::i32);
690 if (isInt<16>(Imm)) {
692 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
694 // Handle the Hi bits.
695 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
696 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
698 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
699 SDValue(Result, 0), getI32Imm(Lo));
702 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
705 // If no shift, we're done.
706 if (!Shift) return Result;
708 // Shift for next step if the upper 32-bits were not zero.
710 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
713 getI32Imm(63 - Shift));
716 // Add in the last bits as required.
717 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
718 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
719 SDValue(Result, 0), getI32Imm(Hi));
721 if ((Lo = Remainder & 0xFFFF)) {
722 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
723 SDValue(Result, 0), getI32Imm(Lo));
729 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
730 unsigned Count = SelectInt64CountDirect(Imm);
732 return SelectInt64Direct(CurDAG, dl, Imm);
739 for (unsigned r = 1; r < 63; ++r) {
740 uint64_t RImm = Rot64(Imm, r);
741 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
742 if (RCount < Count) {
749 // If the immediate to generate has many trailing zeros, it might be
750 // worthwhile to generate a rotated value with too many leading ones
751 // (because that's free with li/lis's sign-extension semantics), and then
752 // mask them off after rotation.
754 unsigned LS = findLastSet(RImm);
755 // We're adding (63-LS) higher-order ones, and we expect to mask them off
756 // after performing the inverse rotation by (64-r). So we need that:
757 // 63-LS == 64-r => LS == r-1
761 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
762 uint64_t RImmWithOnes = RImm | OnesMask;
764 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
765 if (RCount < Count) {
768 MatImm = RImmWithOnes;
774 return SelectInt64Direct(CurDAG, dl, Imm);
776 auto getI32Imm = [CurDAG](unsigned Imm) {
777 return CurDAG->getTargetConstant(Imm, MVT::i32);
780 SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, MatImm), 0);
781 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
782 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
785 // Select a 64-bit constant.
786 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
790 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
791 return SelectInt64(CurDAG, dl, Imm);
795 class BitPermutationSelector {
799 // The bit number in the value, using a convention where bit 0 is the
808 ValueBit(SDValue V, unsigned I, Kind K = Variable)
809 : V(V), Idx(I), K(K) {}
810 ValueBit(Kind K = Variable)
811 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
813 bool isZero() const {
814 return K == ConstZero;
817 bool hasValue() const {
818 return K == Variable;
821 SDValue getValue() const {
822 assert(hasValue() && "Cannot get the value of a constant bit");
826 unsigned getValueBitIndex() const {
827 assert(hasValue() && "Cannot get the value bit index of a constant bit");
832 // A bit group has the same underlying value and the same rotate factor.
836 unsigned StartIdx, EndIdx;
838 // This rotation amount assumes that the lower 32 bits of the quantity are
839 // replicated in the high 32 bits by the rotation operator (which is done
840 // by rlwinm and friends in 64-bit mode).
842 // Did converting to Repl32 == true change the rotation factor? If it did,
843 // it decreased it by 32.
845 // Was this group coalesced after setting Repl32 to true?
846 bool Repl32Coalesced;
848 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
849 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
850 Repl32Coalesced(false) {
851 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
852 " [" << S << ", " << E << "]\n");
856 // Information on each (Value, RLAmt) pair (like the number of groups
857 // associated with each) used to choose the lowering method.
858 struct ValueRotInfo {
862 unsigned FirstGroupStartIdx;
866 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
869 // For sorting (in reverse order) by NumGroups, and then by
870 // FirstGroupStartIdx.
871 bool operator < (const ValueRotInfo &Other) const {
872 // We need to sort so that the non-Repl32 come first because, when we're
873 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
874 // masking operation.
875 if (Repl32 < Other.Repl32)
877 else if (Repl32 > Other.Repl32)
879 else if (NumGroups > Other.NumGroups)
881 else if (NumGroups < Other.NumGroups)
883 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
889 // Return true if something interesting was deduced, return false if we're
890 // providing only a generic representation of V (or something else likewise
891 // uninteresting for instruction selection).
892 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
893 switch (V.getOpcode()) {
896 if (isa<ConstantSDNode>(V.getOperand(1))) {
897 unsigned RotAmt = V.getConstantOperandVal(1);
899 SmallVector<ValueBit, 64> LHSBits(Bits.size());
900 getValueBits(V.getOperand(0), LHSBits);
902 for (unsigned i = 0; i < Bits.size(); ++i)
903 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
909 if (isa<ConstantSDNode>(V.getOperand(1))) {
910 unsigned ShiftAmt = V.getConstantOperandVal(1);
912 SmallVector<ValueBit, 64> LHSBits(Bits.size());
913 getValueBits(V.getOperand(0), LHSBits);
915 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
916 Bits[i] = LHSBits[i - ShiftAmt];
918 for (unsigned i = 0; i < ShiftAmt; ++i)
919 Bits[i] = ValueBit(ValueBit::ConstZero);
925 if (isa<ConstantSDNode>(V.getOperand(1))) {
926 unsigned ShiftAmt = V.getConstantOperandVal(1);
928 SmallVector<ValueBit, 64> LHSBits(Bits.size());
929 getValueBits(V.getOperand(0), LHSBits);
931 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
932 Bits[i] = LHSBits[i + ShiftAmt];
934 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
935 Bits[i] = ValueBit(ValueBit::ConstZero);
941 if (isa<ConstantSDNode>(V.getOperand(1))) {
942 uint64_t Mask = V.getConstantOperandVal(1);
944 SmallVector<ValueBit, 64> LHSBits(Bits.size());
945 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
947 for (unsigned i = 0; i < Bits.size(); ++i)
948 if (((Mask >> i) & 1) == 1)
949 Bits[i] = LHSBits[i];
951 Bits[i] = ValueBit(ValueBit::ConstZero);
953 // Mark this as interesting, only if the LHS was also interesting. This
954 // prevents the overall procedure from matching a single immediate 'and'
955 // (which is non-optimal because such an and might be folded with other
956 // things if we don't select it here).
961 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
962 getValueBits(V.getOperand(0), LHSBits);
963 getValueBits(V.getOperand(1), RHSBits);
965 bool AllDisjoint = true;
966 for (unsigned i = 0; i < Bits.size(); ++i)
967 if (LHSBits[i].isZero())
968 Bits[i] = RHSBits[i];
969 else if (RHSBits[i].isZero())
970 Bits[i] = LHSBits[i];
983 for (unsigned i = 0; i < Bits.size(); ++i)
984 Bits[i] = ValueBit(V, i);
989 // For each value (except the constant ones), compute the left-rotate amount
990 // to get it from its original to final position.
991 void computeRotationAmounts() {
993 RLAmt.resize(Bits.size());
994 for (unsigned i = 0; i < Bits.size(); ++i)
995 if (Bits[i].hasValue()) {
996 unsigned VBI = Bits[i].getValueBitIndex();
1000 RLAmt[i] = Bits.size() - (VBI - i);
1001 } else if (Bits[i].isZero()) {
1003 RLAmt[i] = UINT32_MAX;
1005 llvm_unreachable("Unknown value bit type");
1009 // Collect groups of consecutive bits with the same underlying value and
1010 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1011 // they break up groups.
1012 void collectBitGroups(bool LateMask) {
1015 unsigned LastRLAmt = RLAmt[0];
1016 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1017 unsigned LastGroupStartIdx = 0;
1018 for (unsigned i = 1; i < Bits.size(); ++i) {
1019 unsigned ThisRLAmt = RLAmt[i];
1020 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1021 if (LateMask && !ThisValue) {
1022 ThisValue = LastValue;
1023 ThisRLAmt = LastRLAmt;
1024 // If we're doing late masking, then the first bit group always starts
1025 // at zero (even if the first bits were zero).
1026 if (BitGroups.empty())
1027 LastGroupStartIdx = 0;
1030 // If this bit has the same underlying value and the same rotate factor as
1031 // the last one, then they're part of the same group.
1032 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1035 if (LastValue.getNode())
1036 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1038 LastRLAmt = ThisRLAmt;
1039 LastValue = ThisValue;
1040 LastGroupStartIdx = i;
1042 if (LastValue.getNode())
1043 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1046 if (BitGroups.empty())
1049 // We might be able to combine the first and last groups.
1050 if (BitGroups.size() > 1) {
1051 // If the first and last groups are the same, then remove the first group
1052 // in favor of the last group, making the ending index of the last group
1053 // equal to the ending index of the to-be-removed first group.
1054 if (BitGroups[0].StartIdx == 0 &&
1055 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1056 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1057 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1058 DEBUG(dbgs() << "\tcombining final bit group with inital one\n");
1059 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1060 BitGroups.erase(BitGroups.begin());
1065 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1066 // associated with each. If there is a degeneracy, pick the one that occurs
1067 // first (in the final value).
1068 void collectValueRotInfo() {
1071 for (auto &BG : BitGroups) {
1072 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1073 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1075 VRI.RLAmt = BG.RLAmt;
1076 VRI.Repl32 = BG.Repl32;
1078 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1081 // Now that we've collected the various ValueRotInfo instances, we need to
1083 ValueRotsVec.clear();
1084 for (auto &I : ValueRots) {
1085 ValueRotsVec.push_back(I.second);
1087 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1090 // In 64-bit mode, rlwinm and friends have a rotation operator that
1091 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1092 // indices of these instructions can only be in the lower 32 bits, so they
1093 // can only represent some 64-bit bit groups. However, when they can be used,
1094 // the 32-bit replication can be used to represent, as a single bit group,
1095 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1096 // groups when possible. Returns true if any of the bit groups were
1098 void assignRepl32BitGroups() {
1099 // If we have bits like this:
1101 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1102 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1103 // Groups: | RLAmt = 8 | RLAmt = 40 |
1105 // But, making use of a 32-bit operation that replicates the low-order 32
1106 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1109 auto IsAllLow32 = [this](BitGroup & BG) {
1110 if (BG.StartIdx <= BG.EndIdx) {
1111 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1112 if (!Bits[i].hasValue())
1114 if (Bits[i].getValueBitIndex() >= 32)
1118 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1119 if (!Bits[i].hasValue())
1121 if (Bits[i].getValueBitIndex() >= 32)
1124 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1125 if (!Bits[i].hasValue())
1127 if (Bits[i].getValueBitIndex() >= 32)
1135 for (auto &BG : BitGroups) {
1136 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1137 if (IsAllLow32(BG)) {
1138 if (BG.RLAmt >= 32) {
1145 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1146 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1147 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1152 // Now walk through the bit groups, consolidating where possible.
1153 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1154 // We might want to remove this bit group by merging it with the previous
1155 // group (which might be the ending group).
1156 auto IP = (I == BitGroups.begin()) ?
1157 std::prev(BitGroups.end()) : std::prev(I);
1158 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1159 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1161 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1162 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1163 " [" << I->StartIdx << ", " << I->EndIdx <<
1164 "] with group with range [" <<
1165 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1167 IP->EndIdx = I->EndIdx;
1168 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1169 IP->Repl32Coalesced = true;
1170 I = BitGroups.erase(I);
1173 // There is a special case worth handling: If there is a single group
1174 // covering the entire upper 32 bits, and it can be merged with both
1175 // the next and previous groups (which might be the same group), then
1176 // do so. If it is the same group (so there will be only one group in
1177 // total), then we need to reverse the order of the range so that it
1178 // covers the entire 64 bits.
1179 if (I->StartIdx == 32 && I->EndIdx == 63) {
1180 assert(std::next(I) == BitGroups.end() &&
1181 "bit group ends at index 63 but there is another?");
1182 auto IN = BitGroups.begin();
1184 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1185 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1186 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1189 DEBUG(dbgs() << "\tcombining bit group for " <<
1190 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1191 " [" << I->StartIdx << ", " << I->EndIdx <<
1192 "] with 32-bit replicated groups with ranges [" <<
1193 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1194 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1197 // There is only one other group; change it to cover the whole
1198 // range (backward, so that it can still be Repl32 but cover the
1199 // whole 64-bit range).
1202 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1203 IP->Repl32Coalesced = true;
1204 I = BitGroups.erase(I);
1206 // There are two separate groups, one before this group and one
1207 // after us (at the beginning). We're going to remove this group,
1208 // but also the group at the very beginning.
1209 IP->EndIdx = IN->EndIdx;
1210 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1211 IP->Repl32Coalesced = true;
1212 I = BitGroups.erase(I);
1213 BitGroups.erase(BitGroups.begin());
1216 // This must be the last group in the vector (and we might have
1217 // just invalidated the iterator above), so break here.
1227 SDValue getI32Imm(unsigned Imm) {
1228 return CurDAG->getTargetConstant(Imm, MVT::i32);
1231 uint64_t getZerosMask() {
1233 for (unsigned i = 0; i < Bits.size(); ++i) {
1234 if (Bits[i].hasValue())
1236 Mask |= (UINT64_C(1) << i);
1242 // Depending on the number of groups for a particular value, it might be
1243 // better to rotate, mask explicitly (using andi/andis), and then or the
1244 // result. Select this part of the result first.
1245 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1246 if (BPermRewriterNoMasking)
1249 for (ValueRotInfo &VRI : ValueRotsVec) {
1251 for (unsigned i = 0; i < Bits.size(); ++i) {
1252 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1254 if (RLAmt[i] != VRI.RLAmt)
1259 // Compute the masks for andi/andis that would be necessary.
1260 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1261 assert((ANDIMask != 0 || ANDISMask != 0) &&
1262 "No set bits in mask for value bit groups");
1263 bool NeedsRotate = VRI.RLAmt != 0;
1265 // We're trying to minimize the number of instructions. If we have one
1266 // group, using one of andi/andis can break even. If we have three
1267 // groups, we can use both andi and andis and break even (to use both
1268 // andi and andis we also need to or the results together). We need four
1269 // groups if we also need to rotate. To use andi/andis we need to do more
1270 // than break even because rotate-and-mask instructions tend to be easier
1273 // FIXME: We've biased here against using andi/andis, which is right for
1274 // POWER cores, but not optimal everywhere. For example, on the A2,
1275 // andi/andis have single-cycle latency whereas the rotate-and-mask
1276 // instructions take two cycles, and it would be better to bias toward
1277 // andi/andis in break-even cases.
1279 unsigned NumAndInsts = (unsigned) NeedsRotate +
1280 (unsigned) (ANDIMask != 0) +
1281 (unsigned) (ANDISMask != 0) +
1282 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1283 (unsigned) (bool) Res;
1285 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1286 " RL: " << VRI.RLAmt << ":" <<
1287 "\n\t\t\tisel using masking: " << NumAndInsts <<
1288 " using rotates: " << VRI.NumGroups << "\n");
1290 if (NumAndInsts >= VRI.NumGroups)
1293 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1295 if (InstCnt) *InstCnt += NumAndInsts;
1300 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1301 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1307 SDValue ANDIVal, ANDISVal;
1309 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1310 VRot, getI32Imm(ANDIMask)), 0);
1312 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1313 VRot, getI32Imm(ANDISMask)), 0);
1317 TotalVal = ANDISVal;
1321 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1322 ANDIVal, ANDISVal), 0);
1327 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1330 // Now, remove all groups with this underlying value and rotation
1332 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1333 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1334 I = BitGroups.erase(I);
1341 // Instruction selection for the 32-bit case.
1342 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1346 if (InstCnt) *InstCnt = 0;
1348 // Take care of cases that should use andi/andis first.
1349 SelectAndParts32(dl, Res, InstCnt);
1351 // If we've not yet selected a 'starting' instruction, and we have no zeros
1352 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1353 // number of groups), and start with this rotated value.
1354 if ((!HasZeros || LateMask) && !Res) {
1355 ValueRotInfo &VRI = ValueRotsVec[0];
1357 if (InstCnt) *InstCnt += 1;
1359 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1360 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1365 // Now, remove all groups with this underlying value and rotation factor.
1366 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1367 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1368 I = BitGroups.erase(I);
1374 if (InstCnt) *InstCnt += BitGroups.size();
1376 // Insert the other groups (one at a time).
1377 for (auto &BG : BitGroups) {
1380 { BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1381 getI32Imm(Bits.size() - BG.StartIdx - 1) };
1382 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1385 { Res, BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1386 getI32Imm(Bits.size() - BG.StartIdx - 1) };
1387 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1392 unsigned Mask = (unsigned) getZerosMask();
1394 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1395 assert((ANDIMask != 0 || ANDISMask != 0) &&
1396 "No set bits in zeros mask?");
1398 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1399 (unsigned) (ANDISMask != 0) +
1400 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1402 SDValue ANDIVal, ANDISVal;
1404 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1405 Res, getI32Imm(ANDIMask)), 0);
1407 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1408 Res, getI32Imm(ANDISMask)), 0);
1415 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1416 ANDIVal, ANDISVal), 0);
1419 return Res.getNode();
1422 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1423 unsigned MaskStart, unsigned MaskEnd,
1425 // In the notation used by the instructions, 'start' and 'end' are reversed
1426 // because bits are counted from high to low order.
1427 unsigned InstMaskStart = 64 - MaskEnd - 1,
1428 InstMaskEnd = 64 - MaskStart - 1;
1433 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1434 InstMaskEnd == 63 - RLAmt)
1440 // For 64-bit values, not all combinations of rotates and masks are
1441 // available. Produce one if it is available.
1442 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1443 unsigned MaskStart, unsigned MaskEnd,
1444 unsigned *InstCnt = nullptr) {
1445 // In the notation used by the instructions, 'start' and 'end' are reversed
1446 // because bits are counted from high to low order.
1447 unsigned InstMaskStart = 64 - MaskEnd - 1,
1448 InstMaskEnd = 64 - MaskStart - 1;
1450 if (InstCnt) *InstCnt += 1;
1453 // This rotation amount assumes that the lower 32 bits of the quantity
1454 // are replicated in the high 32 bits by the rotation operator (which is
1455 // done by rlwinm and friends).
1456 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1457 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1459 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1460 getI32Imm(InstMaskEnd - 32) };
1461 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1465 if (InstMaskEnd == 63) {
1467 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1468 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1471 if (InstMaskStart == 0) {
1473 { V, getI32Imm(RLAmt), getI32Imm(InstMaskEnd) };
1474 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1477 if (InstMaskEnd == 63 - RLAmt) {
1479 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1480 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1483 // We cannot do this with a single instruction, so we'll use two. The
1484 // problem is that we're not free to choose both a rotation amount and mask
1485 // start and end independently. We can choose an arbitrary mask start and
1486 // end, but then the rotation amount is fixed. Rotation, however, can be
1487 // inverted, and so by applying an "inverse" rotation first, we can get the
1489 if (InstCnt) *InstCnt += 1;
1491 // The rotation mask for the second instruction must be MaskStart.
1492 unsigned RLAmt2 = MaskStart;
1493 // The first instruction must rotate V so that the overall rotation amount
1495 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1497 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1498 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1501 // For 64-bit values, not all combinations of rotates and masks are
1502 // available. Produce a rotate-mask-and-insert if one is available.
1503 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1504 bool Repl32, unsigned MaskStart,
1505 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1506 // In the notation used by the instructions, 'start' and 'end' are reversed
1507 // because bits are counted from high to low order.
1508 unsigned InstMaskStart = 64 - MaskEnd - 1,
1509 InstMaskEnd = 64 - MaskStart - 1;
1511 if (InstCnt) *InstCnt += 1;
1514 // This rotation amount assumes that the lower 32 bits of the quantity
1515 // are replicated in the high 32 bits by the rotation operator (which is
1516 // done by rlwinm and friends).
1517 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1518 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1520 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1521 getI32Imm(InstMaskEnd - 32) };
1522 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1526 if (InstMaskEnd == 63 - RLAmt) {
1528 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1529 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1532 // We cannot do this with a single instruction, so we'll use two. The
1533 // problem is that we're not free to choose both a rotation amount and mask
1534 // start and end independently. We can choose an arbitrary mask start and
1535 // end, but then the rotation amount is fixed. Rotation, however, can be
1536 // inverted, and so by applying an "inverse" rotation first, we can get the
1538 if (InstCnt) *InstCnt += 1;
1540 // The rotation mask for the second instruction must be MaskStart.
1541 unsigned RLAmt2 = MaskStart;
1542 // The first instruction must rotate V so that the overall rotation amount
1544 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1546 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1547 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1550 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1551 if (BPermRewriterNoMasking)
1554 // The idea here is the same as in the 32-bit version, but with additional
1555 // complications from the fact that Repl32 might be true. Because we
1556 // aggressively convert bit groups to Repl32 form (which, for small
1557 // rotation factors, involves no other change), and then coalesce, it might
1558 // be the case that a single 64-bit masking operation could handle both
1559 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1560 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1561 // completely capture the new combined bit group.
1563 for (ValueRotInfo &VRI : ValueRotsVec) {
1566 // We need to add to the mask all bits from the associated bit groups.
1567 // If Repl32 is false, we need to add bits from bit groups that have
1568 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1569 // group is trivially convertable if it overlaps only with the lower 32
1570 // bits, and the group has not been coalesced.
1571 auto MatchingBG = [VRI](BitGroup &BG) {
1575 unsigned EffRLAmt = BG.RLAmt;
1576 if (!VRI.Repl32 && BG.Repl32) {
1577 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1578 !BG.Repl32Coalesced) {
1584 } else if (VRI.Repl32 != BG.Repl32) {
1588 if (VRI.RLAmt != EffRLAmt)
1594 for (auto &BG : BitGroups) {
1595 if (!MatchingBG(BG))
1598 if (BG.StartIdx <= BG.EndIdx) {
1599 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1600 Mask |= (UINT64_C(1) << i);
1602 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1603 Mask |= (UINT64_C(1) << i);
1604 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1605 Mask |= (UINT64_C(1) << i);
1609 // We can use the 32-bit andi/andis technique if the mask does not
1610 // require any higher-order bits. This can save an instruction compared
1611 // to always using the general 64-bit technique.
1612 bool Use32BitInsts = isUInt<32>(Mask);
1613 // Compute the masks for andi/andis that would be necessary.
1614 unsigned ANDIMask = (Mask & UINT16_MAX),
1615 ANDISMask = (Mask >> 16) & UINT16_MAX;
1617 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1619 unsigned NumAndInsts = (unsigned) NeedsRotate +
1620 (unsigned) (bool) Res;
1622 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1623 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1625 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1627 unsigned NumRLInsts = 0;
1628 bool FirstBG = true;
1629 for (auto &BG : BitGroups) {
1630 if (!MatchingBG(BG))
1633 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1638 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1639 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1640 "\n\t\t\tisel using masking: " << NumAndInsts <<
1641 " using rotates: " << NumRLInsts << "\n");
1643 // When we'd use andi/andis, we bias toward using the rotates (andi only
1644 // has a record form, and is cracked on POWER cores). However, when using
1645 // general 64-bit constant formation, bias toward the constant form,
1646 // because that exposes more opportunities for CSE.
1647 if (NumAndInsts > NumRLInsts)
1649 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1652 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1654 if (InstCnt) *InstCnt += NumAndInsts;
1657 // We actually need to generate a rotation if we have a non-zero rotation
1658 // factor or, in the Repl32 case, if we care about any of the
1659 // higher-order replicated bits. In the latter case, we generate a mask
1660 // backward so that it actually includes the entire 64 bits.
1661 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1662 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1663 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1668 if (Use32BitInsts) {
1669 assert((ANDIMask != 0 || ANDISMask != 0) &&
1670 "No set bits in mask when using 32-bit ands for 64-bit value");
1672 SDValue ANDIVal, ANDISVal;
1674 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1675 VRot, getI32Imm(ANDIMask)), 0);
1677 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1678 VRot, getI32Imm(ANDISMask)), 0);
1681 TotalVal = ANDISVal;
1685 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1686 ANDIVal, ANDISVal), 0);
1688 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1690 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1691 VRot, TotalVal), 0);
1697 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1700 // Now, remove all groups with this underlying value and rotation
1702 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1704 I = BitGroups.erase(I);
1711 // Instruction selection for the 64-bit case.
1712 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1716 if (InstCnt) *InstCnt = 0;
1718 // Take care of cases that should use andi/andis first.
1719 SelectAndParts64(dl, Res, InstCnt);
1721 // If we've not yet selected a 'starting' instruction, and we have no zeros
1722 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1723 // number of groups), and start with this rotated value.
1724 if ((!HasZeros || LateMask) && !Res) {
1725 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1726 // groups will come first, and so the VRI representing the largest number
1727 // of groups might not be first (it might be the first Repl32 groups).
1728 unsigned MaxGroupsIdx = 0;
1729 if (!ValueRotsVec[0].Repl32) {
1730 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1731 if (ValueRotsVec[i].Repl32) {
1732 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1738 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1739 bool NeedsRotate = false;
1742 } else if (VRI.Repl32) {
1743 for (auto &BG : BitGroups) {
1744 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1745 BG.Repl32 != VRI.Repl32)
1748 // We don't need a rotate if the bit group is confined to the lower
1750 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1759 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1760 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1765 // Now, remove all groups with this underlying value and rotation factor.
1767 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1768 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt && I->Repl32 == VRI.Repl32)
1769 I = BitGroups.erase(I);
1775 // Because 64-bit rotates are more flexible than inserts, we might have a
1776 // preference regarding which one we do first (to save one instruction).
1778 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1779 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1781 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1783 if (I != BitGroups.begin()) {
1786 BitGroups.insert(BitGroups.begin(), BG);
1793 // Insert the other groups (one at a time).
1794 for (auto &BG : BitGroups) {
1796 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1797 BG.EndIdx, InstCnt);
1799 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1800 BG.StartIdx, BG.EndIdx, InstCnt);
1804 uint64_t Mask = getZerosMask();
1806 // We can use the 32-bit andi/andis technique if the mask does not
1807 // require any higher-order bits. This can save an instruction compared
1808 // to always using the general 64-bit technique.
1809 bool Use32BitInsts = isUInt<32>(Mask);
1810 // Compute the masks for andi/andis that would be necessary.
1811 unsigned ANDIMask = (Mask & UINT16_MAX),
1812 ANDISMask = (Mask >> 16) & UINT16_MAX;
1814 if (Use32BitInsts) {
1815 assert((ANDIMask != 0 || ANDISMask != 0) &&
1816 "No set bits in mask when using 32-bit ands for 64-bit value");
1818 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1819 (unsigned) (ANDISMask != 0) +
1820 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1822 SDValue ANDIVal, ANDISVal;
1824 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1825 Res, getI32Imm(ANDIMask)), 0);
1827 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1828 Res, getI32Imm(ANDISMask)), 0);
1835 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1836 ANDIVal, ANDISVal), 0);
1838 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1840 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1842 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1847 return Res.getNode();
1850 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1851 // Fill in BitGroups.
1852 collectBitGroups(LateMask);
1853 if (BitGroups.empty())
1856 // For 64-bit values, figure out when we can use 32-bit instructions.
1857 if (Bits.size() == 64)
1858 assignRepl32BitGroups();
1860 // Fill in ValueRotsVec.
1861 collectValueRotInfo();
1863 if (Bits.size() == 32) {
1864 return Select32(N, LateMask, InstCnt);
1866 assert(Bits.size() == 64 && "Not 64 bits here?");
1867 return Select64(N, LateMask, InstCnt);
1873 SmallVector<ValueBit, 64> Bits;
1876 SmallVector<unsigned, 64> RLAmt;
1878 SmallVector<BitGroup, 16> BitGroups;
1880 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1881 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1883 SelectionDAG *CurDAG;
1886 BitPermutationSelector(SelectionDAG *DAG)
1889 // Here we try to match complex bit permutations into a set of
1890 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1891 // known to produce optimial code for common cases (like i32 byte swapping).
1892 SDNode *Select(SDNode *N) {
1893 Bits.resize(N->getValueType(0).getSizeInBits());
1894 if (!getValueBits(SDValue(N, 0), Bits))
1897 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1898 " selection for: ");
1899 DEBUG(N->dump(CurDAG));
1901 // Fill it RLAmt and set HasZeros.
1902 computeRotationAmounts();
1905 return Select(N, false);
1907 // We currently have two techniques for handling results with zeros: early
1908 // masking (the default) and late masking. Late masking is sometimes more
1909 // efficient, but because the structure of the bit groups is different, it
1910 // is hard to tell without generating both and comparing the results. With
1911 // late masking, we ignore zeros in the resulting value when inserting each
1912 // set of bit groups, and then mask in the zeros at the end. With early
1913 // masking, we only insert the non-zero parts of the result at every step.
1915 unsigned InstCnt, InstCntLateMask;
1916 DEBUG(dbgs() << "\tEarly masking:\n");
1917 SDNode *RN = Select(N, false, &InstCnt);
1918 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1920 DEBUG(dbgs() << "\tLate masking:\n");
1921 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1922 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1925 if (InstCnt <= InstCntLateMask) {
1926 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1930 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1934 } // anonymous namespace
1936 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1937 if (N->getValueType(0) != MVT::i32 &&
1938 N->getValueType(0) != MVT::i64)
1941 if (!UseBitPermRewriter)
1944 switch (N->getOpcode()) {
1951 BitPermutationSelector BPS(CurDAG);
1952 return BPS.Select(N);
1959 /// SelectCC - Select a comparison of the specified values with the specified
1960 /// condition code, returning the CR# of the expression.
1961 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1962 ISD::CondCode CC, SDLoc dl) {
1963 // Always select the LHS.
1966 if (LHS.getValueType() == MVT::i32) {
1968 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1969 if (isInt32Immediate(RHS, Imm)) {
1970 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1971 if (isUInt<16>(Imm))
1972 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1973 getI32Imm(Imm & 0xFFFF)), 0);
1974 // If this is a 16-bit signed immediate, fold it.
1975 if (isInt<16>((int)Imm))
1976 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1977 getI32Imm(Imm & 0xFFFF)), 0);
1979 // For non-equality comparisons, the default code would materialize the
1980 // constant, then compare against it, like this:
1982 // ori r2, r2, 22136
1984 // Since we are just comparing for equality, we can emit this instead:
1985 // xoris r0,r3,0x1234
1986 // cmplwi cr0,r0,0x5678
1988 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
1989 getI32Imm(Imm >> 16)), 0);
1990 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1991 getI32Imm(Imm & 0xFFFF)), 0);
1994 } else if (ISD::isUnsignedIntSetCC(CC)) {
1995 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
1996 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1997 getI32Imm(Imm & 0xFFFF)), 0);
2001 if (isIntS16Immediate(RHS, SImm))
2002 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2003 getI32Imm((int)SImm & 0xFFFF)),
2007 } else if (LHS.getValueType() == MVT::i64) {
2009 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2010 if (isInt64Immediate(RHS.getNode(), Imm)) {
2011 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2012 if (isUInt<16>(Imm))
2013 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2014 getI32Imm(Imm & 0xFFFF)), 0);
2015 // If this is a 16-bit signed immediate, fold it.
2017 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2018 getI32Imm(Imm & 0xFFFF)), 0);
2020 // For non-equality comparisons, the default code would materialize the
2021 // constant, then compare against it, like this:
2023 // ori r2, r2, 22136
2025 // Since we are just comparing for equality, we can emit this instead:
2026 // xoris r0,r3,0x1234
2027 // cmpldi cr0,r0,0x5678
2029 if (isUInt<32>(Imm)) {
2030 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2031 getI64Imm(Imm >> 16)), 0);
2032 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2033 getI64Imm(Imm & 0xFFFF)), 0);
2037 } else if (ISD::isUnsignedIntSetCC(CC)) {
2038 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2039 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2040 getI64Imm(Imm & 0xFFFF)), 0);
2044 if (isIntS16Immediate(RHS, SImm))
2045 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2046 getI64Imm(SImm & 0xFFFF)),
2050 } else if (LHS.getValueType() == MVT::f32) {
2053 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2054 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2056 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2059 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2065 llvm_unreachable("Should be lowered by legalize!");
2066 default: llvm_unreachable("Unknown condition!");
2068 case ISD::SETEQ: return PPC::PRED_EQ;
2070 case ISD::SETNE: return PPC::PRED_NE;
2072 case ISD::SETLT: return PPC::PRED_LT;
2074 case ISD::SETLE: return PPC::PRED_LE;
2076 case ISD::SETGT: return PPC::PRED_GT;
2078 case ISD::SETGE: return PPC::PRED_GE;
2079 case ISD::SETO: return PPC::PRED_NU;
2080 case ISD::SETUO: return PPC::PRED_UN;
2081 // These two are invalid for floating point. Assume we have int.
2082 case ISD::SETULT: return PPC::PRED_LT;
2083 case ISD::SETUGT: return PPC::PRED_GT;
2087 /// getCRIdxForSetCC - Return the index of the condition register field
2088 /// associated with the SetCC condition, and whether or not the field is
2089 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2090 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2093 default: llvm_unreachable("Unknown condition!");
2095 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2097 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2099 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2100 case ISD::SETUO: return 3; // Bit #3 = SETUO
2102 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2104 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2106 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2107 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2112 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2113 // These are invalid for floating point. Assume integer.
2114 case ISD::SETULT: return 0;
2115 case ISD::SETUGT: return 1;
2119 // getVCmpInst: return the vector compare instruction for the specified
2120 // vector type and condition code. Since this is for altivec specific code,
2121 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2122 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2123 bool HasVSX, bool &Swap, bool &Negate) {
2127 if (VecVT.isFloatingPoint()) {
2128 /* Handle some cases by swapping input operands. */
2130 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2131 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2132 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2133 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2134 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2135 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2138 /* Handle some cases by negating the result. */
2140 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2141 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2142 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2143 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2146 /* We have instructions implementing the remaining cases. */
2150 if (VecVT == MVT::v4f32)
2151 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2152 else if (VecVT == MVT::v2f64)
2153 return PPC::XVCMPEQDP;
2157 if (VecVT == MVT::v4f32)
2158 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2159 else if (VecVT == MVT::v2f64)
2160 return PPC::XVCMPGTDP;
2164 if (VecVT == MVT::v4f32)
2165 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2166 else if (VecVT == MVT::v2f64)
2167 return PPC::XVCMPGEDP;
2172 llvm_unreachable("Invalid floating-point vector compare condition");
2174 /* Handle some cases by swapping input operands. */
2176 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2177 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2178 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2179 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2182 /* Handle some cases by negating the result. */
2184 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2185 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2186 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2187 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2190 /* We have instructions implementing the remaining cases. */
2194 if (VecVT == MVT::v16i8)
2195 return PPC::VCMPEQUB;
2196 else if (VecVT == MVT::v8i16)
2197 return PPC::VCMPEQUH;
2198 else if (VecVT == MVT::v4i32)
2199 return PPC::VCMPEQUW;
2200 else if (VecVT == MVT::v2i64)
2201 return PPC::VCMPEQUD;
2204 if (VecVT == MVT::v16i8)
2205 return PPC::VCMPGTSB;
2206 else if (VecVT == MVT::v8i16)
2207 return PPC::VCMPGTSH;
2208 else if (VecVT == MVT::v4i32)
2209 return PPC::VCMPGTSW;
2210 else if (VecVT == MVT::v2i64)
2211 return PPC::VCMPGTSD;
2214 if (VecVT == MVT::v16i8)
2215 return PPC::VCMPGTUB;
2216 else if (VecVT == MVT::v8i16)
2217 return PPC::VCMPGTUH;
2218 else if (VecVT == MVT::v4i32)
2219 return PPC::VCMPGTUW;
2220 else if (VecVT == MVT::v2i64)
2221 return PPC::VCMPGTUD;
2226 llvm_unreachable("Invalid integer vector compare condition");
2230 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2233 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2234 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2235 bool isPPC64 = (PtrVT == MVT::i64);
2237 if (!PPCSubTarget->useCRBits() &&
2238 isInt32Immediate(N->getOperand(1), Imm)) {
2239 // We can codegen setcc op, imm very efficiently compared to a brcond.
2240 // Check for those cases here.
2243 SDValue Op = N->getOperand(0);
2247 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2248 SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
2249 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2254 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2255 Op, getI32Imm(~0U)), 0);
2256 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2260 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2261 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2265 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2266 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2267 SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2268 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2271 } else if (Imm == ~0U) { // setcc op, -1
2272 SDValue Op = N->getOperand(0);
2277 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2278 Op, getI32Imm(1)), 0);
2279 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2280 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2286 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2287 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2288 Op, getI32Imm(~0U));
2289 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2290 Op, SDValue(AD, 1));
2293 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2295 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2297 SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2298 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2301 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2302 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2304 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2311 SDValue LHS = N->getOperand(0);
2312 SDValue RHS = N->getOperand(1);
2314 // Altivec Vector compare instructions do not set any CR register by default and
2315 // vector compare operations return the same type as the operands.
2316 if (LHS.getValueType().isVector()) {
2317 if (PPCSubTarget->hasQPX())
2320 EVT VecVT = LHS.getValueType();
2322 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2323 PPCSubTarget->hasVSX(), Swap, Negate);
2325 std::swap(LHS, RHS);
2328 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2329 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2334 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2337 if (PPCSubTarget->useCRBits())
2341 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2342 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2345 // Force the ccreg into CR7.
2346 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2348 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2349 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2350 InFlag).getValue(1);
2352 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2355 SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
2356 getI32Imm(31), getI32Imm(31) };
2358 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2360 // Get the specified bit.
2362 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2363 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
2366 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2367 // Transfer memoperands.
2368 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2369 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2370 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2375 // Select - Convert the specified operand from a target-independent to a
2376 // target-specific node if it hasn't already been changed.
2377 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2379 if (N->isMachineOpcode()) {
2381 return nullptr; // Already selected.
2384 // In case any misguided DAG-level optimizations form an ADD with a
2385 // TargetConstant operand, crash here instead of miscompiling (by selecting
2386 // an r+r add instead of some kind of r+i add).
2387 if (N->getOpcode() == ISD::ADD &&
2388 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2389 llvm_unreachable("Invalid ADD with TargetConstant operand");
2391 // Try matching complex bit permutations before doing anything else.
2392 if (SDNode *NN = SelectBitPermutation(N))
2395 switch (N->getOpcode()) {
2398 case ISD::Constant: {
2399 if (N->getValueType(0) == MVT::i64)
2400 return SelectInt64(CurDAG, N);
2405 SDNode *SN = SelectSETCC(N);
2410 case PPCISD::GlobalBaseReg:
2411 return getGlobalBaseReg();
2413 case ISD::FrameIndex:
2414 return getFrameIndex(N, N);
2416 case PPCISD::MFOCRF: {
2417 SDValue InFlag = N->getOperand(1);
2418 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2419 N->getOperand(0), InFlag);
2422 case PPCISD::READ_TIME_BASE: {
2423 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2424 MVT::Other, N->getOperand(0));
2427 case PPCISD::SRA_ADDZE: {
2428 SDValue N0 = N->getOperand(0);
2430 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2431 getConstantIntValue(), N->getValueType(0));
2432 if (N->getValueType(0) == MVT::i64) {
2434 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2436 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2437 SDValue(Op, 0), SDValue(Op, 1));
2439 assert(N->getValueType(0) == MVT::i32 &&
2440 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2442 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2444 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2445 SDValue(Op, 0), SDValue(Op, 1));
2450 // Handle preincrement loads.
2451 LoadSDNode *LD = cast<LoadSDNode>(N);
2452 EVT LoadedVT = LD->getMemoryVT();
2454 // Normal loads are handled by code generated from the .td file.
2455 if (LD->getAddressingMode() != ISD::PRE_INC)
2458 SDValue Offset = LD->getOffset();
2459 if (Offset.getOpcode() == ISD::TargetConstant ||
2460 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2463 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2464 if (LD->getValueType(0) != MVT::i64) {
2465 // Handle PPC32 integer and normal FP loads.
2466 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2467 switch (LoadedVT.getSimpleVT().SimpleTy) {
2468 default: llvm_unreachable("Invalid PPC load type!");
2469 case MVT::f64: Opcode = PPC::LFDU; break;
2470 case MVT::f32: Opcode = PPC::LFSU; break;
2471 case MVT::i32: Opcode = PPC::LWZU; break;
2472 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2474 case MVT::i8: Opcode = PPC::LBZU; break;
2477 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2478 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2479 switch (LoadedVT.getSimpleVT().SimpleTy) {
2480 default: llvm_unreachable("Invalid PPC load type!");
2481 case MVT::i64: Opcode = PPC::LDU; break;
2482 case MVT::i32: Opcode = PPC::LWZU8; break;
2483 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2485 case MVT::i8: Opcode = PPC::LBZU8; break;
2489 SDValue Chain = LD->getChain();
2490 SDValue Base = LD->getBasePtr();
2491 SDValue Ops[] = { Offset, Base, Chain };
2492 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2493 LD->getValueType(0),
2494 PPCLowering->getPointerTy(),
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::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2505 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2506 case MVT::f64: Opcode = PPC::LFDUX; break;
2507 case MVT::f32: Opcode = PPC::LFSUX; break;
2508 case MVT::i32: Opcode = PPC::LWZUX; break;
2509 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2511 case MVT::i8: Opcode = PPC::LBZUX; break;
2514 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2515 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2516 "Invalid sext update load");
2517 switch (LoadedVT.getSimpleVT().SimpleTy) {
2518 default: llvm_unreachable("Invalid PPC load type!");
2519 case MVT::i64: Opcode = PPC::LDUX; break;
2520 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2521 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2523 case MVT::i8: Opcode = PPC::LBZUX8; break;
2527 SDValue Chain = LD->getChain();
2528 SDValue Base = LD->getBasePtr();
2529 SDValue Ops[] = { Base, Offset, Chain };
2530 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2531 LD->getValueType(0),
2532 PPCLowering->getPointerTy(),
2538 unsigned Imm, Imm2, SH, MB, ME;
2541 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2542 // with a mask, emit rlwinm
2543 if (isInt32Immediate(N->getOperand(1), Imm) &&
2544 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2545 SDValue Val = N->getOperand(0).getOperand(0);
2546 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2547 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2549 // If this is just a masked value where the input is not handled above, and
2550 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2551 if (isInt32Immediate(N->getOperand(1), Imm) &&
2552 isRunOfOnes(Imm, MB, ME) &&
2553 N->getOperand(0).getOpcode() != ISD::ROTL) {
2554 SDValue Val = N->getOperand(0);
2555 SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
2556 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2558 // If this is a 64-bit zero-extension mask, emit rldicl.
2559 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2561 SDValue Val = N->getOperand(0);
2562 MB = 64 - countTrailingOnes(Imm64);
2565 // If the operand is a logical right shift, we can fold it into this
2566 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2567 // for n <= mb. The right shift is really a left rotate followed by a
2568 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2570 if (Val.getOpcode() == ISD::SRL &&
2571 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2572 assert(Imm < 64 && "Illegal shift amount");
2573 Val = Val.getOperand(0);
2577 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
2578 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2580 // AND X, 0 -> 0, not "rlwinm 32".
2581 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2582 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2585 // ISD::OR doesn't get all the bitfield insertion fun.
2586 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2587 if (isInt32Immediate(N->getOperand(1), Imm) &&
2588 N->getOperand(0).getOpcode() == ISD::OR &&
2589 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2592 if (isRunOfOnes(Imm, MB, ME)) {
2593 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2594 N->getOperand(0).getOperand(1),
2595 getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
2596 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2600 // Other cases are autogenerated.
2604 if (N->getValueType(0) == MVT::i32)
2605 if (SDNode *I = SelectBitfieldInsert(N))
2609 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2610 isIntS16Immediate(N->getOperand(1), Imm)) {
2611 APInt LHSKnownZero, LHSKnownOne;
2612 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2614 // If this is equivalent to an add, then we can fold it with the
2615 // FrameIndex calculation.
2616 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2617 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2620 // Other cases are autogenerated.
2625 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2626 isIntS16Immediate(N->getOperand(1), Imm))
2627 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2632 unsigned Imm, SH, MB, ME;
2633 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2634 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2635 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2636 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2637 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2640 // Other cases are autogenerated.
2644 unsigned Imm, SH, MB, ME;
2645 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2646 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2647 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2648 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2649 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2652 // Other cases are autogenerated.
2655 // FIXME: Remove this once the ANDI glue bug is fixed:
2656 case PPCISD::ANDIo_1_EQ_BIT:
2657 case PPCISD::ANDIo_1_GT_BIT: {
2661 EVT InVT = N->getOperand(0).getValueType();
2662 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2663 "Invalid input type for ANDIo_1_EQ_BIT");
2665 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2666 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2668 CurDAG->getTargetConstant(1, InVT)), 0);
2669 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2671 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2672 PPC::sub_eq : PPC::sub_gt, MVT::i32);
2674 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2676 SDValue(AndI.getNode(), 1) /* glue */);
2678 case ISD::SELECT_CC: {
2679 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2680 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2681 bool isPPC64 = (PtrVT == MVT::i64);
2683 // If this is a select of i1 operands, we'll pattern match it.
2684 if (PPCSubTarget->useCRBits() &&
2685 N->getOperand(0).getValueType() == MVT::i1)
2688 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2690 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2691 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2692 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2693 if (N1C->isNullValue() && N3C->isNullValue() &&
2694 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2695 // FIXME: Implement this optzn for PPC64.
2696 N->getValueType(0) == MVT::i32) {
2698 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2699 N->getOperand(0), getI32Imm(~0U));
2700 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2701 SDValue(Tmp, 0), N->getOperand(0),
2705 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2707 if (N->getValueType(0) == MVT::i1) {
2708 // An i1 select is: (c & t) | (!c & f).
2710 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2714 default: llvm_unreachable("Invalid CC index");
2715 case 0: SRI = PPC::sub_lt; break;
2716 case 1: SRI = PPC::sub_gt; break;
2717 case 2: SRI = PPC::sub_eq; break;
2718 case 3: SRI = PPC::sub_un; break;
2721 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2723 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2725 SDValue C = Inv ? NotCCBit : CCBit,
2726 NotC = Inv ? CCBit : NotCCBit;
2728 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2729 C, N->getOperand(2)), 0);
2730 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2731 NotC, N->getOperand(3)), 0);
2733 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2736 unsigned BROpc = getPredicateForSetCC(CC);
2738 unsigned SelectCCOp;
2739 if (N->getValueType(0) == MVT::i32)
2740 SelectCCOp = PPC::SELECT_CC_I4;
2741 else if (N->getValueType(0) == MVT::i64)
2742 SelectCCOp = PPC::SELECT_CC_I8;
2743 else if (N->getValueType(0) == MVT::f32)
2744 SelectCCOp = PPC::SELECT_CC_F4;
2745 else if (N->getValueType(0) == MVT::f64)
2746 if (PPCSubTarget->hasVSX())
2747 SelectCCOp = PPC::SELECT_CC_VSFRC;
2749 SelectCCOp = PPC::SELECT_CC_F8;
2750 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2751 SelectCCOp = PPC::SELECT_CC_QFRC;
2752 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2753 SelectCCOp = PPC::SELECT_CC_QSRC;
2754 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2755 SelectCCOp = PPC::SELECT_CC_QBRC;
2756 else if (N->getValueType(0) == MVT::v2f64 ||
2757 N->getValueType(0) == MVT::v2i64)
2758 SelectCCOp = PPC::SELECT_CC_VSRC;
2760 SelectCCOp = PPC::SELECT_CC_VRRC;
2762 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2764 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2767 if (PPCSubTarget->hasVSX()) {
2768 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2769 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2773 case ISD::VECTOR_SHUFFLE:
2774 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2775 N->getValueType(0) == MVT::v2i64)) {
2776 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2778 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2779 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2782 for (int i = 0; i < 2; ++i)
2783 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2788 // For little endian, we must swap the input operands and adjust
2789 // the mask elements (reverse and invert them).
2790 if (PPCSubTarget->isLittleEndian()) {
2791 std::swap(Op1, Op2);
2792 unsigned tmp = DM[0];
2797 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
2799 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2800 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2801 isa<LoadSDNode>(Op1.getOperand(0))) {
2802 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2803 SDValue Base, Offset;
2805 if (LD->isUnindexed() &&
2806 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2807 SDValue Chain = LD->getChain();
2808 SDValue Ops[] = { Base, Offset, Chain };
2809 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2810 N->getValueType(0), Ops);
2814 SDValue Ops[] = { Op1, Op2, DMV };
2815 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2821 bool IsPPC64 = PPCSubTarget->isPPC64();
2822 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2823 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2824 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2825 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2828 case PPCISD::COND_BRANCH: {
2829 // Op #0 is the Chain.
2830 // Op #1 is the PPC::PRED_* number.
2832 // Op #3 is the Dest MBB
2833 // Op #4 is the Flag.
2834 // Prevent PPC::PRED_* from being selected into LI.
2836 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
2837 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2838 N->getOperand(0), N->getOperand(4) };
2839 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2842 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2843 unsigned PCC = getPredicateForSetCC(CC);
2845 if (N->getOperand(2).getValueType() == MVT::i1) {
2849 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2850 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2851 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2852 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2853 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2854 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2855 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2858 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2859 N->getOperand(Swap ? 3 : 2),
2860 N->getOperand(Swap ? 2 : 3)), 0);
2861 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2862 BitComp, N->getOperand(4), N->getOperand(0));
2865 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2866 SDValue Ops[] = { getI32Imm(PCC), CondCode,
2867 N->getOperand(4), N->getOperand(0) };
2868 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2871 // FIXME: Should custom lower this.
2872 SDValue Chain = N->getOperand(0);
2873 SDValue Target = N->getOperand(1);
2874 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2875 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2876 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2878 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2880 case PPCISD::TOC_ENTRY: {
2881 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2882 "Only supported for 64-bit ABI and 32-bit SVR4");
2883 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2884 SDValue GA = N->getOperand(0);
2885 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2886 MVT::i32, GA, N->getOperand(1)));
2889 // For medium and large code model, we generate two instructions as
2890 // described below. Otherwise we allow SelectCodeCommon to handle this,
2891 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2892 CodeModel::Model CModel = TM.getCodeModel();
2893 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2896 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2897 // If it is an externally defined symbol, a symbol with common linkage,
2898 // a non-local function address, or a jump table address, or if we are
2899 // generating code for large code model, we generate:
2900 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2901 // Otherwise we generate:
2902 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2903 SDValue GA = N->getOperand(0);
2904 SDValue TOCbase = N->getOperand(1);
2905 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2908 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2909 CModel == CodeModel::Large)
2910 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2911 MVT::i64, GA, SDValue(Tmp, 0)));
2913 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2914 const GlobalValue *GValue = G->getGlobal();
2915 if ((GValue->getType()->getElementType()->isFunctionTy() &&
2916 (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2917 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2918 GValue->hasAvailableExternallyLinkage())
2919 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2920 MVT::i64, GA, SDValue(Tmp, 0)));
2923 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2924 SDValue(Tmp, 0), GA);
2926 case PPCISD::PPC32_PICGOT: {
2927 // Generate a PIC-safe GOT reference.
2928 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2929 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2930 return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(), MVT::i32);
2932 case PPCISD::VADD_SPLAT: {
2933 // This expands into one of three sequences, depending on whether
2934 // the first operand is odd or even, positive or negative.
2935 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2936 isa<ConstantSDNode>(N->getOperand(1)) &&
2937 "Invalid operand on VADD_SPLAT!");
2939 int Elt = N->getConstantOperandVal(0);
2940 int EltSize = N->getConstantOperandVal(1);
2941 unsigned Opc1, Opc2, Opc3;
2945 Opc1 = PPC::VSPLTISB;
2946 Opc2 = PPC::VADDUBM;
2947 Opc3 = PPC::VSUBUBM;
2949 } else if (EltSize == 2) {
2950 Opc1 = PPC::VSPLTISH;
2951 Opc2 = PPC::VADDUHM;
2952 Opc3 = PPC::VSUBUHM;
2955 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2956 Opc1 = PPC::VSPLTISW;
2957 Opc2 = PPC::VADDUWM;
2958 Opc3 = PPC::VSUBUWM;
2962 if ((Elt & 1) == 0) {
2963 // Elt is even, in the range [-32,-18] + [16,30].
2965 // Convert: VADD_SPLAT elt, size
2966 // Into: tmp = VSPLTIS[BHW] elt
2967 // VADDU[BHW]M tmp, tmp
2968 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2969 SDValue EltVal = getI32Imm(Elt >> 1);
2970 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2971 SDValue TmpVal = SDValue(Tmp, 0);
2972 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2974 } else if (Elt > 0) {
2975 // Elt is odd and positive, in the range [17,31].
2977 // Convert: VADD_SPLAT elt, size
2978 // Into: tmp1 = VSPLTIS[BHW] elt-16
2979 // tmp2 = VSPLTIS[BHW] -16
2980 // VSUBU[BHW]M tmp1, tmp2
2981 SDValue EltVal = getI32Imm(Elt - 16);
2982 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2983 EltVal = getI32Imm(-16);
2984 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2985 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2989 // Elt is odd and negative, in the range [-31,-17].
2991 // Convert: VADD_SPLAT elt, size
2992 // Into: tmp1 = VSPLTIS[BHW] elt+16
2993 // tmp2 = VSPLTIS[BHW] -16
2994 // VADDU[BHW]M tmp1, tmp2
2995 SDValue EltVal = getI32Imm(Elt + 16);
2996 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2997 EltVal = getI32Imm(-16);
2998 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2999 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3005 return SelectCode(N);
3008 // If the target supports the cmpb instruction, do the idiom recognition here.
3009 // We don't do this as a DAG combine because we don't want to do it as nodes
3010 // are being combined (because we might miss part of the eventual idiom). We
3011 // don't want to do it during instruction selection because we want to reuse
3012 // the logic for lowering the masking operations already part of the
3013 // instruction selector.
3014 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3017 assert(N->getOpcode() == ISD::OR &&
3018 "Only OR nodes are supported for CMPB");
3021 if (!PPCSubTarget->hasCMPB())
3024 if (N->getValueType(0) != MVT::i32 &&
3025 N->getValueType(0) != MVT::i64)
3028 EVT VT = N->getValueType(0);
3031 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3032 uint64_t Mask = 0, Alt = 0;
3034 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3035 uint64_t &Mask, uint64_t &Alt,
3036 SDValue &LHS, SDValue &RHS) {
3037 if (O.getOpcode() != ISD::SELECT_CC)
3039 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3041 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3042 !isa<ConstantSDNode>(O.getOperand(3)))
3045 uint64_t PM = O.getConstantOperandVal(2);
3046 uint64_t PAlt = O.getConstantOperandVal(3);
3047 for (b = 0; b < 8; ++b) {
3048 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3049 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3058 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3059 O.getConstantOperandVal(1) != 0) {
3060 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3061 if (Op0.getOpcode() == ISD::TRUNCATE)
3062 Op0 = Op0.getOperand(0);
3063 if (Op1.getOpcode() == ISD::TRUNCATE)
3064 Op1 = Op1.getOperand(0);
3066 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3067 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3068 isa<ConstantSDNode>(Op0.getOperand(1))) {
3070 unsigned Bits = Op0.getValueType().getSizeInBits();
3073 if (Op0.getConstantOperandVal(1) != Bits-8)
3076 LHS = Op0.getOperand(0);
3077 RHS = Op1.getOperand(0);
3081 // When we have small integers (i16 to be specific), the form present
3082 // post-legalization uses SETULT in the SELECT_CC for the
3083 // higher-order byte, depending on the fact that the
3084 // even-higher-order bytes are known to all be zero, for example:
3085 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3086 // (so when the second byte is the same, because all higher-order
3087 // bits from bytes 3 and 4 are known to be zero, the result of the
3088 // xor can be at most 255)
3089 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3090 isa<ConstantSDNode>(O.getOperand(1))) {
3092 uint64_t ULim = O.getConstantOperandVal(1);
3093 if (ULim != (UINT64_C(1) << b*8))
3096 // Now we need to make sure that the upper bytes are known to be
3098 unsigned Bits = Op0.getValueType().getSizeInBits();
3099 if (!CurDAG->MaskedValueIsZero(Op0,
3100 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3103 LHS = Op0.getOperand(0);
3104 RHS = Op0.getOperand(1);
3111 if (CC != ISD::SETEQ)
3114 SDValue Op = O.getOperand(0);
3115 if (Op.getOpcode() == ISD::AND) {
3116 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3118 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3121 SDValue XOR = Op.getOperand(0);
3122 if (XOR.getOpcode() == ISD::TRUNCATE)
3123 XOR = XOR.getOperand(0);
3124 if (XOR.getOpcode() != ISD::XOR)
3127 LHS = XOR.getOperand(0);
3128 RHS = XOR.getOperand(1);
3130 } else if (Op.getOpcode() == ISD::SRL) {
3131 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3133 unsigned Bits = Op.getValueType().getSizeInBits();
3136 if (Op.getConstantOperandVal(1) != Bits-8)
3139 SDValue XOR = Op.getOperand(0);
3140 if (XOR.getOpcode() == ISD::TRUNCATE)
3141 XOR = XOR.getOperand(0);
3142 if (XOR.getOpcode() != ISD::XOR)
3145 LHS = XOR.getOperand(0);
3146 RHS = XOR.getOperand(1);
3153 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3154 while (!Queue.empty()) {
3155 SDValue V = Queue.pop_back_val();
3157 for (const SDValue &O : V.getNode()->ops()) {
3159 uint64_t M = 0, A = 0;
3161 if (O.getOpcode() == ISD::OR) {
3163 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3167 BytesFound[b] = true;
3170 } else if ((LHS == ORHS && RHS == OLHS) ||
3171 (RHS == ORHS && LHS == OLHS)) {
3172 BytesFound[b] = true;
3184 unsigned LastB = 0, BCnt = 0;
3185 for (unsigned i = 0; i < 8; ++i)
3186 if (BytesFound[LastB]) {
3191 if (!LastB || BCnt < 2)
3194 // Because we'll be zero-extending the output anyway if don't have a specific
3195 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3196 if (LHS.getValueType() != VT) {
3197 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3198 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3201 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3203 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3204 if (NonTrivialMask && !Alt) {
3205 // Res = Mask & CMPB
3206 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, CurDAG->getConstant(Mask, VT));
3208 // Res = (CMPB & Mask) | (~CMPB & Alt)
3209 // Which, as suggested here:
3210 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3211 // can be written as:
3212 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3213 // useful because the (Alt ^ Mask) can be pre-computed.
3214 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3215 CurDAG->getConstant(Mask ^ Alt, VT));
3216 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, CurDAG->getConstant(Alt, VT));
3222 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3223 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3224 // involves constant materialization of a 0 or a 1 or both. If the result of
3225 // the extension is then operated upon by some operator that can be constant
3226 // folded with a constant 0 or 1, and that constant can be materialized using
3227 // only one instruction (like a zero or one), then we should fold in those
3228 // operations with the select.
3229 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3230 if (!PPCSubTarget->useCRBits())
3233 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3234 N->getOpcode() != ISD::SIGN_EXTEND &&
3235 N->getOpcode() != ISD::ANY_EXTEND)
3238 if (N->getOperand(0).getValueType() != MVT::i1)
3241 if (!N->hasOneUse())
3245 EVT VT = N->getValueType(0);
3246 SDValue Cond = N->getOperand(0);
3248 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, VT);
3249 SDValue ConstFalse = CurDAG->getConstant(0, VT);
3252 SDNode *User = *N->use_begin();
3253 if (User->getNumOperands() != 2)
3256 auto TryFold = [this, N, User](SDValue Val) {
3257 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3258 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3259 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3261 return CurDAG->FoldConstantArithmetic(User->getOpcode(),
3262 User->getValueType(0),
3263 O0.getNode(), O1.getNode());
3266 SDValue TrueRes = TryFold(ConstTrue);
3269 SDValue FalseRes = TryFold(ConstFalse);
3273 // For us to materialize these using one instruction, we must be able to
3274 // represent them as signed 16-bit integers.
3275 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3276 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3277 if (!isInt<16>(True) || !isInt<16>(False))
3280 // We can replace User with a new SELECT node, and try again to see if we
3281 // can fold the select with its user.
3282 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3284 ConstTrue = TrueRes;
3285 ConstFalse = FalseRes;
3286 } while (N->hasOneUse());
3289 void PPCDAGToDAGISel::PreprocessISelDAG() {
3290 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3293 bool MadeChange = false;
3294 while (Position != CurDAG->allnodes_begin()) {
3295 SDNode *N = --Position;
3300 switch (N->getOpcode()) {
3303 Res = combineToCMPB(N);
3308 foldBoolExts(Res, N);
3311 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3312 DEBUG(N->dump(CurDAG));
3313 DEBUG(dbgs() << "\nNew: ");
3314 DEBUG(Res.getNode()->dump(CurDAG));
3315 DEBUG(dbgs() << "\n");
3317 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3323 CurDAG->RemoveDeadNodes();
3326 /// PostprocessISelDAG - Perform some late peephole optimizations
3327 /// on the DAG representation.
3328 void PPCDAGToDAGISel::PostprocessISelDAG() {
3330 // Skip peepholes at -O0.
3331 if (TM.getOptLevel() == CodeGenOpt::None)
3336 PeepholePPC64ZExt();
3339 // Check if all users of this node will become isel where the second operand
3340 // is the constant zero. If this is so, and if we can negate the condition,
3341 // then we can flip the true and false operands. This will allow the zero to
3342 // be folded with the isel so that we don't need to materialize a register
3344 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3345 // If we're not using isel, then this does not matter.
3346 if (!PPCSubTarget->hasISEL())
3349 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3352 if (!User->isMachineOpcode())
3354 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3355 User->getMachineOpcode() != PPC::SELECT_I8)
3358 SDNode *Op2 = User->getOperand(2).getNode();
3359 if (!Op2->isMachineOpcode())
3362 if (Op2->getMachineOpcode() != PPC::LI &&
3363 Op2->getMachineOpcode() != PPC::LI8)
3366 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3370 if (!C->isNullValue())
3377 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3378 SmallVector<SDNode *, 4> ToReplace;
3379 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3382 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3383 User->getMachineOpcode() == PPC::SELECT_I8) &&
3384 "Must have all select users");
3385 ToReplace.push_back(User);
3388 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3389 UE = ToReplace.end(); UI != UE; ++UI) {
3392 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3393 User->getValueType(0), User->getOperand(0),
3394 User->getOperand(2),
3395 User->getOperand(1));
3397 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3398 DEBUG(User->dump(CurDAG));
3399 DEBUG(dbgs() << "\nNew: ");
3400 DEBUG(ResNode->dump(CurDAG));
3401 DEBUG(dbgs() << "\n");
3403 ReplaceUses(User, ResNode);
3407 void PPCDAGToDAGISel::PeepholeCROps() {
3411 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3412 E = CurDAG->allnodes_end(); I != E; ++I) {
3413 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3414 if (!MachineNode || MachineNode->use_empty())
3416 SDNode *ResNode = MachineNode;
3418 bool Op1Set = false, Op1Unset = false,
3420 Op2Set = false, Op2Unset = false,
3423 unsigned Opcode = MachineNode->getMachineOpcode();
3434 SDValue Op = MachineNode->getOperand(1);
3435 if (Op.isMachineOpcode()) {
3436 if (Op.getMachineOpcode() == PPC::CRSET)
3438 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3440 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3441 Op.getOperand(0) == Op.getOperand(1))
3447 case PPC::SELECT_I4:
3448 case PPC::SELECT_I8:
3449 case PPC::SELECT_F4:
3450 case PPC::SELECT_F8:
3451 case PPC::SELECT_QFRC:
3452 case PPC::SELECT_QSRC:
3453 case PPC::SELECT_QBRC:
3454 case PPC::SELECT_VRRC:
3455 case PPC::SELECT_VSFRC:
3456 case PPC::SELECT_VSRC: {
3457 SDValue Op = MachineNode->getOperand(0);
3458 if (Op.isMachineOpcode()) {
3459 if (Op.getMachineOpcode() == PPC::CRSET)
3461 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3463 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3464 Op.getOperand(0) == Op.getOperand(1))
3471 bool SelectSwap = false;
3475 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3477 ResNode = MachineNode->getOperand(0).getNode();
3480 ResNode = MachineNode->getOperand(1).getNode();
3483 ResNode = MachineNode->getOperand(0).getNode();
3484 else if (Op1Unset || Op2Unset)
3485 // x & 0 = 0 & y = 0
3486 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3489 // ~x & y = andc(y, x)
3490 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3491 MVT::i1, MachineNode->getOperand(1),
3492 MachineNode->getOperand(0).
3495 // x & ~y = andc(x, y)
3496 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3497 MVT::i1, MachineNode->getOperand(0),
3498 MachineNode->getOperand(1).
3500 else if (AllUsersSelectZero(MachineNode))
3501 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3502 MVT::i1, MachineNode->getOperand(0),
3503 MachineNode->getOperand(1)),
3507 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3508 // nand(x, x) -> nor(x, x)
3509 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3510 MVT::i1, MachineNode->getOperand(0),
3511 MachineNode->getOperand(0));
3513 // nand(1, y) -> nor(y, y)
3514 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3515 MVT::i1, MachineNode->getOperand(1),
3516 MachineNode->getOperand(1));
3518 // nand(x, 1) -> nor(x, x)
3519 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3520 MVT::i1, MachineNode->getOperand(0),
3521 MachineNode->getOperand(0));
3522 else if (Op1Unset || Op2Unset)
3523 // nand(x, 0) = nand(0, y) = 1
3524 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3527 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3528 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3529 MVT::i1, MachineNode->getOperand(0).
3531 MachineNode->getOperand(1));
3533 // nand(x, ~y) = ~x | y = orc(y, x)
3534 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3535 MVT::i1, MachineNode->getOperand(1).
3537 MachineNode->getOperand(0));
3538 else if (AllUsersSelectZero(MachineNode))
3539 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3540 MVT::i1, MachineNode->getOperand(0),
3541 MachineNode->getOperand(1)),
3545 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3547 ResNode = MachineNode->getOperand(0).getNode();
3548 else if (Op1Set || Op2Set)
3549 // x | 1 = 1 | y = 1
3550 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3554 ResNode = MachineNode->getOperand(1).getNode();
3557 ResNode = MachineNode->getOperand(0).getNode();
3559 // ~x | y = orc(y, x)
3560 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3561 MVT::i1, MachineNode->getOperand(1),
3562 MachineNode->getOperand(0).
3565 // x | ~y = orc(x, y)
3566 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3567 MVT::i1, MachineNode->getOperand(0),
3568 MachineNode->getOperand(1).
3570 else if (AllUsersSelectZero(MachineNode))
3571 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3572 MVT::i1, MachineNode->getOperand(0),
3573 MachineNode->getOperand(1)),
3577 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3579 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3582 // xor(1, y) -> nor(y, y)
3583 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3584 MVT::i1, MachineNode->getOperand(1),
3585 MachineNode->getOperand(1));
3587 // xor(x, 1) -> nor(x, x)
3588 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3589 MVT::i1, MachineNode->getOperand(0),
3590 MachineNode->getOperand(0));
3593 ResNode = MachineNode->getOperand(1).getNode();
3596 ResNode = MachineNode->getOperand(0).getNode();
3598 // xor(~x, y) = eqv(x, y)
3599 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3600 MVT::i1, MachineNode->getOperand(0).
3602 MachineNode->getOperand(1));
3604 // xor(x, ~y) = eqv(x, y)
3605 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3606 MVT::i1, MachineNode->getOperand(0),
3607 MachineNode->getOperand(1).
3609 else if (AllUsersSelectZero(MachineNode))
3610 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3611 MVT::i1, MachineNode->getOperand(0),
3612 MachineNode->getOperand(1)),
3616 if (Op1Set || Op2Set)
3618 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3621 // nor(0, y) = ~y -> nor(y, y)
3622 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3623 MVT::i1, MachineNode->getOperand(1),
3624 MachineNode->getOperand(1));
3627 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3628 MVT::i1, MachineNode->getOperand(0),
3629 MachineNode->getOperand(0));
3631 // nor(~x, y) = andc(x, y)
3632 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3633 MVT::i1, MachineNode->getOperand(0).
3635 MachineNode->getOperand(1));
3637 // nor(x, ~y) = andc(y, x)
3638 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3639 MVT::i1, MachineNode->getOperand(1).
3641 MachineNode->getOperand(0));
3642 else if (AllUsersSelectZero(MachineNode))
3643 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3644 MVT::i1, MachineNode->getOperand(0),
3645 MachineNode->getOperand(1)),
3649 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3651 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3655 ResNode = MachineNode->getOperand(1).getNode();
3658 ResNode = MachineNode->getOperand(0).getNode();
3660 // eqv(0, y) = ~y -> nor(y, y)
3661 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3662 MVT::i1, MachineNode->getOperand(1),
3663 MachineNode->getOperand(1));
3666 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3667 MVT::i1, MachineNode->getOperand(0),
3668 MachineNode->getOperand(0));
3670 // eqv(~x, y) = xor(x, y)
3671 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3672 MVT::i1, MachineNode->getOperand(0).
3674 MachineNode->getOperand(1));
3676 // eqv(x, ~y) = xor(x, y)
3677 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3678 MVT::i1, MachineNode->getOperand(0),
3679 MachineNode->getOperand(1).
3681 else if (AllUsersSelectZero(MachineNode))
3682 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3683 MVT::i1, MachineNode->getOperand(0),
3684 MachineNode->getOperand(1)),
3688 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3690 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3694 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3695 MVT::i1, MachineNode->getOperand(1),
3696 MachineNode->getOperand(1));
3697 else if (Op1Unset || Op2Set)
3698 // andc(0, y) = andc(x, 1) = 0
3699 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3703 ResNode = MachineNode->getOperand(0).getNode();
3705 // andc(~x, y) = ~(x | y) = nor(x, y)
3706 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3707 MVT::i1, MachineNode->getOperand(0).
3709 MachineNode->getOperand(1));
3711 // andc(x, ~y) = x & y
3712 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3713 MVT::i1, MachineNode->getOperand(0),
3714 MachineNode->getOperand(1).
3716 else if (AllUsersSelectZero(MachineNode))
3717 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3718 MVT::i1, MachineNode->getOperand(1),
3719 MachineNode->getOperand(0)),
3723 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3725 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3727 else if (Op1Set || Op2Unset)
3728 // orc(1, y) = orc(x, 0) = 1
3729 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3733 ResNode = MachineNode->getOperand(0).getNode();
3736 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3737 MVT::i1, MachineNode->getOperand(1),
3738 MachineNode->getOperand(1));
3740 // orc(~x, y) = ~(x & y) = nand(x, y)
3741 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3742 MVT::i1, MachineNode->getOperand(0).
3744 MachineNode->getOperand(1));
3746 // orc(x, ~y) = x | y
3747 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3748 MVT::i1, MachineNode->getOperand(0),
3749 MachineNode->getOperand(1).
3751 else if (AllUsersSelectZero(MachineNode))
3752 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3753 MVT::i1, MachineNode->getOperand(1),
3754 MachineNode->getOperand(0)),
3757 case PPC::SELECT_I4:
3758 case PPC::SELECT_I8:
3759 case PPC::SELECT_F4:
3760 case PPC::SELECT_F8:
3761 case PPC::SELECT_QFRC:
3762 case PPC::SELECT_QSRC:
3763 case PPC::SELECT_QBRC:
3764 case PPC::SELECT_VRRC:
3765 case PPC::SELECT_VSFRC:
3766 case PPC::SELECT_VSRC:
3768 ResNode = MachineNode->getOperand(1).getNode();
3770 ResNode = MachineNode->getOperand(2).getNode();
3772 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3774 MachineNode->getValueType(0),
3775 MachineNode->getOperand(0).
3777 MachineNode->getOperand(2),
3778 MachineNode->getOperand(1));
3783 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3787 MachineNode->getOperand(0).
3789 MachineNode->getOperand(1),
3790 MachineNode->getOperand(2));
3791 // FIXME: Handle Op1Set, Op1Unset here too.
3795 // If we're inverting this node because it is used only by selects that
3796 // we'd like to swap, then swap the selects before the node replacement.
3798 SwapAllSelectUsers(MachineNode);
3800 if (ResNode != MachineNode) {
3801 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3802 DEBUG(MachineNode->dump(CurDAG));
3803 DEBUG(dbgs() << "\nNew: ");
3804 DEBUG(ResNode->dump(CurDAG));
3805 DEBUG(dbgs() << "\n");
3807 ReplaceUses(MachineNode, ResNode);
3812 CurDAG->RemoveDeadNodes();
3813 } while (IsModified);
3816 // Gather the set of 32-bit operations that are known to have their
3817 // higher-order 32 bits zero, where ToPromote contains all such operations.
3818 static bool PeepholePPC64ZExtGather(SDValue Op32,
3819 SmallPtrSetImpl<SDNode *> &ToPromote) {
3820 if (!Op32.isMachineOpcode())
3823 // First, check for the "frontier" instructions (those that will clear the
3824 // higher-order 32 bits.
3826 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3827 // around. If it does not, then these instructions will clear the
3828 // higher-order bits.
3829 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3830 Op32.getMachineOpcode() == PPC::RLWNM) &&
3831 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3832 ToPromote.insert(Op32.getNode());
3836 // SLW and SRW always clear the higher-order bits.
3837 if (Op32.getMachineOpcode() == PPC::SLW ||
3838 Op32.getMachineOpcode() == PPC::SRW) {
3839 ToPromote.insert(Op32.getNode());
3843 // For LI and LIS, we need the immediate to be positive (so that it is not
3845 if (Op32.getMachineOpcode() == PPC::LI ||
3846 Op32.getMachineOpcode() == PPC::LIS) {
3847 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3850 ToPromote.insert(Op32.getNode());
3854 // LHBRX and LWBRX always clear the higher-order bits.
3855 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3856 Op32.getMachineOpcode() == PPC::LWBRX) {
3857 ToPromote.insert(Op32.getNode());
3861 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3862 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3863 ToPromote.insert(Op32.getNode());
3867 // Next, check for those instructions we can look through.
3869 // Assuming the mask does not wrap around, then the higher-order bits are
3870 // taken directly from the first operand.
3871 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3872 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3873 SmallPtrSet<SDNode *, 16> ToPromote1;
3874 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3877 ToPromote.insert(Op32.getNode());
3878 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3882 // For OR, the higher-order bits are zero if that is true for both operands.
3883 // For SELECT_I4, the same is true (but the relevant operand numbers are
3885 if (Op32.getMachineOpcode() == PPC::OR ||
3886 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3887 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3888 SmallPtrSet<SDNode *, 16> ToPromote1;
3889 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3891 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3894 ToPromote.insert(Op32.getNode());
3895 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3899 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3900 // zero, and also for the constant to be positive (so that it is not sign
3902 if (Op32.getMachineOpcode() == PPC::ORI ||
3903 Op32.getMachineOpcode() == PPC::ORIS) {
3904 SmallPtrSet<SDNode *, 16> ToPromote1;
3905 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3907 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3910 ToPromote.insert(Op32.getNode());
3911 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3915 // The higher-order bits of AND are zero if that is true for at least one of
3917 if (Op32.getMachineOpcode() == PPC::AND) {
3918 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3920 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3922 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3923 if (!Op0OK && !Op1OK)
3926 ToPromote.insert(Op32.getNode());
3929 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3932 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3937 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3938 // of the first operand, or if the second operand is positive (so that it is
3939 // not sign extended).
3940 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3941 Op32.getMachineOpcode() == PPC::ANDISo) {
3942 SmallPtrSet<SDNode *, 16> ToPromote1;
3944 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3945 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3946 if (!Op0OK && !Op1OK)
3949 ToPromote.insert(Op32.getNode());
3952 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3960 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3961 if (!PPCSubTarget->isPPC64())
3964 // When we zero-extend from i32 to i64, we use a pattern like this:
3965 // def : Pat<(i64 (zext i32:$in)),
3966 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3968 // There are several 32-bit shift/rotate instructions, however, that will
3969 // clear the higher-order bits of their output, rendering the RLDICL
3970 // unnecessary. When that happens, we remove it here, and redefine the
3971 // relevant 32-bit operation to be a 64-bit operation.
3973 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3976 bool MadeChange = false;
3977 while (Position != CurDAG->allnodes_begin()) {
3978 SDNode *N = --Position;
3979 // Skip dead nodes and any non-machine opcodes.
3980 if (N->use_empty() || !N->isMachineOpcode())
3983 if (N->getMachineOpcode() != PPC::RLDICL)
3986 if (N->getConstantOperandVal(1) != 0 ||
3987 N->getConstantOperandVal(2) != 32)
3990 SDValue ISR = N->getOperand(0);
3991 if (!ISR.isMachineOpcode() ||
3992 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3995 if (!ISR.hasOneUse())
3998 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4001 SDValue IDef = ISR.getOperand(0);
4002 if (!IDef.isMachineOpcode() ||
4003 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4006 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4007 // can get rid of it.
4009 SDValue Op32 = ISR->getOperand(1);
4010 if (!Op32.isMachineOpcode())
4013 // There are some 32-bit instructions that always clear the high-order 32
4014 // bits, there are also some instructions (like AND) that we can look
4016 SmallPtrSet<SDNode *, 16> ToPromote;
4017 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4020 // If the ToPromote set contains nodes that have uses outside of the set
4021 // (except for the original INSERT_SUBREG), then abort the transformation.
4022 bool OutsideUse = false;
4023 for (SDNode *PN : ToPromote) {
4024 for (SDNode *UN : PN->uses()) {
4025 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4039 // We now know that this zero extension can be removed by promoting to
4040 // nodes in ToPromote to 64-bit operations, where for operations in the
4041 // frontier of the set, we need to insert INSERT_SUBREGs for their
4043 for (SDNode *PN : ToPromote) {
4045 switch (PN->getMachineOpcode()) {
4047 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4048 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4049 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4050 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4051 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4052 case PPC::LI: NewOpcode = PPC::LI8; break;
4053 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4054 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4055 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4056 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4057 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4058 case PPC::OR: NewOpcode = PPC::OR8; break;
4059 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4060 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4061 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4062 case PPC::AND: NewOpcode = PPC::AND8; break;
4063 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4064 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4067 // Note: During the replacement process, the nodes will be in an
4068 // inconsistent state (some instructions will have operands with values
4069 // of the wrong type). Once done, however, everything should be right
4072 SmallVector<SDValue, 4> Ops;
4073 for (const SDValue &V : PN->ops()) {
4074 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4075 !isa<ConstantSDNode>(V)) {
4076 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4078 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4079 ISR.getNode()->getVTList(), ReplOpOps);
4080 Ops.push_back(SDValue(ReplOp, 0));
4086 // Because all to-be-promoted nodes only have users that are other
4087 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4088 // the i32 result value type with i64.
4090 SmallVector<EVT, 2> NewVTs;
4091 SDVTList VTs = PN->getVTList();
4092 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4093 if (VTs.VTs[i] == MVT::i32)
4094 NewVTs.push_back(MVT::i64);
4096 NewVTs.push_back(VTs.VTs[i]);
4098 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4099 DEBUG(PN->dump(CurDAG));
4101 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4103 DEBUG(dbgs() << "\nNew: ");
4104 DEBUG(PN->dump(CurDAG));
4105 DEBUG(dbgs() << "\n");
4108 // Now we replace the original zero extend and its associated INSERT_SUBREG
4109 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4112 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4113 DEBUG(N->dump(CurDAG));
4114 DEBUG(dbgs() << "\nNew: ");
4115 DEBUG(Op32.getNode()->dump(CurDAG));
4116 DEBUG(dbgs() << "\n");
4118 ReplaceUses(N, Op32.getNode());
4122 CurDAG->RemoveDeadNodes();
4125 void PPCDAGToDAGISel::PeepholePPC64() {
4126 // These optimizations are currently supported only for 64-bit SVR4.
4127 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4130 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4133 while (Position != CurDAG->allnodes_begin()) {
4134 SDNode *N = --Position;
4135 // Skip dead nodes and any non-machine opcodes.
4136 if (N->use_empty() || !N->isMachineOpcode())
4140 unsigned StorageOpcode = N->getMachineOpcode();
4142 switch (StorageOpcode) {
4173 // If this is a load or store with a zero offset, we may be able to
4174 // fold an add-immediate into the memory operation.
4175 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
4176 N->getConstantOperandVal(FirstOp) != 0)
4179 SDValue Base = N->getOperand(FirstOp + 1);
4180 if (!Base.isMachineOpcode())
4184 bool ReplaceFlags = true;
4186 // When the feeding operation is an add-immediate of some sort,
4187 // determine whether we need to add relocation information to the
4188 // target flags on the immediate operand when we fold it into the
4189 // load instruction.
4191 // For something like ADDItocL, the relocation information is
4192 // inferred from the opcode; when we process it in the AsmPrinter,
4193 // we add the necessary relocation there. A load, though, can receive
4194 // relocation from various flavors of ADDIxxx, so we need to carry
4195 // the relocation information in the target flags.
4196 switch (Base.getMachineOpcode()) {
4201 // In some cases (such as TLS) the relocation information
4202 // is already in place on the operand, so copying the operand
4204 ReplaceFlags = false;
4205 // For these cases, the immediate may not be divisible by 4, in
4206 // which case the fold is illegal for DS-form instructions. (The
4207 // other cases provide aligned addresses and are always safe.)
4208 if ((StorageOpcode == PPC::LWA ||
4209 StorageOpcode == PPC::LD ||
4210 StorageOpcode == PPC::STD) &&
4211 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4212 Base.getConstantOperandVal(1) % 4 != 0))
4215 case PPC::ADDIdtprelL:
4216 Flags = PPCII::MO_DTPREL_LO;
4218 case PPC::ADDItlsldL:
4219 Flags = PPCII::MO_TLSLD_LO;
4222 Flags = PPCII::MO_TOC_LO;
4226 // We found an opportunity. Reverse the operands from the add
4227 // immediate and substitute them into the load or store. If
4228 // needed, update the target flags for the immediate operand to
4229 // reflect the necessary relocation information.
4230 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4231 DEBUG(Base->dump(CurDAG));
4232 DEBUG(dbgs() << "\nN: ");
4233 DEBUG(N->dump(CurDAG));
4234 DEBUG(dbgs() << "\n");
4236 SDValue ImmOpnd = Base.getOperand(1);
4238 // If the relocation information isn't already present on the
4239 // immediate operand, add it now.
4241 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4243 const GlobalValue *GV = GA->getGlobal();
4244 // We can't perform this optimization for data whose alignment
4245 // is insufficient for the instruction encoding.
4246 if (GV->getAlignment() < 4 &&
4247 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4248 StorageOpcode == PPC::LWA)) {
4249 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4252 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4253 } else if (ConstantPoolSDNode *CP =
4254 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4255 const Constant *C = CP->getConstVal();
4256 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4262 if (FirstOp == 1) // Store
4263 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4264 Base.getOperand(0), N->getOperand(3));
4266 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4269 // The add-immediate may now be dead, in which case remove it.
4270 if (Base.getNode()->use_empty())
4271 CurDAG->RemoveDeadNode(Base.getNode());
4276 /// createPPCISelDag - This pass converts a legalized DAG into a
4277 /// PowerPC-specific DAG, ready for instruction scheduling.
4279 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4280 return new PPCDAGToDAGISel(TM);
4283 static void initializePassOnce(PassRegistry &Registry) {
4284 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4285 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4286 nullptr, false, false);
4287 Registry.registerPass(*PI, true);
4290 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4291 CALL_ONCE_INITIALIZATION(initializePassOnce);