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,
190 std::vector<SDValue> &OutOps) override {
191 // We need to make sure that this one operand does not end up in r0
192 // (because we might end up lowering this as 0(%op)).
193 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
194 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
195 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
197 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
198 SDLoc(Op), Op.getValueType(),
201 OutOps.push_back(NewOp);
205 void InsertVRSaveCode(MachineFunction &MF);
207 const char *getPassName() const override {
208 return "PowerPC DAG->DAG Pattern Instruction Selection";
211 // Include the pieces autogenerated from the target description.
212 #include "PPCGenDAGISel.inc"
215 SDNode *SelectSETCC(SDNode *N);
217 void PeepholePPC64();
218 void PeepholePPC64ZExt();
219 void PeepholeCROps();
221 SDValue combineToCMPB(SDNode *N);
222 void foldBoolExts(SDValue &Res, SDNode *&N);
224 bool AllUsersSelectZero(SDNode *N);
225 void SwapAllSelectUsers(SDNode *N);
227 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
231 /// InsertVRSaveCode - Once the entire function has been instruction selected,
232 /// all virtual registers are created and all machine instructions are built,
233 /// check to see if we need to save/restore VRSAVE. If so, do it.
234 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
235 // Check to see if this function uses vector registers, which means we have to
236 // save and restore the VRSAVE register and update it with the regs we use.
238 // In this case, there will be virtual registers of vector type created
239 // by the scheduler. Detect them now.
240 bool HasVectorVReg = false;
241 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
242 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
243 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
244 HasVectorVReg = true;
248 if (!HasVectorVReg) return; // nothing to do.
250 // If we have a vector register, we want to emit code into the entry and exit
251 // blocks to save and restore the VRSAVE register. We do this here (instead
252 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
254 // 1. This (trivially) reduces the load on the register allocator, by not
255 // having to represent the live range of the VRSAVE register.
256 // 2. This (more significantly) allows us to create a temporary virtual
257 // register to hold the saved VRSAVE value, allowing this temporary to be
258 // register allocated, instead of forcing it to be spilled to the stack.
260 // Create two vregs - one to hold the VRSAVE register that is live-in to the
261 // function and one for the value after having bits or'd into it.
262 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
263 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
265 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
266 MachineBasicBlock &EntryBB = *Fn.begin();
268 // Emit the following code into the entry block:
269 // InVRSAVE = MFVRSAVE
270 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
271 // MTVRSAVE UpdatedVRSAVE
272 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
273 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
274 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
275 UpdatedVRSAVE).addReg(InVRSAVE);
276 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
278 // Find all return blocks, outputting a restore in each epilog.
279 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
280 if (!BB->empty() && BB->back().isReturn()) {
281 IP = BB->end(); --IP;
283 // Skip over all terminator instructions, which are part of the return
285 MachineBasicBlock::iterator I2 = IP;
286 while (I2 != BB->begin() && (--I2)->isTerminator())
289 // Emit: MTVRSAVE InVRSave
290 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
296 /// getGlobalBaseReg - Output the instructions required to put the
297 /// base address to use for accessing globals into a register.
299 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
300 if (!GlobalBaseReg) {
301 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
302 // Insert the set of GlobalBaseReg into the first MBB of the function
303 MachineBasicBlock &FirstMBB = MF->front();
304 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
305 const Module *M = MF->getFunction()->getParent();
308 if (PPCLowering->getPointerTy() == MVT::i32) {
309 if (PPCSubTarget->isTargetELF()) {
310 GlobalBaseReg = PPC::R30;
311 if (M->getPICLevel() == PICLevel::Small) {
312 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
313 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
314 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
316 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
317 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
318 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
319 BuildMI(FirstMBB, MBBI, dl,
320 TII.get(PPC::UpdateGBR), GlobalBaseReg)
321 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
322 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
326 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
327 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
328 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
331 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
332 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
333 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
336 return CurDAG->getRegister(GlobalBaseReg,
337 PPCLowering->getPointerTy()).getNode();
340 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
341 /// or 64-bit immediate, and if the value can be accurately represented as a
342 /// sign extension from a 16-bit value. If so, this returns true and the
344 static bool isIntS16Immediate(SDNode *N, short &Imm) {
345 if (N->getOpcode() != ISD::Constant)
348 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
349 if (N->getValueType(0) == MVT::i32)
350 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
352 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
355 static bool isIntS16Immediate(SDValue Op, short &Imm) {
356 return isIntS16Immediate(Op.getNode(), Imm);
360 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
361 /// operand. If so Imm will receive the 32-bit value.
362 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
363 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
364 Imm = cast<ConstantSDNode>(N)->getZExtValue();
370 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
371 /// operand. If so Imm will receive the 64-bit value.
372 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
373 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
374 Imm = cast<ConstantSDNode>(N)->getZExtValue();
380 // isInt32Immediate - This method tests to see if a constant operand.
381 // If so Imm will receive the 32 bit value.
382 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
383 return isInt32Immediate(N.getNode(), Imm);
387 // isOpcWithIntImmediate - This method tests to see if the node is a specific
388 // opcode and that it has a immediate integer right operand.
389 // If so Imm will receive the 32 bit value.
390 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
391 return N->getOpcode() == Opc
392 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
395 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
397 int FI = cast<FrameIndexSDNode>(N)->getIndex();
398 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
399 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
401 return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
402 getSmallIPtrImm(Offset));
403 return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
404 getSmallIPtrImm(Offset));
407 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
411 if (isShiftedMask_32(Val)) {
412 // look for the first non-zero bit
413 MB = countLeadingZeros(Val);
414 // look for the first zero bit after the run of ones
415 ME = countLeadingZeros((Val - 1) ^ Val);
418 Val = ~Val; // invert mask
419 if (isShiftedMask_32(Val)) {
420 // effectively look for the first zero bit
421 ME = countLeadingZeros(Val) - 1;
422 // effectively look for the first one bit after the run of zeros
423 MB = countLeadingZeros((Val - 1) ^ Val) + 1;
431 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
432 bool isShiftMask, unsigned &SH,
433 unsigned &MB, unsigned &ME) {
434 // Don't even go down this path for i64, since different logic will be
435 // necessary for rldicl/rldicr/rldimi.
436 if (N->getValueType(0) != MVT::i32)
440 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
441 unsigned Opcode = N->getOpcode();
442 if (N->getNumOperands() != 2 ||
443 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
446 if (Opcode == ISD::SHL) {
447 // apply shift left to mask if it comes first
448 if (isShiftMask) Mask = Mask << Shift;
449 // determine which bits are made indeterminant by shift
450 Indeterminant = ~(0xFFFFFFFFu << Shift);
451 } else if (Opcode == ISD::SRL) {
452 // apply shift right to mask if it comes first
453 if (isShiftMask) Mask = Mask >> Shift;
454 // determine which bits are made indeterminant by shift
455 Indeterminant = ~(0xFFFFFFFFu >> Shift);
456 // adjust for the left rotate
458 } else if (Opcode == ISD::ROTL) {
464 // if the mask doesn't intersect any Indeterminant bits
465 if (Mask && !(Mask & Indeterminant)) {
467 // make sure the mask is still a mask (wrap arounds may not be)
468 return isRunOfOnes(Mask, MB, ME);
473 /// SelectBitfieldInsert - turn an or of two masked values into
474 /// the rotate left word immediate then mask insert (rlwimi) instruction.
475 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
476 SDValue Op0 = N->getOperand(0);
477 SDValue Op1 = N->getOperand(1);
480 APInt LKZ, LKO, RKZ, RKO;
481 CurDAG->computeKnownBits(Op0, LKZ, LKO);
482 CurDAG->computeKnownBits(Op1, RKZ, RKO);
484 unsigned TargetMask = LKZ.getZExtValue();
485 unsigned InsertMask = RKZ.getZExtValue();
487 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
488 unsigned Op0Opc = Op0.getOpcode();
489 unsigned Op1Opc = Op1.getOpcode();
490 unsigned Value, SH = 0;
491 TargetMask = ~TargetMask;
492 InsertMask = ~InsertMask;
494 // If the LHS has a foldable shift and the RHS does not, then swap it to the
495 // RHS so that we can fold the shift into the insert.
496 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
497 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
498 Op0.getOperand(0).getOpcode() == ISD::SRL) {
499 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
500 Op1.getOperand(0).getOpcode() != ISD::SRL) {
502 std::swap(Op0Opc, Op1Opc);
503 std::swap(TargetMask, InsertMask);
506 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
507 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
508 Op1.getOperand(0).getOpcode() != ISD::SRL) {
510 std::swap(Op0Opc, Op1Opc);
511 std::swap(TargetMask, InsertMask);
516 if (isRunOfOnes(InsertMask, MB, ME)) {
519 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
520 isInt32Immediate(Op1.getOperand(1), Value)) {
521 Op1 = Op1.getOperand(0);
522 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
524 if (Op1Opc == ISD::AND) {
525 // The AND mask might not be a constant, and we need to make sure that
526 // if we're going to fold the masking with the insert, all bits not
527 // know to be zero in the mask are known to be one.
529 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
530 bool CanFoldMask = InsertMask == MKO.getZExtValue();
532 unsigned SHOpc = Op1.getOperand(0).getOpcode();
533 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
534 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
535 // Note that Value must be in range here (less than 32) because
536 // otherwise there would not be any bits set in InsertMask.
537 Op1 = Op1.getOperand(0).getOperand(0);
538 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
543 SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
545 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
551 // Predict the number of instructions that would be generated by calling
553 static unsigned SelectInt64CountDirect(int64_t Imm) {
554 // Assume no remaining bits.
555 unsigned Remainder = 0;
556 // Assume no shift required.
559 // If it can't be represented as a 32 bit value.
560 if (!isInt<32>(Imm)) {
561 Shift = countTrailingZeros<uint64_t>(Imm);
562 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
564 // If the shifted value fits 32 bits.
565 if (isInt<32>(ImmSh)) {
566 // Go with the shifted value.
569 // Still stuck with a 64 bit value.
576 // Intermediate operand.
579 // Handle first 32 bits.
580 unsigned Lo = Imm & 0xFFFF;
581 unsigned Hi = (Imm >> 16) & 0xFFFF;
584 if (isInt<16>(Imm)) {
588 // Handle the Hi bits and Lo bits.
595 // If no shift, we're done.
596 if (!Shift) return Result;
598 // Shift for next step if the upper 32-bits were not zero.
602 // Add in the last bits as required.
603 if ((Hi = (Remainder >> 16) & 0xFFFF))
605 if ((Lo = Remainder & 0xFFFF))
611 static uint64_t Rot64(uint64_t Imm, unsigned R) {
612 return (Imm << R) | (Imm >> (64 - R));
615 static unsigned SelectInt64Count(int64_t Imm) {
616 unsigned Count = SelectInt64CountDirect(Imm);
620 for (unsigned r = 1; r < 63; ++r) {
621 uint64_t RImm = Rot64(Imm, r);
622 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
623 Count = std::min(Count, RCount);
625 // See comments in SelectInt64 for an explanation of the logic below.
626 unsigned LS = findLastSet(RImm);
630 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
631 uint64_t RImmWithOnes = RImm | OnesMask;
633 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
634 Count = std::min(Count, RCount);
640 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
641 // (above) needs to be kept in sync with this function.
642 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
643 // Assume no remaining bits.
644 unsigned Remainder = 0;
645 // Assume no shift required.
648 // If it can't be represented as a 32 bit value.
649 if (!isInt<32>(Imm)) {
650 Shift = countTrailingZeros<uint64_t>(Imm);
651 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
653 // If the shifted value fits 32 bits.
654 if (isInt<32>(ImmSh)) {
655 // Go with the shifted value.
658 // Still stuck with a 64 bit value.
665 // Intermediate operand.
668 // Handle first 32 bits.
669 unsigned Lo = Imm & 0xFFFF;
670 unsigned Hi = (Imm >> 16) & 0xFFFF;
672 auto getI32Imm = [CurDAG](unsigned Imm) {
673 return CurDAG->getTargetConstant(Imm, MVT::i32);
677 if (isInt<16>(Imm)) {
679 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
681 // Handle the Hi bits.
682 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
683 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
685 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
686 SDValue(Result, 0), getI32Imm(Lo));
689 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
692 // If no shift, we're done.
693 if (!Shift) return Result;
695 // Shift for next step if the upper 32-bits were not zero.
697 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
700 getI32Imm(63 - Shift));
703 // Add in the last bits as required.
704 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
705 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
706 SDValue(Result, 0), getI32Imm(Hi));
708 if ((Lo = Remainder & 0xFFFF)) {
709 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
710 SDValue(Result, 0), getI32Imm(Lo));
716 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
717 unsigned Count = SelectInt64CountDirect(Imm);
719 return SelectInt64Direct(CurDAG, dl, Imm);
726 for (unsigned r = 1; r < 63; ++r) {
727 uint64_t RImm = Rot64(Imm, r);
728 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
729 if (RCount < Count) {
736 // If the immediate to generate has many trailing zeros, it might be
737 // worthwhile to generate a rotated value with too many leading ones
738 // (because that's free with li/lis's sign-extension semantics), and then
739 // mask them off after rotation.
741 unsigned LS = findLastSet(RImm);
742 // We're adding (63-LS) higher-order ones, and we expect to mask them off
743 // after performing the inverse rotation by (64-r). So we need that:
744 // 63-LS == 64-r => LS == r-1
748 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
749 uint64_t RImmWithOnes = RImm | OnesMask;
751 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
752 if (RCount < Count) {
755 MatImm = RImmWithOnes;
761 return SelectInt64Direct(CurDAG, dl, Imm);
763 auto getI32Imm = [CurDAG](unsigned Imm) {
764 return CurDAG->getTargetConstant(Imm, MVT::i32);
767 SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, MatImm), 0);
768 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
769 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
772 // Select a 64-bit constant.
773 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
777 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
778 return SelectInt64(CurDAG, dl, Imm);
782 class BitPermutationSelector {
786 // The bit number in the value, using a convention where bit 0 is the
795 ValueBit(SDValue V, unsigned I, Kind K = Variable)
796 : V(V), Idx(I), K(K) {}
797 ValueBit(Kind K = Variable)
798 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
800 bool isZero() const {
801 return K == ConstZero;
804 bool hasValue() const {
805 return K == Variable;
808 SDValue getValue() const {
809 assert(hasValue() && "Cannot get the value of a constant bit");
813 unsigned getValueBitIndex() const {
814 assert(hasValue() && "Cannot get the value bit index of a constant bit");
819 // A bit group has the same underlying value and the same rotate factor.
823 unsigned StartIdx, EndIdx;
825 // This rotation amount assumes that the lower 32 bits of the quantity are
826 // replicated in the high 32 bits by the rotation operator (which is done
827 // by rlwinm and friends in 64-bit mode).
829 // Did converting to Repl32 == true change the rotation factor? If it did,
830 // it decreased it by 32.
832 // Was this group coalesced after setting Repl32 to true?
833 bool Repl32Coalesced;
835 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
836 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
837 Repl32Coalesced(false) {
838 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
839 " [" << S << ", " << E << "]\n");
843 // Information on each (Value, RLAmt) pair (like the number of groups
844 // associated with each) used to choose the lowering method.
845 struct ValueRotInfo {
849 unsigned FirstGroupStartIdx;
853 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
856 // For sorting (in reverse order) by NumGroups, and then by
857 // FirstGroupStartIdx.
858 bool operator < (const ValueRotInfo &Other) const {
859 // We need to sort so that the non-Repl32 come first because, when we're
860 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
861 // masking operation.
862 if (Repl32 < Other.Repl32)
864 else if (Repl32 > Other.Repl32)
866 else if (NumGroups > Other.NumGroups)
868 else if (NumGroups < Other.NumGroups)
870 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
876 // Return true if something interesting was deduced, return false if we're
877 // providing only a generic representation of V (or something else likewise
878 // uninteresting for instruction selection).
879 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
880 switch (V.getOpcode()) {
883 if (isa<ConstantSDNode>(V.getOperand(1))) {
884 unsigned RotAmt = V.getConstantOperandVal(1);
886 SmallVector<ValueBit, 64> LHSBits(Bits.size());
887 getValueBits(V.getOperand(0), LHSBits);
889 for (unsigned i = 0; i < Bits.size(); ++i)
890 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
896 if (isa<ConstantSDNode>(V.getOperand(1))) {
897 unsigned ShiftAmt = V.getConstantOperandVal(1);
899 SmallVector<ValueBit, 64> LHSBits(Bits.size());
900 getValueBits(V.getOperand(0), LHSBits);
902 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
903 Bits[i] = LHSBits[i - ShiftAmt];
905 for (unsigned i = 0; i < ShiftAmt; ++i)
906 Bits[i] = ValueBit(ValueBit::ConstZero);
912 if (isa<ConstantSDNode>(V.getOperand(1))) {
913 unsigned ShiftAmt = V.getConstantOperandVal(1);
915 SmallVector<ValueBit, 64> LHSBits(Bits.size());
916 getValueBits(V.getOperand(0), LHSBits);
918 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
919 Bits[i] = LHSBits[i + ShiftAmt];
921 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
922 Bits[i] = ValueBit(ValueBit::ConstZero);
928 if (isa<ConstantSDNode>(V.getOperand(1))) {
929 uint64_t Mask = V.getConstantOperandVal(1);
931 SmallVector<ValueBit, 64> LHSBits(Bits.size());
932 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
934 for (unsigned i = 0; i < Bits.size(); ++i)
935 if (((Mask >> i) & 1) == 1)
936 Bits[i] = LHSBits[i];
938 Bits[i] = ValueBit(ValueBit::ConstZero);
940 // Mark this as interesting, only if the LHS was also interesting. This
941 // prevents the overall procedure from matching a single immediate 'and'
942 // (which is non-optimal because such an and might be folded with other
943 // things if we don't select it here).
948 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
949 getValueBits(V.getOperand(0), LHSBits);
950 getValueBits(V.getOperand(1), RHSBits);
952 bool AllDisjoint = true;
953 for (unsigned i = 0; i < Bits.size(); ++i)
954 if (LHSBits[i].isZero())
955 Bits[i] = RHSBits[i];
956 else if (RHSBits[i].isZero())
957 Bits[i] = LHSBits[i];
970 for (unsigned i = 0; i < Bits.size(); ++i)
971 Bits[i] = ValueBit(V, i);
976 // For each value (except the constant ones), compute the left-rotate amount
977 // to get it from its original to final position.
978 void computeRotationAmounts() {
980 RLAmt.resize(Bits.size());
981 for (unsigned i = 0; i < Bits.size(); ++i)
982 if (Bits[i].hasValue()) {
983 unsigned VBI = Bits[i].getValueBitIndex();
987 RLAmt[i] = Bits.size() - (VBI - i);
988 } else if (Bits[i].isZero()) {
990 RLAmt[i] = UINT32_MAX;
992 llvm_unreachable("Unknown value bit type");
996 // Collect groups of consecutive bits with the same underlying value and
997 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
998 // they break up groups.
999 void collectBitGroups(bool LateMask) {
1002 unsigned LastRLAmt = RLAmt[0];
1003 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1004 unsigned LastGroupStartIdx = 0;
1005 for (unsigned i = 1; i < Bits.size(); ++i) {
1006 unsigned ThisRLAmt = RLAmt[i];
1007 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1008 if (LateMask && !ThisValue) {
1009 ThisValue = LastValue;
1010 ThisRLAmt = LastRLAmt;
1011 // If we're doing late masking, then the first bit group always starts
1012 // at zero (even if the first bits were zero).
1013 if (BitGroups.empty())
1014 LastGroupStartIdx = 0;
1017 // If this bit has the same underlying value and the same rotate factor as
1018 // the last one, then they're part of the same group.
1019 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1022 if (LastValue.getNode())
1023 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1025 LastRLAmt = ThisRLAmt;
1026 LastValue = ThisValue;
1027 LastGroupStartIdx = i;
1029 if (LastValue.getNode())
1030 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1033 if (BitGroups.empty())
1036 // We might be able to combine the first and last groups.
1037 if (BitGroups.size() > 1) {
1038 // If the first and last groups are the same, then remove the first group
1039 // in favor of the last group, making the ending index of the last group
1040 // equal to the ending index of the to-be-removed first group.
1041 if (BitGroups[0].StartIdx == 0 &&
1042 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1043 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1044 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1045 DEBUG(dbgs() << "\tcombining final bit group with inital one\n");
1046 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1047 BitGroups.erase(BitGroups.begin());
1052 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1053 // associated with each. If there is a degeneracy, pick the one that occurs
1054 // first (in the final value).
1055 void collectValueRotInfo() {
1058 for (auto &BG : BitGroups) {
1059 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1060 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1062 VRI.RLAmt = BG.RLAmt;
1063 VRI.Repl32 = BG.Repl32;
1065 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1068 // Now that we've collected the various ValueRotInfo instances, we need to
1070 ValueRotsVec.clear();
1071 for (auto &I : ValueRots) {
1072 ValueRotsVec.push_back(I.second);
1074 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1077 // In 64-bit mode, rlwinm and friends have a rotation operator that
1078 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1079 // indices of these instructions can only be in the lower 32 bits, so they
1080 // can only represent some 64-bit bit groups. However, when they can be used,
1081 // the 32-bit replication can be used to represent, as a single bit group,
1082 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1083 // groups when possible. Returns true if any of the bit groups were
1085 void assignRepl32BitGroups() {
1086 // If we have bits like this:
1088 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1089 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1090 // Groups: | RLAmt = 8 | RLAmt = 40 |
1092 // But, making use of a 32-bit operation that replicates the low-order 32
1093 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1096 auto IsAllLow32 = [this](BitGroup & BG) {
1097 if (BG.StartIdx <= BG.EndIdx) {
1098 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1099 if (!Bits[i].hasValue())
1101 if (Bits[i].getValueBitIndex() >= 32)
1105 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1106 if (!Bits[i].hasValue())
1108 if (Bits[i].getValueBitIndex() >= 32)
1111 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1112 if (!Bits[i].hasValue())
1114 if (Bits[i].getValueBitIndex() >= 32)
1122 for (auto &BG : BitGroups) {
1123 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1124 if (IsAllLow32(BG)) {
1125 if (BG.RLAmt >= 32) {
1132 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1133 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1134 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1139 // Now walk through the bit groups, consolidating where possible.
1140 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1141 // We might want to remove this bit group by merging it with the previous
1142 // group (which might be the ending group).
1143 auto IP = (I == BitGroups.begin()) ?
1144 std::prev(BitGroups.end()) : std::prev(I);
1145 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1146 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1148 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1149 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1150 " [" << I->StartIdx << ", " << I->EndIdx <<
1151 "] with group with range [" <<
1152 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1154 IP->EndIdx = I->EndIdx;
1155 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1156 IP->Repl32Coalesced = true;
1157 I = BitGroups.erase(I);
1160 // There is a special case worth handling: If there is a single group
1161 // covering the entire upper 32 bits, and it can be merged with both
1162 // the next and previous groups (which might be the same group), then
1163 // do so. If it is the same group (so there will be only one group in
1164 // total), then we need to reverse the order of the range so that it
1165 // covers the entire 64 bits.
1166 if (I->StartIdx == 32 && I->EndIdx == 63) {
1167 assert(std::next(I) == BitGroups.end() &&
1168 "bit group ends at index 63 but there is another?");
1169 auto IN = BitGroups.begin();
1171 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1172 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1173 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1176 DEBUG(dbgs() << "\tcombining bit group for " <<
1177 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1178 " [" << I->StartIdx << ", " << I->EndIdx <<
1179 "] with 32-bit replicated groups with ranges [" <<
1180 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1181 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1184 // There is only one other group; change it to cover the whole
1185 // range (backward, so that it can still be Repl32 but cover the
1186 // whole 64-bit range).
1189 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1190 IP->Repl32Coalesced = true;
1191 I = BitGroups.erase(I);
1193 // There are two separate groups, one before this group and one
1194 // after us (at the beginning). We're going to remove this group,
1195 // but also the group at the very beginning.
1196 IP->EndIdx = IN->EndIdx;
1197 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1198 IP->Repl32Coalesced = true;
1199 I = BitGroups.erase(I);
1200 BitGroups.erase(BitGroups.begin());
1203 // This must be the last group in the vector (and we might have
1204 // just invalidated the iterator above), so break here.
1214 SDValue getI32Imm(unsigned Imm) {
1215 return CurDAG->getTargetConstant(Imm, MVT::i32);
1218 uint64_t getZerosMask() {
1220 for (unsigned i = 0; i < Bits.size(); ++i) {
1221 if (Bits[i].hasValue())
1223 Mask |= (UINT64_C(1) << i);
1229 // Depending on the number of groups for a particular value, it might be
1230 // better to rotate, mask explicitly (using andi/andis), and then or the
1231 // result. Select this part of the result first.
1232 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1233 if (BPermRewriterNoMasking)
1236 for (ValueRotInfo &VRI : ValueRotsVec) {
1238 for (unsigned i = 0; i < Bits.size(); ++i) {
1239 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1241 if (RLAmt[i] != VRI.RLAmt)
1246 // Compute the masks for andi/andis that would be necessary.
1247 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1248 assert((ANDIMask != 0 || ANDISMask != 0) &&
1249 "No set bits in mask for value bit groups");
1250 bool NeedsRotate = VRI.RLAmt != 0;
1252 // We're trying to minimize the number of instructions. If we have one
1253 // group, using one of andi/andis can break even. If we have three
1254 // groups, we can use both andi and andis and break even (to use both
1255 // andi and andis we also need to or the results together). We need four
1256 // groups if we also need to rotate. To use andi/andis we need to do more
1257 // than break even because rotate-and-mask instructions tend to be easier
1260 // FIXME: We've biased here against using andi/andis, which is right for
1261 // POWER cores, but not optimal everywhere. For example, on the A2,
1262 // andi/andis have single-cycle latency whereas the rotate-and-mask
1263 // instructions take two cycles, and it would be better to bias toward
1264 // andi/andis in break-even cases.
1266 unsigned NumAndInsts = (unsigned) NeedsRotate +
1267 (unsigned) (ANDIMask != 0) +
1268 (unsigned) (ANDISMask != 0) +
1269 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1270 (unsigned) (bool) Res;
1272 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1273 " RL: " << VRI.RLAmt << ":" <<
1274 "\n\t\t\tisel using masking: " << NumAndInsts <<
1275 " using rotates: " << VRI.NumGroups << "\n");
1277 if (NumAndInsts >= VRI.NumGroups)
1280 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1282 if (InstCnt) *InstCnt += NumAndInsts;
1287 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1288 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1294 SDValue ANDIVal, ANDISVal;
1296 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1297 VRot, getI32Imm(ANDIMask)), 0);
1299 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1300 VRot, getI32Imm(ANDISMask)), 0);
1304 TotalVal = ANDISVal;
1308 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1309 ANDIVal, ANDISVal), 0);
1314 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1317 // Now, remove all groups with this underlying value and rotation
1319 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1320 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1321 I = BitGroups.erase(I);
1328 // Instruction selection for the 32-bit case.
1329 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1333 if (InstCnt) *InstCnt = 0;
1335 // Take care of cases that should use andi/andis first.
1336 SelectAndParts32(dl, Res, InstCnt);
1338 // If we've not yet selected a 'starting' instruction, and we have no zeros
1339 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1340 // number of groups), and start with this rotated value.
1341 if ((!HasZeros || LateMask) && !Res) {
1342 ValueRotInfo &VRI = ValueRotsVec[0];
1344 if (InstCnt) *InstCnt += 1;
1346 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1347 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1352 // Now, remove all groups with this underlying value and rotation factor.
1353 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1354 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1355 I = BitGroups.erase(I);
1361 if (InstCnt) *InstCnt += BitGroups.size();
1363 // Insert the other groups (one at a time).
1364 for (auto &BG : BitGroups) {
1367 { BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1368 getI32Imm(Bits.size() - BG.StartIdx - 1) };
1369 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1372 { Res, BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1373 getI32Imm(Bits.size() - BG.StartIdx - 1) };
1374 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1379 unsigned Mask = (unsigned) getZerosMask();
1381 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1382 assert((ANDIMask != 0 || ANDISMask != 0) &&
1383 "No set bits in zeros mask?");
1385 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1386 (unsigned) (ANDISMask != 0) +
1387 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1389 SDValue ANDIVal, ANDISVal;
1391 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1392 Res, getI32Imm(ANDIMask)), 0);
1394 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1395 Res, getI32Imm(ANDISMask)), 0);
1402 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1403 ANDIVal, ANDISVal), 0);
1406 return Res.getNode();
1409 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1410 unsigned MaskStart, unsigned MaskEnd,
1412 // In the notation used by the instructions, 'start' and 'end' are reversed
1413 // because bits are counted from high to low order.
1414 unsigned InstMaskStart = 64 - MaskEnd - 1,
1415 InstMaskEnd = 64 - MaskStart - 1;
1420 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1421 InstMaskEnd == 63 - RLAmt)
1427 // For 64-bit values, not all combinations of rotates and masks are
1428 // available. Produce one if it is available.
1429 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1430 unsigned MaskStart, unsigned MaskEnd,
1431 unsigned *InstCnt = nullptr) {
1432 // In the notation used by the instructions, 'start' and 'end' are reversed
1433 // because bits are counted from high to low order.
1434 unsigned InstMaskStart = 64 - MaskEnd - 1,
1435 InstMaskEnd = 64 - MaskStart - 1;
1437 if (InstCnt) *InstCnt += 1;
1440 // This rotation amount assumes that the lower 32 bits of the quantity
1441 // are replicated in the high 32 bits by the rotation operator (which is
1442 // done by rlwinm and friends).
1443 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1444 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1446 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1447 getI32Imm(InstMaskEnd - 32) };
1448 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1452 if (InstMaskEnd == 63) {
1454 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1455 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1458 if (InstMaskStart == 0) {
1460 { V, getI32Imm(RLAmt), getI32Imm(InstMaskEnd) };
1461 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1464 if (InstMaskEnd == 63 - RLAmt) {
1466 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1467 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1470 // We cannot do this with a single instruction, so we'll use two. The
1471 // problem is that we're not free to choose both a rotation amount and mask
1472 // start and end independently. We can choose an arbitrary mask start and
1473 // end, but then the rotation amount is fixed. Rotation, however, can be
1474 // inverted, and so by applying an "inverse" rotation first, we can get the
1476 if (InstCnt) *InstCnt += 1;
1478 // The rotation mask for the second instruction must be MaskStart.
1479 unsigned RLAmt2 = MaskStart;
1480 // The first instruction must rotate V so that the overall rotation amount
1482 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1484 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1485 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1488 // For 64-bit values, not all combinations of rotates and masks are
1489 // available. Produce a rotate-mask-and-insert if one is available.
1490 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1491 bool Repl32, unsigned MaskStart,
1492 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1493 // In the notation used by the instructions, 'start' and 'end' are reversed
1494 // because bits are counted from high to low order.
1495 unsigned InstMaskStart = 64 - MaskEnd - 1,
1496 InstMaskEnd = 64 - MaskStart - 1;
1498 if (InstCnt) *InstCnt += 1;
1501 // This rotation amount assumes that the lower 32 bits of the quantity
1502 // are replicated in the high 32 bits by the rotation operator (which is
1503 // done by rlwinm and friends).
1504 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1505 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1507 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1508 getI32Imm(InstMaskEnd - 32) };
1509 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1513 if (InstMaskEnd == 63 - RLAmt) {
1515 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1516 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1519 // We cannot do this with a single instruction, so we'll use two. The
1520 // problem is that we're not free to choose both a rotation amount and mask
1521 // start and end independently. We can choose an arbitrary mask start and
1522 // end, but then the rotation amount is fixed. Rotation, however, can be
1523 // inverted, and so by applying an "inverse" rotation first, we can get the
1525 if (InstCnt) *InstCnt += 1;
1527 // The rotation mask for the second instruction must be MaskStart.
1528 unsigned RLAmt2 = MaskStart;
1529 // The first instruction must rotate V so that the overall rotation amount
1531 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1533 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1534 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1537 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1538 if (BPermRewriterNoMasking)
1541 // The idea here is the same as in the 32-bit version, but with additional
1542 // complications from the fact that Repl32 might be true. Because we
1543 // aggressively convert bit groups to Repl32 form (which, for small
1544 // rotation factors, involves no other change), and then coalesce, it might
1545 // be the case that a single 64-bit masking operation could handle both
1546 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1547 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1548 // completely capture the new combined bit group.
1550 for (ValueRotInfo &VRI : ValueRotsVec) {
1553 // We need to add to the mask all bits from the associated bit groups.
1554 // If Repl32 is false, we need to add bits from bit groups that have
1555 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1556 // group is trivially convertable if it overlaps only with the lower 32
1557 // bits, and the group has not been coalesced.
1558 auto MatchingBG = [VRI](BitGroup &BG) {
1562 unsigned EffRLAmt = BG.RLAmt;
1563 if (!VRI.Repl32 && BG.Repl32) {
1564 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1565 !BG.Repl32Coalesced) {
1571 } else if (VRI.Repl32 != BG.Repl32) {
1575 if (VRI.RLAmt != EffRLAmt)
1581 for (auto &BG : BitGroups) {
1582 if (!MatchingBG(BG))
1585 if (BG.StartIdx <= BG.EndIdx) {
1586 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1587 Mask |= (UINT64_C(1) << i);
1589 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1590 Mask |= (UINT64_C(1) << i);
1591 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1592 Mask |= (UINT64_C(1) << i);
1596 // We can use the 32-bit andi/andis technique if the mask does not
1597 // require any higher-order bits. This can save an instruction compared
1598 // to always using the general 64-bit technique.
1599 bool Use32BitInsts = isUInt<32>(Mask);
1600 // Compute the masks for andi/andis that would be necessary.
1601 unsigned ANDIMask = (Mask & UINT16_MAX),
1602 ANDISMask = (Mask >> 16) & UINT16_MAX;
1604 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1606 unsigned NumAndInsts = (unsigned) NeedsRotate +
1607 (unsigned) (bool) Res;
1609 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1610 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1612 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1614 unsigned NumRLInsts = 0;
1615 bool FirstBG = true;
1616 for (auto &BG : BitGroups) {
1617 if (!MatchingBG(BG))
1620 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1625 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1626 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1627 "\n\t\t\tisel using masking: " << NumAndInsts <<
1628 " using rotates: " << NumRLInsts << "\n");
1630 // When we'd use andi/andis, we bias toward using the rotates (andi only
1631 // has a record form, and is cracked on POWER cores). However, when using
1632 // general 64-bit constant formation, bias toward the constant form,
1633 // because that exposes more opportunities for CSE.
1634 if (NumAndInsts > NumRLInsts)
1636 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1639 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1641 if (InstCnt) *InstCnt += NumAndInsts;
1644 // We actually need to generate a rotation if we have a non-zero rotation
1645 // factor or, in the Repl32 case, if we care about any of the
1646 // higher-order replicated bits. In the latter case, we generate a mask
1647 // backward so that it actually includes the entire 64 bits.
1648 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1649 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1650 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1655 if (Use32BitInsts) {
1656 assert((ANDIMask != 0 || ANDISMask != 0) &&
1657 "No set bits in mask when using 32-bit ands for 64-bit value");
1659 SDValue ANDIVal, ANDISVal;
1661 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1662 VRot, getI32Imm(ANDIMask)), 0);
1664 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1665 VRot, getI32Imm(ANDISMask)), 0);
1668 TotalVal = ANDISVal;
1672 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1673 ANDIVal, ANDISVal), 0);
1675 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1677 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1678 VRot, TotalVal), 0);
1684 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1687 // Now, remove all groups with this underlying value and rotation
1689 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1691 I = BitGroups.erase(I);
1698 // Instruction selection for the 64-bit case.
1699 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1703 if (InstCnt) *InstCnt = 0;
1705 // Take care of cases that should use andi/andis first.
1706 SelectAndParts64(dl, Res, InstCnt);
1708 // If we've not yet selected a 'starting' instruction, and we have no zeros
1709 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1710 // number of groups), and start with this rotated value.
1711 if ((!HasZeros || LateMask) && !Res) {
1712 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1713 // groups will come first, and so the VRI representing the largest number
1714 // of groups might not be first (it might be the first Repl32 groups).
1715 unsigned MaxGroupsIdx = 0;
1716 if (!ValueRotsVec[0].Repl32) {
1717 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1718 if (ValueRotsVec[i].Repl32) {
1719 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1725 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1726 bool NeedsRotate = false;
1729 } else if (VRI.Repl32) {
1730 for (auto &BG : BitGroups) {
1731 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1732 BG.Repl32 != VRI.Repl32)
1735 // We don't need a rotate if the bit group is confined to the lower
1737 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1746 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1747 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1752 // Now, remove all groups with this underlying value and rotation factor.
1754 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1755 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt && I->Repl32 == VRI.Repl32)
1756 I = BitGroups.erase(I);
1762 // Because 64-bit rotates are more flexible than inserts, we might have a
1763 // preference regarding which one we do first (to save one instruction).
1765 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1766 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1768 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1770 if (I != BitGroups.begin()) {
1773 BitGroups.insert(BitGroups.begin(), BG);
1780 // Insert the other groups (one at a time).
1781 for (auto &BG : BitGroups) {
1783 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1784 BG.EndIdx, InstCnt);
1786 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1787 BG.StartIdx, BG.EndIdx, InstCnt);
1791 uint64_t Mask = getZerosMask();
1793 // We can use the 32-bit andi/andis technique if the mask does not
1794 // require any higher-order bits. This can save an instruction compared
1795 // to always using the general 64-bit technique.
1796 bool Use32BitInsts = isUInt<32>(Mask);
1797 // Compute the masks for andi/andis that would be necessary.
1798 unsigned ANDIMask = (Mask & UINT16_MAX),
1799 ANDISMask = (Mask >> 16) & UINT16_MAX;
1801 if (Use32BitInsts) {
1802 assert((ANDIMask != 0 || ANDISMask != 0) &&
1803 "No set bits in mask when using 32-bit ands for 64-bit value");
1805 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1806 (unsigned) (ANDISMask != 0) +
1807 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1809 SDValue ANDIVal, ANDISVal;
1811 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1812 Res, getI32Imm(ANDIMask)), 0);
1814 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1815 Res, getI32Imm(ANDISMask)), 0);
1822 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1823 ANDIVal, ANDISVal), 0);
1825 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1827 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1829 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1834 return Res.getNode();
1837 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1838 // Fill in BitGroups.
1839 collectBitGroups(LateMask);
1840 if (BitGroups.empty())
1843 // For 64-bit values, figure out when we can use 32-bit instructions.
1844 if (Bits.size() == 64)
1845 assignRepl32BitGroups();
1847 // Fill in ValueRotsVec.
1848 collectValueRotInfo();
1850 if (Bits.size() == 32) {
1851 return Select32(N, LateMask, InstCnt);
1853 assert(Bits.size() == 64 && "Not 64 bits here?");
1854 return Select64(N, LateMask, InstCnt);
1860 SmallVector<ValueBit, 64> Bits;
1863 SmallVector<unsigned, 64> RLAmt;
1865 SmallVector<BitGroup, 16> BitGroups;
1867 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1868 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1870 SelectionDAG *CurDAG;
1873 BitPermutationSelector(SelectionDAG *DAG)
1876 // Here we try to match complex bit permutations into a set of
1877 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1878 // known to produce optimial code for common cases (like i32 byte swapping).
1879 SDNode *Select(SDNode *N) {
1880 Bits.resize(N->getValueType(0).getSizeInBits());
1881 if (!getValueBits(SDValue(N, 0), Bits))
1884 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1885 " selection for: ");
1886 DEBUG(N->dump(CurDAG));
1888 // Fill it RLAmt and set HasZeros.
1889 computeRotationAmounts();
1892 return Select(N, false);
1894 // We currently have two techniques for handling results with zeros: early
1895 // masking (the default) and late masking. Late masking is sometimes more
1896 // efficient, but because the structure of the bit groups is different, it
1897 // is hard to tell without generating both and comparing the results. With
1898 // late masking, we ignore zeros in the resulting value when inserting each
1899 // set of bit groups, and then mask in the zeros at the end. With early
1900 // masking, we only insert the non-zero parts of the result at every step.
1902 unsigned InstCnt, InstCntLateMask;
1903 DEBUG(dbgs() << "\tEarly masking:\n");
1904 SDNode *RN = Select(N, false, &InstCnt);
1905 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1907 DEBUG(dbgs() << "\tLate masking:\n");
1908 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1909 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1912 if (InstCnt <= InstCntLateMask) {
1913 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1917 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1921 } // anonymous namespace
1923 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1924 if (N->getValueType(0) != MVT::i32 &&
1925 N->getValueType(0) != MVT::i64)
1928 if (!UseBitPermRewriter)
1931 switch (N->getOpcode()) {
1938 BitPermutationSelector BPS(CurDAG);
1939 return BPS.Select(N);
1946 /// SelectCC - Select a comparison of the specified values with the specified
1947 /// condition code, returning the CR# of the expression.
1948 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1949 ISD::CondCode CC, SDLoc dl) {
1950 // Always select the LHS.
1953 if (LHS.getValueType() == MVT::i32) {
1955 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1956 if (isInt32Immediate(RHS, Imm)) {
1957 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1958 if (isUInt<16>(Imm))
1959 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1960 getI32Imm(Imm & 0xFFFF)), 0);
1961 // If this is a 16-bit signed immediate, fold it.
1962 if (isInt<16>((int)Imm))
1963 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1964 getI32Imm(Imm & 0xFFFF)), 0);
1966 // For non-equality comparisons, the default code would materialize the
1967 // constant, then compare against it, like this:
1969 // ori r2, r2, 22136
1971 // Since we are just comparing for equality, we can emit this instead:
1972 // xoris r0,r3,0x1234
1973 // cmplwi cr0,r0,0x5678
1975 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
1976 getI32Imm(Imm >> 16)), 0);
1977 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1978 getI32Imm(Imm & 0xFFFF)), 0);
1981 } else if (ISD::isUnsignedIntSetCC(CC)) {
1982 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
1983 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1984 getI32Imm(Imm & 0xFFFF)), 0);
1988 if (isIntS16Immediate(RHS, SImm))
1989 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1990 getI32Imm((int)SImm & 0xFFFF)),
1994 } else if (LHS.getValueType() == MVT::i64) {
1996 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1997 if (isInt64Immediate(RHS.getNode(), Imm)) {
1998 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1999 if (isUInt<16>(Imm))
2000 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2001 getI32Imm(Imm & 0xFFFF)), 0);
2002 // If this is a 16-bit signed immediate, fold it.
2004 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2005 getI32Imm(Imm & 0xFFFF)), 0);
2007 // For non-equality comparisons, the default code would materialize the
2008 // constant, then compare against it, like this:
2010 // ori r2, r2, 22136
2012 // Since we are just comparing for equality, we can emit this instead:
2013 // xoris r0,r3,0x1234
2014 // cmpldi cr0,r0,0x5678
2016 if (isUInt<32>(Imm)) {
2017 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2018 getI64Imm(Imm >> 16)), 0);
2019 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2020 getI64Imm(Imm & 0xFFFF)), 0);
2024 } else if (ISD::isUnsignedIntSetCC(CC)) {
2025 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2026 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2027 getI64Imm(Imm & 0xFFFF)), 0);
2031 if (isIntS16Immediate(RHS, SImm))
2032 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2033 getI64Imm(SImm & 0xFFFF)),
2037 } else if (LHS.getValueType() == MVT::f32) {
2040 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2041 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2043 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2046 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2052 llvm_unreachable("Should be lowered by legalize!");
2053 default: llvm_unreachable("Unknown condition!");
2055 case ISD::SETEQ: return PPC::PRED_EQ;
2057 case ISD::SETNE: return PPC::PRED_NE;
2059 case ISD::SETLT: return PPC::PRED_LT;
2061 case ISD::SETLE: return PPC::PRED_LE;
2063 case ISD::SETGT: return PPC::PRED_GT;
2065 case ISD::SETGE: return PPC::PRED_GE;
2066 case ISD::SETO: return PPC::PRED_NU;
2067 case ISD::SETUO: return PPC::PRED_UN;
2068 // These two are invalid for floating point. Assume we have int.
2069 case ISD::SETULT: return PPC::PRED_LT;
2070 case ISD::SETUGT: return PPC::PRED_GT;
2074 /// getCRIdxForSetCC - Return the index of the condition register field
2075 /// associated with the SetCC condition, and whether or not the field is
2076 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2077 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2080 default: llvm_unreachable("Unknown condition!");
2082 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2084 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2086 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2087 case ISD::SETUO: return 3; // Bit #3 = SETUO
2089 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2091 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2093 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2094 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2099 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2100 // These are invalid for floating point. Assume integer.
2101 case ISD::SETULT: return 0;
2102 case ISD::SETUGT: return 1;
2106 // getVCmpInst: return the vector compare instruction for the specified
2107 // vector type and condition code. Since this is for altivec specific code,
2108 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
2109 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2110 bool HasVSX, bool &Swap, bool &Negate) {
2114 if (VecVT.isFloatingPoint()) {
2115 /* Handle some cases by swapping input operands. */
2117 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2118 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2119 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2120 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2121 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2122 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2125 /* Handle some cases by negating the result. */
2127 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2128 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2129 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2130 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2133 /* We have instructions implementing the remaining cases. */
2137 if (VecVT == MVT::v4f32)
2138 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2139 else if (VecVT == MVT::v2f64)
2140 return PPC::XVCMPEQDP;
2144 if (VecVT == MVT::v4f32)
2145 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2146 else if (VecVT == MVT::v2f64)
2147 return PPC::XVCMPGTDP;
2151 if (VecVT == MVT::v4f32)
2152 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2153 else if (VecVT == MVT::v2f64)
2154 return PPC::XVCMPGEDP;
2159 llvm_unreachable("Invalid floating-point vector compare condition");
2161 /* Handle some cases by swapping input operands. */
2163 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2164 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2165 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2166 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2169 /* Handle some cases by negating the result. */
2171 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2172 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2173 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2174 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2177 /* We have instructions implementing the remaining cases. */
2181 if (VecVT == MVT::v16i8)
2182 return PPC::VCMPEQUB;
2183 else if (VecVT == MVT::v8i16)
2184 return PPC::VCMPEQUH;
2185 else if (VecVT == MVT::v4i32)
2186 return PPC::VCMPEQUW;
2189 if (VecVT == MVT::v16i8)
2190 return PPC::VCMPGTSB;
2191 else if (VecVT == MVT::v8i16)
2192 return PPC::VCMPGTSH;
2193 else if (VecVT == MVT::v4i32)
2194 return PPC::VCMPGTSW;
2197 if (VecVT == MVT::v16i8)
2198 return PPC::VCMPGTUB;
2199 else if (VecVT == MVT::v8i16)
2200 return PPC::VCMPGTUH;
2201 else if (VecVT == MVT::v4i32)
2202 return PPC::VCMPGTUW;
2207 llvm_unreachable("Invalid integer vector compare condition");
2211 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2214 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2215 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2216 bool isPPC64 = (PtrVT == MVT::i64);
2218 if (!PPCSubTarget->useCRBits() &&
2219 isInt32Immediate(N->getOperand(1), Imm)) {
2220 // We can codegen setcc op, imm very efficiently compared to a brcond.
2221 // Check for those cases here.
2224 SDValue Op = N->getOperand(0);
2228 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2229 SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
2230 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2235 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2236 Op, getI32Imm(~0U)), 0);
2237 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2241 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2242 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2246 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2247 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2248 SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2249 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2252 } else if (Imm == ~0U) { // setcc op, -1
2253 SDValue Op = N->getOperand(0);
2258 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2259 Op, getI32Imm(1)), 0);
2260 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2261 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2267 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2268 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2269 Op, getI32Imm(~0U));
2270 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2271 Op, SDValue(AD, 1));
2274 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2276 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2278 SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2279 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2282 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2283 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2285 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2292 SDValue LHS = N->getOperand(0);
2293 SDValue RHS = N->getOperand(1);
2295 // Altivec Vector compare instructions do not set any CR register by default and
2296 // vector compare operations return the same type as the operands.
2297 if (LHS.getValueType().isVector()) {
2298 if (PPCSubTarget->hasQPX())
2301 EVT VecVT = LHS.getValueType();
2303 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2304 PPCSubTarget->hasVSX(), Swap, Negate);
2306 std::swap(LHS, RHS);
2309 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2310 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2315 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2318 if (PPCSubTarget->useCRBits())
2322 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2323 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2326 // Force the ccreg into CR7.
2327 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2329 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2330 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2331 InFlag).getValue(1);
2333 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2336 SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
2337 getI32Imm(31), getI32Imm(31) };
2339 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2341 // Get the specified bit.
2343 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2344 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
2347 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2348 // Transfer memoperands.
2349 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2350 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2351 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2356 // Select - Convert the specified operand from a target-independent to a
2357 // target-specific node if it hasn't already been changed.
2358 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2360 if (N->isMachineOpcode()) {
2362 return nullptr; // Already selected.
2365 // In case any misguided DAG-level optimizations form an ADD with a
2366 // TargetConstant operand, crash here instead of miscompiling (by selecting
2367 // an r+r add instead of some kind of r+i add).
2368 if (N->getOpcode() == ISD::ADD &&
2369 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2370 llvm_unreachable("Invalid ADD with TargetConstant operand");
2372 // Try matching complex bit permutations before doing anything else.
2373 if (SDNode *NN = SelectBitPermutation(N))
2376 switch (N->getOpcode()) {
2379 case ISD::Constant: {
2380 if (N->getValueType(0) == MVT::i64)
2381 return SelectInt64(CurDAG, N);
2386 SDNode *SN = SelectSETCC(N);
2391 case PPCISD::GlobalBaseReg:
2392 return getGlobalBaseReg();
2394 case ISD::FrameIndex:
2395 return getFrameIndex(N, N);
2397 case PPCISD::MFOCRF: {
2398 SDValue InFlag = N->getOperand(1);
2399 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2400 N->getOperand(0), InFlag);
2403 case PPCISD::READ_TIME_BASE: {
2404 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2405 MVT::Other, N->getOperand(0));
2408 case PPCISD::SRA_ADDZE: {
2409 SDValue N0 = N->getOperand(0);
2411 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2412 getConstantIntValue(), N->getValueType(0));
2413 if (N->getValueType(0) == MVT::i64) {
2415 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2417 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2418 SDValue(Op, 0), SDValue(Op, 1));
2420 assert(N->getValueType(0) == MVT::i32 &&
2421 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2423 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2425 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2426 SDValue(Op, 0), SDValue(Op, 1));
2431 // Handle preincrement loads.
2432 LoadSDNode *LD = cast<LoadSDNode>(N);
2433 EVT LoadedVT = LD->getMemoryVT();
2435 // Normal loads are handled by code generated from the .td file.
2436 if (LD->getAddressingMode() != ISD::PRE_INC)
2439 SDValue Offset = LD->getOffset();
2440 if (Offset.getOpcode() == ISD::TargetConstant ||
2441 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2444 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2445 if (LD->getValueType(0) != MVT::i64) {
2446 // Handle PPC32 integer and normal FP loads.
2447 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2448 switch (LoadedVT.getSimpleVT().SimpleTy) {
2449 default: llvm_unreachable("Invalid PPC load type!");
2450 case MVT::f64: Opcode = PPC::LFDU; break;
2451 case MVT::f32: Opcode = PPC::LFSU; break;
2452 case MVT::i32: Opcode = PPC::LWZU; break;
2453 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2455 case MVT::i8: Opcode = PPC::LBZU; break;
2458 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2459 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2460 switch (LoadedVT.getSimpleVT().SimpleTy) {
2461 default: llvm_unreachable("Invalid PPC load type!");
2462 case MVT::i64: Opcode = PPC::LDU; break;
2463 case MVT::i32: Opcode = PPC::LWZU8; break;
2464 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2466 case MVT::i8: Opcode = PPC::LBZU8; break;
2470 SDValue Chain = LD->getChain();
2471 SDValue Base = LD->getBasePtr();
2472 SDValue Ops[] = { Offset, Base, Chain };
2473 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2474 LD->getValueType(0),
2475 PPCLowering->getPointerTy(),
2479 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2480 if (LD->getValueType(0) != MVT::i64) {
2481 // Handle PPC32 integer and normal FP loads.
2482 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2483 switch (LoadedVT.getSimpleVT().SimpleTy) {
2484 default: llvm_unreachable("Invalid PPC load type!");
2485 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2486 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2487 case MVT::f64: Opcode = PPC::LFDUX; break;
2488 case MVT::f32: Opcode = PPC::LFSUX; break;
2489 case MVT::i32: Opcode = PPC::LWZUX; break;
2490 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2492 case MVT::i8: Opcode = PPC::LBZUX; break;
2495 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2496 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2497 "Invalid sext update load");
2498 switch (LoadedVT.getSimpleVT().SimpleTy) {
2499 default: llvm_unreachable("Invalid PPC load type!");
2500 case MVT::i64: Opcode = PPC::LDUX; break;
2501 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2502 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2504 case MVT::i8: Opcode = PPC::LBZUX8; break;
2508 SDValue Chain = LD->getChain();
2509 SDValue Base = LD->getBasePtr();
2510 SDValue Ops[] = { Base, Offset, Chain };
2511 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2512 LD->getValueType(0),
2513 PPCLowering->getPointerTy(),
2519 unsigned Imm, Imm2, SH, MB, ME;
2522 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2523 // with a mask, emit rlwinm
2524 if (isInt32Immediate(N->getOperand(1), Imm) &&
2525 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2526 SDValue Val = N->getOperand(0).getOperand(0);
2527 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2528 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2530 // If this is just a masked value where the input is not handled above, and
2531 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2532 if (isInt32Immediate(N->getOperand(1), Imm) &&
2533 isRunOfOnes(Imm, MB, ME) &&
2534 N->getOperand(0).getOpcode() != ISD::ROTL) {
2535 SDValue Val = N->getOperand(0);
2536 SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
2537 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2539 // If this is a 64-bit zero-extension mask, emit rldicl.
2540 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2542 SDValue Val = N->getOperand(0);
2543 MB = 64 - countTrailingOnes(Imm64);
2546 // If the operand is a logical right shift, we can fold it into this
2547 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2548 // for n <= mb. The right shift is really a left rotate followed by a
2549 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2551 if (Val.getOpcode() == ISD::SRL &&
2552 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2553 assert(Imm < 64 && "Illegal shift amount");
2554 Val = Val.getOperand(0);
2558 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
2559 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2561 // AND X, 0 -> 0, not "rlwinm 32".
2562 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2563 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2566 // ISD::OR doesn't get all the bitfield insertion fun.
2567 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2568 if (isInt32Immediate(N->getOperand(1), Imm) &&
2569 N->getOperand(0).getOpcode() == ISD::OR &&
2570 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2573 if (isRunOfOnes(Imm, MB, ME)) {
2574 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2575 N->getOperand(0).getOperand(1),
2576 getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
2577 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2581 // Other cases are autogenerated.
2585 if (N->getValueType(0) == MVT::i32)
2586 if (SDNode *I = SelectBitfieldInsert(N))
2590 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2591 isIntS16Immediate(N->getOperand(1), Imm)) {
2592 APInt LHSKnownZero, LHSKnownOne;
2593 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2595 // If this is equivalent to an add, then we can fold it with the
2596 // FrameIndex calculation.
2597 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2598 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2601 // Other cases are autogenerated.
2606 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2607 isIntS16Immediate(N->getOperand(1), Imm))
2608 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2613 unsigned Imm, SH, MB, ME;
2614 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2615 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2616 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2617 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2618 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2621 // Other cases are autogenerated.
2625 unsigned Imm, SH, MB, ME;
2626 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2627 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2628 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2629 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2630 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2633 // Other cases are autogenerated.
2636 // FIXME: Remove this once the ANDI glue bug is fixed:
2637 case PPCISD::ANDIo_1_EQ_BIT:
2638 case PPCISD::ANDIo_1_GT_BIT: {
2642 EVT InVT = N->getOperand(0).getValueType();
2643 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2644 "Invalid input type for ANDIo_1_EQ_BIT");
2646 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2647 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2649 CurDAG->getTargetConstant(1, InVT)), 0);
2650 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2652 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2653 PPC::sub_eq : PPC::sub_gt, MVT::i32);
2655 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2657 SDValue(AndI.getNode(), 1) /* glue */);
2659 case ISD::SELECT_CC: {
2660 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2661 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2662 bool isPPC64 = (PtrVT == MVT::i64);
2664 // If this is a select of i1 operands, we'll pattern match it.
2665 if (PPCSubTarget->useCRBits() &&
2666 N->getOperand(0).getValueType() == MVT::i1)
2669 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2671 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2672 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2673 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2674 if (N1C->isNullValue() && N3C->isNullValue() &&
2675 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2676 // FIXME: Implement this optzn for PPC64.
2677 N->getValueType(0) == MVT::i32) {
2679 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2680 N->getOperand(0), getI32Imm(~0U));
2681 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2682 SDValue(Tmp, 0), N->getOperand(0),
2686 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2688 if (N->getValueType(0) == MVT::i1) {
2689 // An i1 select is: (c & t) | (!c & f).
2691 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2695 default: llvm_unreachable("Invalid CC index");
2696 case 0: SRI = PPC::sub_lt; break;
2697 case 1: SRI = PPC::sub_gt; break;
2698 case 2: SRI = PPC::sub_eq; break;
2699 case 3: SRI = PPC::sub_un; break;
2702 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2704 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2706 SDValue C = Inv ? NotCCBit : CCBit,
2707 NotC = Inv ? CCBit : NotCCBit;
2709 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2710 C, N->getOperand(2)), 0);
2711 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2712 NotC, N->getOperand(3)), 0);
2714 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2717 unsigned BROpc = getPredicateForSetCC(CC);
2719 unsigned SelectCCOp;
2720 if (N->getValueType(0) == MVT::i32)
2721 SelectCCOp = PPC::SELECT_CC_I4;
2722 else if (N->getValueType(0) == MVT::i64)
2723 SelectCCOp = PPC::SELECT_CC_I8;
2724 else if (N->getValueType(0) == MVT::f32)
2725 SelectCCOp = PPC::SELECT_CC_F4;
2726 else if (N->getValueType(0) == MVT::f64)
2727 if (PPCSubTarget->hasVSX())
2728 SelectCCOp = PPC::SELECT_CC_VSFRC;
2730 SelectCCOp = PPC::SELECT_CC_F8;
2731 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2732 SelectCCOp = PPC::SELECT_CC_QFRC;
2733 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2734 SelectCCOp = PPC::SELECT_CC_QSRC;
2735 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2736 SelectCCOp = PPC::SELECT_CC_QBRC;
2737 else if (N->getValueType(0) == MVT::v2f64 ||
2738 N->getValueType(0) == MVT::v2i64)
2739 SelectCCOp = PPC::SELECT_CC_VSRC;
2741 SelectCCOp = PPC::SELECT_CC_VRRC;
2743 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2745 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2748 if (PPCSubTarget->hasVSX()) {
2749 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2750 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2754 case ISD::VECTOR_SHUFFLE:
2755 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2756 N->getValueType(0) == MVT::v2i64)) {
2757 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2759 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2760 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2763 for (int i = 0; i < 2; ++i)
2764 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2769 // For little endian, we must swap the input operands and adjust
2770 // the mask elements (reverse and invert them).
2771 if (PPCSubTarget->isLittleEndian()) {
2772 std::swap(Op1, Op2);
2773 unsigned tmp = DM[0];
2778 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
2780 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2781 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2782 isa<LoadSDNode>(Op1.getOperand(0))) {
2783 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2784 SDValue Base, Offset;
2786 if (LD->isUnindexed() &&
2787 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2788 SDValue Chain = LD->getChain();
2789 SDValue Ops[] = { Base, Offset, Chain };
2790 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2791 N->getValueType(0), Ops);
2795 SDValue Ops[] = { Op1, Op2, DMV };
2796 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2802 bool IsPPC64 = PPCSubTarget->isPPC64();
2803 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2804 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2805 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2806 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2809 case PPCISD::COND_BRANCH: {
2810 // Op #0 is the Chain.
2811 // Op #1 is the PPC::PRED_* number.
2813 // Op #3 is the Dest MBB
2814 // Op #4 is the Flag.
2815 // Prevent PPC::PRED_* from being selected into LI.
2817 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
2818 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2819 N->getOperand(0), N->getOperand(4) };
2820 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2823 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2824 unsigned PCC = getPredicateForSetCC(CC);
2826 if (N->getOperand(2).getValueType() == MVT::i1) {
2830 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2831 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2832 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2833 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2834 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2835 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2836 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2839 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2840 N->getOperand(Swap ? 3 : 2),
2841 N->getOperand(Swap ? 2 : 3)), 0);
2842 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2843 BitComp, N->getOperand(4), N->getOperand(0));
2846 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2847 SDValue Ops[] = { getI32Imm(PCC), CondCode,
2848 N->getOperand(4), N->getOperand(0) };
2849 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2852 // FIXME: Should custom lower this.
2853 SDValue Chain = N->getOperand(0);
2854 SDValue Target = N->getOperand(1);
2855 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2856 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2857 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2859 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2861 case PPCISD::TOC_ENTRY: {
2862 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2863 "Only supported for 64-bit ABI and 32-bit SVR4");
2864 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2865 SDValue GA = N->getOperand(0);
2866 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2867 MVT::i32, GA, N->getOperand(1)));
2870 // For medium and large code model, we generate two instructions as
2871 // described below. Otherwise we allow SelectCodeCommon to handle this,
2872 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2873 CodeModel::Model CModel = TM.getCodeModel();
2874 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2877 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2878 // If it is an externally defined symbol, a symbol with common linkage,
2879 // a non-local function address, or a jump table address, or if we are
2880 // generating code for large code model, we generate:
2881 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2882 // Otherwise we generate:
2883 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2884 SDValue GA = N->getOperand(0);
2885 SDValue TOCbase = N->getOperand(1);
2886 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2889 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2890 CModel == CodeModel::Large)
2891 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2892 MVT::i64, GA, SDValue(Tmp, 0)));
2894 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2895 const GlobalValue *GValue = G->getGlobal();
2896 if ((GValue->getType()->getElementType()->isFunctionTy() &&
2897 (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2898 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2899 GValue->hasAvailableExternallyLinkage())
2900 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2901 MVT::i64, GA, SDValue(Tmp, 0)));
2904 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2905 SDValue(Tmp, 0), GA);
2907 case PPCISD::PPC32_PICGOT: {
2908 // Generate a PIC-safe GOT reference.
2909 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2910 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2911 return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(), MVT::i32);
2913 case PPCISD::VADD_SPLAT: {
2914 // This expands into one of three sequences, depending on whether
2915 // the first operand is odd or even, positive or negative.
2916 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2917 isa<ConstantSDNode>(N->getOperand(1)) &&
2918 "Invalid operand on VADD_SPLAT!");
2920 int Elt = N->getConstantOperandVal(0);
2921 int EltSize = N->getConstantOperandVal(1);
2922 unsigned Opc1, Opc2, Opc3;
2926 Opc1 = PPC::VSPLTISB;
2927 Opc2 = PPC::VADDUBM;
2928 Opc3 = PPC::VSUBUBM;
2930 } else if (EltSize == 2) {
2931 Opc1 = PPC::VSPLTISH;
2932 Opc2 = PPC::VADDUHM;
2933 Opc3 = PPC::VSUBUHM;
2936 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2937 Opc1 = PPC::VSPLTISW;
2938 Opc2 = PPC::VADDUWM;
2939 Opc3 = PPC::VSUBUWM;
2943 if ((Elt & 1) == 0) {
2944 // Elt is even, in the range [-32,-18] + [16,30].
2946 // Convert: VADD_SPLAT elt, size
2947 // Into: tmp = VSPLTIS[BHW] elt
2948 // VADDU[BHW]M tmp, tmp
2949 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2950 SDValue EltVal = getI32Imm(Elt >> 1);
2951 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2952 SDValue TmpVal = SDValue(Tmp, 0);
2953 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2955 } else if (Elt > 0) {
2956 // Elt is odd and positive, in the range [17,31].
2958 // Convert: VADD_SPLAT elt, size
2959 // Into: tmp1 = VSPLTIS[BHW] elt-16
2960 // tmp2 = VSPLTIS[BHW] -16
2961 // VSUBU[BHW]M tmp1, tmp2
2962 SDValue EltVal = getI32Imm(Elt - 16);
2963 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2964 EltVal = getI32Imm(-16);
2965 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2966 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2970 // Elt is odd and negative, in the range [-31,-17].
2972 // Convert: VADD_SPLAT elt, size
2973 // Into: tmp1 = VSPLTIS[BHW] elt+16
2974 // tmp2 = VSPLTIS[BHW] -16
2975 // VADDU[BHW]M tmp1, tmp2
2976 SDValue EltVal = getI32Imm(Elt + 16);
2977 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2978 EltVal = getI32Imm(-16);
2979 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2980 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
2986 return SelectCode(N);
2989 // If the target supports the cmpb instruction, do the idiom recognition here.
2990 // We don't do this as a DAG combine because we don't want to do it as nodes
2991 // are being combined (because we might miss part of the eventual idiom). We
2992 // don't want to do it during instruction selection because we want to reuse
2993 // the logic for lowering the masking operations already part of the
2994 // instruction selector.
2995 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
2998 assert(N->getOpcode() == ISD::OR &&
2999 "Only OR nodes are supported for CMPB");
3002 if (!PPCSubTarget->hasCMPB())
3005 if (N->getValueType(0) != MVT::i32 &&
3006 N->getValueType(0) != MVT::i64)
3009 EVT VT = N->getValueType(0);
3012 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3013 uint64_t Mask = 0, Alt = 0;
3015 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3016 uint64_t &Mask, uint64_t &Alt,
3017 SDValue &LHS, SDValue &RHS) {
3018 if (O.getOpcode() != ISD::SELECT_CC)
3020 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3022 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3023 !isa<ConstantSDNode>(O.getOperand(3)))
3026 uint64_t PM = O.getConstantOperandVal(2);
3027 uint64_t PAlt = O.getConstantOperandVal(3);
3028 for (b = 0; b < 8; ++b) {
3029 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3030 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3039 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3040 O.getConstantOperandVal(1) != 0) {
3041 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3042 if (Op0.getOpcode() == ISD::TRUNCATE)
3043 Op0 = Op0.getOperand(0);
3044 if (Op1.getOpcode() == ISD::TRUNCATE)
3045 Op1 = Op1.getOperand(0);
3047 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3048 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3049 isa<ConstantSDNode>(Op0.getOperand(1))) {
3051 unsigned Bits = Op0.getValueType().getSizeInBits();
3054 if (Op0.getConstantOperandVal(1) != Bits-8)
3057 LHS = Op0.getOperand(0);
3058 RHS = Op1.getOperand(0);
3062 // When we have small integers (i16 to be specific), the form present
3063 // post-legalization uses SETULT in the SELECT_CC for the
3064 // higher-order byte, depending on the fact that the
3065 // even-higher-order bytes are known to all be zero, for example:
3066 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3067 // (so when the second byte is the same, because all higher-order
3068 // bits from bytes 3 and 4 are known to be zero, the result of the
3069 // xor can be at most 255)
3070 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3071 isa<ConstantSDNode>(O.getOperand(1))) {
3073 uint64_t ULim = O.getConstantOperandVal(1);
3074 if (ULim != (UINT64_C(1) << b*8))
3077 // Now we need to make sure that the upper bytes are known to be
3079 unsigned Bits = Op0.getValueType().getSizeInBits();
3080 if (!CurDAG->MaskedValueIsZero(Op0,
3081 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3084 LHS = Op0.getOperand(0);
3085 RHS = Op0.getOperand(1);
3092 if (CC != ISD::SETEQ)
3095 SDValue Op = O.getOperand(0);
3096 if (Op.getOpcode() == ISD::AND) {
3097 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3099 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3102 SDValue XOR = Op.getOperand(0);
3103 if (XOR.getOpcode() == ISD::TRUNCATE)
3104 XOR = XOR.getOperand(0);
3105 if (XOR.getOpcode() != ISD::XOR)
3108 LHS = XOR.getOperand(0);
3109 RHS = XOR.getOperand(1);
3111 } else if (Op.getOpcode() == ISD::SRL) {
3112 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3114 unsigned Bits = Op.getValueType().getSizeInBits();
3117 if (Op.getConstantOperandVal(1) != Bits-8)
3120 SDValue XOR = Op.getOperand(0);
3121 if (XOR.getOpcode() == ISD::TRUNCATE)
3122 XOR = XOR.getOperand(0);
3123 if (XOR.getOpcode() != ISD::XOR)
3126 LHS = XOR.getOperand(0);
3127 RHS = XOR.getOperand(1);
3134 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3135 while (!Queue.empty()) {
3136 SDValue V = Queue.pop_back_val();
3138 for (const SDValue &O : V.getNode()->ops()) {
3140 uint64_t M = 0, A = 0;
3142 if (O.getOpcode() == ISD::OR) {
3144 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3148 BytesFound[b] = true;
3151 } else if ((LHS == ORHS && RHS == OLHS) ||
3152 (RHS == ORHS && LHS == OLHS)) {
3153 BytesFound[b] = true;
3165 unsigned LastB = 0, BCnt = 0;
3166 for (unsigned i = 0; i < 8; ++i)
3167 if (BytesFound[LastB]) {
3172 if (!LastB || BCnt < 2)
3175 // Because we'll be zero-extending the output anyway if don't have a specific
3176 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3177 if (LHS.getValueType() != VT) {
3178 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3179 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3182 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3184 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3185 if (NonTrivialMask && !Alt) {
3186 // Res = Mask & CMPB
3187 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, CurDAG->getConstant(Mask, VT));
3189 // Res = (CMPB & Mask) | (~CMPB & Alt)
3190 // Which, as suggested here:
3191 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3192 // can be written as:
3193 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3194 // useful because the (Alt ^ Mask) can be pre-computed.
3195 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3196 CurDAG->getConstant(Mask ^ Alt, VT));
3197 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, CurDAG->getConstant(Alt, VT));
3203 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3204 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3205 // involves constant materialization of a 0 or a 1 or both. If the result of
3206 // the extension is then operated upon by some operator that can be constant
3207 // folded with a constant 0 or 1, and that constant can be materialized using
3208 // only one instruction (like a zero or one), then we should fold in those
3209 // operations with the select.
3210 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3211 if (!PPCSubTarget->useCRBits())
3214 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3215 N->getOpcode() != ISD::SIGN_EXTEND &&
3216 N->getOpcode() != ISD::ANY_EXTEND)
3219 if (N->getOperand(0).getValueType() != MVT::i1)
3222 if (!N->hasOneUse())
3226 EVT VT = N->getValueType(0);
3227 SDValue Cond = N->getOperand(0);
3229 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, VT);
3230 SDValue ConstFalse = CurDAG->getConstant(0, VT);
3233 SDNode *User = *N->use_begin();
3234 if (User->getNumOperands() != 2)
3237 auto TryFold = [this, N, User](SDValue Val) {
3238 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3239 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3240 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3242 return CurDAG->FoldConstantArithmetic(User->getOpcode(),
3243 User->getValueType(0),
3244 O0.getNode(), O1.getNode());
3247 SDValue TrueRes = TryFold(ConstTrue);
3250 SDValue FalseRes = TryFold(ConstFalse);
3254 // For us to materialize these using one instruction, we must be able to
3255 // represent them as signed 16-bit integers.
3256 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3257 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3258 if (!isInt<16>(True) || !isInt<16>(False))
3261 // We can replace User with a new SELECT node, and try again to see if we
3262 // can fold the select with its user.
3263 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3265 ConstTrue = TrueRes;
3266 ConstFalse = FalseRes;
3267 } while (N->hasOneUse());
3270 void PPCDAGToDAGISel::PreprocessISelDAG() {
3271 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3274 bool MadeChange = false;
3275 while (Position != CurDAG->allnodes_begin()) {
3276 SDNode *N = --Position;
3281 switch (N->getOpcode()) {
3284 Res = combineToCMPB(N);
3289 foldBoolExts(Res, N);
3292 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3293 DEBUG(N->dump(CurDAG));
3294 DEBUG(dbgs() << "\nNew: ");
3295 DEBUG(Res.getNode()->dump(CurDAG));
3296 DEBUG(dbgs() << "\n");
3298 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3304 CurDAG->RemoveDeadNodes();
3307 /// PostprocessISelDAG - Perform some late peephole optimizations
3308 /// on the DAG representation.
3309 void PPCDAGToDAGISel::PostprocessISelDAG() {
3311 // Skip peepholes at -O0.
3312 if (TM.getOptLevel() == CodeGenOpt::None)
3317 PeepholePPC64ZExt();
3320 // Check if all users of this node will become isel where the second operand
3321 // is the constant zero. If this is so, and if we can negate the condition,
3322 // then we can flip the true and false operands. This will allow the zero to
3323 // be folded with the isel so that we don't need to materialize a register
3325 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3326 // If we're not using isel, then this does not matter.
3327 if (!PPCSubTarget->hasISEL())
3330 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3333 if (!User->isMachineOpcode())
3335 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3336 User->getMachineOpcode() != PPC::SELECT_I8)
3339 SDNode *Op2 = User->getOperand(2).getNode();
3340 if (!Op2->isMachineOpcode())
3343 if (Op2->getMachineOpcode() != PPC::LI &&
3344 Op2->getMachineOpcode() != PPC::LI8)
3347 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3351 if (!C->isNullValue())
3358 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3359 SmallVector<SDNode *, 4> ToReplace;
3360 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3363 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3364 User->getMachineOpcode() == PPC::SELECT_I8) &&
3365 "Must have all select users");
3366 ToReplace.push_back(User);
3369 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3370 UE = ToReplace.end(); UI != UE; ++UI) {
3373 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3374 User->getValueType(0), User->getOperand(0),
3375 User->getOperand(2),
3376 User->getOperand(1));
3378 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3379 DEBUG(User->dump(CurDAG));
3380 DEBUG(dbgs() << "\nNew: ");
3381 DEBUG(ResNode->dump(CurDAG));
3382 DEBUG(dbgs() << "\n");
3384 ReplaceUses(User, ResNode);
3388 void PPCDAGToDAGISel::PeepholeCROps() {
3392 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3393 E = CurDAG->allnodes_end(); I != E; ++I) {
3394 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3395 if (!MachineNode || MachineNode->use_empty())
3397 SDNode *ResNode = MachineNode;
3399 bool Op1Set = false, Op1Unset = false,
3401 Op2Set = false, Op2Unset = false,
3404 unsigned Opcode = MachineNode->getMachineOpcode();
3415 SDValue Op = MachineNode->getOperand(1);
3416 if (Op.isMachineOpcode()) {
3417 if (Op.getMachineOpcode() == PPC::CRSET)
3419 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3421 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3422 Op.getOperand(0) == Op.getOperand(1))
3428 case PPC::SELECT_I4:
3429 case PPC::SELECT_I8:
3430 case PPC::SELECT_F4:
3431 case PPC::SELECT_F8:
3432 case PPC::SELECT_QFRC:
3433 case PPC::SELECT_QSRC:
3434 case PPC::SELECT_QBRC:
3435 case PPC::SELECT_VRRC:
3436 case PPC::SELECT_VSFRC:
3437 case PPC::SELECT_VSRC: {
3438 SDValue Op = MachineNode->getOperand(0);
3439 if (Op.isMachineOpcode()) {
3440 if (Op.getMachineOpcode() == PPC::CRSET)
3442 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3444 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3445 Op.getOperand(0) == Op.getOperand(1))
3452 bool SelectSwap = false;
3456 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3458 ResNode = MachineNode->getOperand(0).getNode();
3461 ResNode = MachineNode->getOperand(1).getNode();
3464 ResNode = MachineNode->getOperand(0).getNode();
3465 else if (Op1Unset || Op2Unset)
3466 // x & 0 = 0 & y = 0
3467 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3470 // ~x & y = andc(y, x)
3471 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3472 MVT::i1, MachineNode->getOperand(1),
3473 MachineNode->getOperand(0).
3476 // x & ~y = andc(x, y)
3477 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3478 MVT::i1, MachineNode->getOperand(0),
3479 MachineNode->getOperand(1).
3481 else if (AllUsersSelectZero(MachineNode))
3482 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3483 MVT::i1, MachineNode->getOperand(0),
3484 MachineNode->getOperand(1)),
3488 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3489 // nand(x, x) -> nor(x, x)
3490 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3491 MVT::i1, MachineNode->getOperand(0),
3492 MachineNode->getOperand(0));
3494 // nand(1, y) -> nor(y, y)
3495 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3496 MVT::i1, MachineNode->getOperand(1),
3497 MachineNode->getOperand(1));
3499 // nand(x, 1) -> nor(x, x)
3500 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3501 MVT::i1, MachineNode->getOperand(0),
3502 MachineNode->getOperand(0));
3503 else if (Op1Unset || Op2Unset)
3504 // nand(x, 0) = nand(0, y) = 1
3505 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3508 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3509 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3510 MVT::i1, MachineNode->getOperand(0).
3512 MachineNode->getOperand(1));
3514 // nand(x, ~y) = ~x | y = orc(y, x)
3515 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3516 MVT::i1, MachineNode->getOperand(1).
3518 MachineNode->getOperand(0));
3519 else if (AllUsersSelectZero(MachineNode))
3520 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3521 MVT::i1, MachineNode->getOperand(0),
3522 MachineNode->getOperand(1)),
3526 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3528 ResNode = MachineNode->getOperand(0).getNode();
3529 else if (Op1Set || Op2Set)
3530 // x | 1 = 1 | y = 1
3531 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3535 ResNode = MachineNode->getOperand(1).getNode();
3538 ResNode = MachineNode->getOperand(0).getNode();
3540 // ~x | y = orc(y, x)
3541 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3542 MVT::i1, MachineNode->getOperand(1),
3543 MachineNode->getOperand(0).
3546 // x | ~y = orc(x, y)
3547 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3548 MVT::i1, MachineNode->getOperand(0),
3549 MachineNode->getOperand(1).
3551 else if (AllUsersSelectZero(MachineNode))
3552 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3553 MVT::i1, MachineNode->getOperand(0),
3554 MachineNode->getOperand(1)),
3558 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3560 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3563 // xor(1, y) -> nor(y, y)
3564 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3565 MVT::i1, MachineNode->getOperand(1),
3566 MachineNode->getOperand(1));
3568 // xor(x, 1) -> nor(x, x)
3569 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3570 MVT::i1, MachineNode->getOperand(0),
3571 MachineNode->getOperand(0));
3574 ResNode = MachineNode->getOperand(1).getNode();
3577 ResNode = MachineNode->getOperand(0).getNode();
3579 // xor(~x, y) = eqv(x, y)
3580 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3581 MVT::i1, MachineNode->getOperand(0).
3583 MachineNode->getOperand(1));
3585 // xor(x, ~y) = eqv(x, y)
3586 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3587 MVT::i1, MachineNode->getOperand(0),
3588 MachineNode->getOperand(1).
3590 else if (AllUsersSelectZero(MachineNode))
3591 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3592 MVT::i1, MachineNode->getOperand(0),
3593 MachineNode->getOperand(1)),
3597 if (Op1Set || Op2Set)
3599 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3602 // nor(0, y) = ~y -> nor(y, y)
3603 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3604 MVT::i1, MachineNode->getOperand(1),
3605 MachineNode->getOperand(1));
3608 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3609 MVT::i1, MachineNode->getOperand(0),
3610 MachineNode->getOperand(0));
3612 // nor(~x, y) = andc(x, y)
3613 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3614 MVT::i1, MachineNode->getOperand(0).
3616 MachineNode->getOperand(1));
3618 // nor(x, ~y) = andc(y, x)
3619 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3620 MVT::i1, MachineNode->getOperand(1).
3622 MachineNode->getOperand(0));
3623 else if (AllUsersSelectZero(MachineNode))
3624 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3625 MVT::i1, MachineNode->getOperand(0),
3626 MachineNode->getOperand(1)),
3630 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3632 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3636 ResNode = MachineNode->getOperand(1).getNode();
3639 ResNode = MachineNode->getOperand(0).getNode();
3641 // eqv(0, y) = ~y -> nor(y, y)
3642 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3643 MVT::i1, MachineNode->getOperand(1),
3644 MachineNode->getOperand(1));
3647 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3648 MVT::i1, MachineNode->getOperand(0),
3649 MachineNode->getOperand(0));
3651 // eqv(~x, y) = xor(x, y)
3652 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3653 MVT::i1, MachineNode->getOperand(0).
3655 MachineNode->getOperand(1));
3657 // eqv(x, ~y) = xor(x, y)
3658 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3659 MVT::i1, MachineNode->getOperand(0),
3660 MachineNode->getOperand(1).
3662 else if (AllUsersSelectZero(MachineNode))
3663 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3664 MVT::i1, MachineNode->getOperand(0),
3665 MachineNode->getOperand(1)),
3669 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3671 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3675 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3676 MVT::i1, MachineNode->getOperand(1),
3677 MachineNode->getOperand(1));
3678 else if (Op1Unset || Op2Set)
3679 // andc(0, y) = andc(x, 1) = 0
3680 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3684 ResNode = MachineNode->getOperand(0).getNode();
3686 // andc(~x, y) = ~(x | y) = nor(x, y)
3687 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3688 MVT::i1, MachineNode->getOperand(0).
3690 MachineNode->getOperand(1));
3692 // andc(x, ~y) = x & y
3693 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3694 MVT::i1, MachineNode->getOperand(0),
3695 MachineNode->getOperand(1).
3697 else if (AllUsersSelectZero(MachineNode))
3698 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3699 MVT::i1, MachineNode->getOperand(1),
3700 MachineNode->getOperand(0)),
3704 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3706 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3708 else if (Op1Set || Op2Unset)
3709 // orc(1, y) = orc(x, 0) = 1
3710 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3714 ResNode = MachineNode->getOperand(0).getNode();
3717 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3718 MVT::i1, MachineNode->getOperand(1),
3719 MachineNode->getOperand(1));
3721 // orc(~x, y) = ~(x & y) = nand(x, y)
3722 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3723 MVT::i1, MachineNode->getOperand(0).
3725 MachineNode->getOperand(1));
3727 // orc(x, ~y) = x | y
3728 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3729 MVT::i1, MachineNode->getOperand(0),
3730 MachineNode->getOperand(1).
3732 else if (AllUsersSelectZero(MachineNode))
3733 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3734 MVT::i1, MachineNode->getOperand(1),
3735 MachineNode->getOperand(0)),
3738 case PPC::SELECT_I4:
3739 case PPC::SELECT_I8:
3740 case PPC::SELECT_F4:
3741 case PPC::SELECT_F8:
3742 case PPC::SELECT_QFRC:
3743 case PPC::SELECT_QSRC:
3744 case PPC::SELECT_QBRC:
3745 case PPC::SELECT_VRRC:
3746 case PPC::SELECT_VSFRC:
3747 case PPC::SELECT_VSRC:
3749 ResNode = MachineNode->getOperand(1).getNode();
3751 ResNode = MachineNode->getOperand(2).getNode();
3753 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3755 MachineNode->getValueType(0),
3756 MachineNode->getOperand(0).
3758 MachineNode->getOperand(2),
3759 MachineNode->getOperand(1));
3764 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3768 MachineNode->getOperand(0).
3770 MachineNode->getOperand(1),
3771 MachineNode->getOperand(2));
3772 // FIXME: Handle Op1Set, Op1Unset here too.
3776 // If we're inverting this node because it is used only by selects that
3777 // we'd like to swap, then swap the selects before the node replacement.
3779 SwapAllSelectUsers(MachineNode);
3781 if (ResNode != MachineNode) {
3782 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3783 DEBUG(MachineNode->dump(CurDAG));
3784 DEBUG(dbgs() << "\nNew: ");
3785 DEBUG(ResNode->dump(CurDAG));
3786 DEBUG(dbgs() << "\n");
3788 ReplaceUses(MachineNode, ResNode);
3793 CurDAG->RemoveDeadNodes();
3794 } while (IsModified);
3797 // Gather the set of 32-bit operations that are known to have their
3798 // higher-order 32 bits zero, where ToPromote contains all such operations.
3799 static bool PeepholePPC64ZExtGather(SDValue Op32,
3800 SmallPtrSetImpl<SDNode *> &ToPromote) {
3801 if (!Op32.isMachineOpcode())
3804 // First, check for the "frontier" instructions (those that will clear the
3805 // higher-order 32 bits.
3807 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3808 // around. If it does not, then these instructions will clear the
3809 // higher-order bits.
3810 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3811 Op32.getMachineOpcode() == PPC::RLWNM) &&
3812 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3813 ToPromote.insert(Op32.getNode());
3817 // SLW and SRW always clear the higher-order bits.
3818 if (Op32.getMachineOpcode() == PPC::SLW ||
3819 Op32.getMachineOpcode() == PPC::SRW) {
3820 ToPromote.insert(Op32.getNode());
3824 // For LI and LIS, we need the immediate to be positive (so that it is not
3826 if (Op32.getMachineOpcode() == PPC::LI ||
3827 Op32.getMachineOpcode() == PPC::LIS) {
3828 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3831 ToPromote.insert(Op32.getNode());
3835 // LHBRX and LWBRX always clear the higher-order bits.
3836 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3837 Op32.getMachineOpcode() == PPC::LWBRX) {
3838 ToPromote.insert(Op32.getNode());
3842 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3843 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3844 ToPromote.insert(Op32.getNode());
3848 // Next, check for those instructions we can look through.
3850 // Assuming the mask does not wrap around, then the higher-order bits are
3851 // taken directly from the first operand.
3852 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3853 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3854 SmallPtrSet<SDNode *, 16> ToPromote1;
3855 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3858 ToPromote.insert(Op32.getNode());
3859 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3863 // For OR, the higher-order bits are zero if that is true for both operands.
3864 // For SELECT_I4, the same is true (but the relevant operand numbers are
3866 if (Op32.getMachineOpcode() == PPC::OR ||
3867 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3868 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3869 SmallPtrSet<SDNode *, 16> ToPromote1;
3870 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3872 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3875 ToPromote.insert(Op32.getNode());
3876 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3880 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3881 // zero, and also for the constant to be positive (so that it is not sign
3883 if (Op32.getMachineOpcode() == PPC::ORI ||
3884 Op32.getMachineOpcode() == PPC::ORIS) {
3885 SmallPtrSet<SDNode *, 16> ToPromote1;
3886 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3888 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3891 ToPromote.insert(Op32.getNode());
3892 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3896 // The higher-order bits of AND are zero if that is true for at least one of
3898 if (Op32.getMachineOpcode() == PPC::AND) {
3899 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3901 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3903 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3904 if (!Op0OK && !Op1OK)
3907 ToPromote.insert(Op32.getNode());
3910 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3913 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3918 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3919 // of the first operand, or if the second operand is positive (so that it is
3920 // not sign extended).
3921 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3922 Op32.getMachineOpcode() == PPC::ANDISo) {
3923 SmallPtrSet<SDNode *, 16> ToPromote1;
3925 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3926 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3927 if (!Op0OK && !Op1OK)
3930 ToPromote.insert(Op32.getNode());
3933 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3941 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3942 if (!PPCSubTarget->isPPC64())
3945 // When we zero-extend from i32 to i64, we use a pattern like this:
3946 // def : Pat<(i64 (zext i32:$in)),
3947 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3949 // There are several 32-bit shift/rotate instructions, however, that will
3950 // clear the higher-order bits of their output, rendering the RLDICL
3951 // unnecessary. When that happens, we remove it here, and redefine the
3952 // relevant 32-bit operation to be a 64-bit operation.
3954 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3957 bool MadeChange = false;
3958 while (Position != CurDAG->allnodes_begin()) {
3959 SDNode *N = --Position;
3960 // Skip dead nodes and any non-machine opcodes.
3961 if (N->use_empty() || !N->isMachineOpcode())
3964 if (N->getMachineOpcode() != PPC::RLDICL)
3967 if (N->getConstantOperandVal(1) != 0 ||
3968 N->getConstantOperandVal(2) != 32)
3971 SDValue ISR = N->getOperand(0);
3972 if (!ISR.isMachineOpcode() ||
3973 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3976 if (!ISR.hasOneUse())
3979 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
3982 SDValue IDef = ISR.getOperand(0);
3983 if (!IDef.isMachineOpcode() ||
3984 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
3987 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
3988 // can get rid of it.
3990 SDValue Op32 = ISR->getOperand(1);
3991 if (!Op32.isMachineOpcode())
3994 // There are some 32-bit instructions that always clear the high-order 32
3995 // bits, there are also some instructions (like AND) that we can look
3997 SmallPtrSet<SDNode *, 16> ToPromote;
3998 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4001 // If the ToPromote set contains nodes that have uses outside of the set
4002 // (except for the original INSERT_SUBREG), then abort the transformation.
4003 bool OutsideUse = false;
4004 for (SDNode *PN : ToPromote) {
4005 for (SDNode *UN : PN->uses()) {
4006 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4020 // We now know that this zero extension can be removed by promoting to
4021 // nodes in ToPromote to 64-bit operations, where for operations in the
4022 // frontier of the set, we need to insert INSERT_SUBREGs for their
4024 for (SDNode *PN : ToPromote) {
4026 switch (PN->getMachineOpcode()) {
4028 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4029 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4030 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4031 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4032 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4033 case PPC::LI: NewOpcode = PPC::LI8; break;
4034 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4035 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4036 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4037 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4038 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4039 case PPC::OR: NewOpcode = PPC::OR8; break;
4040 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4041 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4042 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4043 case PPC::AND: NewOpcode = PPC::AND8; break;
4044 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4045 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4048 // Note: During the replacement process, the nodes will be in an
4049 // inconsistent state (some instructions will have operands with values
4050 // of the wrong type). Once done, however, everything should be right
4053 SmallVector<SDValue, 4> Ops;
4054 for (const SDValue &V : PN->ops()) {
4055 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4056 !isa<ConstantSDNode>(V)) {
4057 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4059 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4060 ISR.getNode()->getVTList(), ReplOpOps);
4061 Ops.push_back(SDValue(ReplOp, 0));
4067 // Because all to-be-promoted nodes only have users that are other
4068 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4069 // the i32 result value type with i64.
4071 SmallVector<EVT, 2> NewVTs;
4072 SDVTList VTs = PN->getVTList();
4073 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4074 if (VTs.VTs[i] == MVT::i32)
4075 NewVTs.push_back(MVT::i64);
4077 NewVTs.push_back(VTs.VTs[i]);
4079 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4080 DEBUG(PN->dump(CurDAG));
4082 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4084 DEBUG(dbgs() << "\nNew: ");
4085 DEBUG(PN->dump(CurDAG));
4086 DEBUG(dbgs() << "\n");
4089 // Now we replace the original zero extend and its associated INSERT_SUBREG
4090 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4093 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4094 DEBUG(N->dump(CurDAG));
4095 DEBUG(dbgs() << "\nNew: ");
4096 DEBUG(Op32.getNode()->dump(CurDAG));
4097 DEBUG(dbgs() << "\n");
4099 ReplaceUses(N, Op32.getNode());
4103 CurDAG->RemoveDeadNodes();
4106 void PPCDAGToDAGISel::PeepholePPC64() {
4107 // These optimizations are currently supported only for 64-bit SVR4.
4108 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4111 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4114 while (Position != CurDAG->allnodes_begin()) {
4115 SDNode *N = --Position;
4116 // Skip dead nodes and any non-machine opcodes.
4117 if (N->use_empty() || !N->isMachineOpcode())
4121 unsigned StorageOpcode = N->getMachineOpcode();
4123 switch (StorageOpcode) {
4154 // If this is a load or store with a zero offset, we may be able to
4155 // fold an add-immediate into the memory operation.
4156 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
4157 N->getConstantOperandVal(FirstOp) != 0)
4160 SDValue Base = N->getOperand(FirstOp + 1);
4161 if (!Base.isMachineOpcode())
4165 bool ReplaceFlags = true;
4167 // When the feeding operation is an add-immediate of some sort,
4168 // determine whether we need to add relocation information to the
4169 // target flags on the immediate operand when we fold it into the
4170 // load instruction.
4172 // For something like ADDItocL, the relocation information is
4173 // inferred from the opcode; when we process it in the AsmPrinter,
4174 // we add the necessary relocation there. A load, though, can receive
4175 // relocation from various flavors of ADDIxxx, so we need to carry
4176 // the relocation information in the target flags.
4177 switch (Base.getMachineOpcode()) {
4182 // In some cases (such as TLS) the relocation information
4183 // is already in place on the operand, so copying the operand
4185 ReplaceFlags = false;
4186 // For these cases, the immediate may not be divisible by 4, in
4187 // which case the fold is illegal for DS-form instructions. (The
4188 // other cases provide aligned addresses and are always safe.)
4189 if ((StorageOpcode == PPC::LWA ||
4190 StorageOpcode == PPC::LD ||
4191 StorageOpcode == PPC::STD) &&
4192 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4193 Base.getConstantOperandVal(1) % 4 != 0))
4196 case PPC::ADDIdtprelL:
4197 Flags = PPCII::MO_DTPREL_LO;
4199 case PPC::ADDItlsldL:
4200 Flags = PPCII::MO_TLSLD_LO;
4203 Flags = PPCII::MO_TOC_LO;
4207 // We found an opportunity. Reverse the operands from the add
4208 // immediate and substitute them into the load or store. If
4209 // needed, update the target flags for the immediate operand to
4210 // reflect the necessary relocation information.
4211 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4212 DEBUG(Base->dump(CurDAG));
4213 DEBUG(dbgs() << "\nN: ");
4214 DEBUG(N->dump(CurDAG));
4215 DEBUG(dbgs() << "\n");
4217 SDValue ImmOpnd = Base.getOperand(1);
4219 // If the relocation information isn't already present on the
4220 // immediate operand, add it now.
4222 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4224 const GlobalValue *GV = GA->getGlobal();
4225 // We can't perform this optimization for data whose alignment
4226 // is insufficient for the instruction encoding.
4227 if (GV->getAlignment() < 4 &&
4228 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4229 StorageOpcode == PPC::LWA)) {
4230 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4233 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4234 } else if (ConstantPoolSDNode *CP =
4235 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4236 const Constant *C = CP->getConstVal();
4237 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4243 if (FirstOp == 1) // Store
4244 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4245 Base.getOperand(0), N->getOperand(3));
4247 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4250 // The add-immediate may now be dead, in which case remove it.
4251 if (Base.getNode()->use_empty())
4252 CurDAG->RemoveDeadNode(Base.getNode());
4257 /// createPPCISelDag - This pass converts a legalized DAG into a
4258 /// PowerPC-specific DAG, ready for instruction scheduling.
4260 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4261 return new PPCDAGToDAGISel(TM);
4264 static void initializePassOnce(PassRegistry &Registry) {
4265 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4266 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4267 nullptr, false, false);
4268 Registry.registerPass(*PI, true);
4271 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4272 CALL_ONCE_INITIALIZATION(initializePassOnce);