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, v2i64, 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;
2187 else if (VecVT == MVT::v2i64)
2188 return PPC::VCMPEQUD;
2191 if (VecVT == MVT::v16i8)
2192 return PPC::VCMPGTSB;
2193 else if (VecVT == MVT::v8i16)
2194 return PPC::VCMPGTSH;
2195 else if (VecVT == MVT::v4i32)
2196 return PPC::VCMPGTSW;
2197 else if (VecVT == MVT::v2i64)
2198 return PPC::VCMPGTSD;
2201 if (VecVT == MVT::v16i8)
2202 return PPC::VCMPGTUB;
2203 else if (VecVT == MVT::v8i16)
2204 return PPC::VCMPGTUH;
2205 else if (VecVT == MVT::v4i32)
2206 return PPC::VCMPGTUW;
2207 else if (VecVT == MVT::v2i64)
2208 return PPC::VCMPGTUD;
2213 llvm_unreachable("Invalid integer vector compare condition");
2217 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2220 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2221 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2222 bool isPPC64 = (PtrVT == MVT::i64);
2224 if (!PPCSubTarget->useCRBits() &&
2225 isInt32Immediate(N->getOperand(1), Imm)) {
2226 // We can codegen setcc op, imm very efficiently compared to a brcond.
2227 // Check for those cases here.
2230 SDValue Op = N->getOperand(0);
2234 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2235 SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
2236 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2241 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2242 Op, getI32Imm(~0U)), 0);
2243 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2247 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2248 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2252 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2253 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2254 SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2255 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2258 } else if (Imm == ~0U) { // setcc op, -1
2259 SDValue Op = N->getOperand(0);
2264 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2265 Op, getI32Imm(1)), 0);
2266 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2267 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2273 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2274 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2275 Op, getI32Imm(~0U));
2276 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2277 Op, SDValue(AD, 1));
2280 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2282 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2284 SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2285 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2288 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2289 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2291 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2298 SDValue LHS = N->getOperand(0);
2299 SDValue RHS = N->getOperand(1);
2301 // Altivec Vector compare instructions do not set any CR register by default and
2302 // vector compare operations return the same type as the operands.
2303 if (LHS.getValueType().isVector()) {
2304 if (PPCSubTarget->hasQPX())
2307 EVT VecVT = LHS.getValueType();
2309 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2310 PPCSubTarget->hasVSX(), Swap, Negate);
2312 std::swap(LHS, RHS);
2315 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2316 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2321 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2324 if (PPCSubTarget->useCRBits())
2328 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2329 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2332 // Force the ccreg into CR7.
2333 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2335 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2336 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2337 InFlag).getValue(1);
2339 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2342 SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
2343 getI32Imm(31), getI32Imm(31) };
2345 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2347 // Get the specified bit.
2349 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2350 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
2353 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2354 // Transfer memoperands.
2355 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2356 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2357 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2362 // Select - Convert the specified operand from a target-independent to a
2363 // target-specific node if it hasn't already been changed.
2364 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2366 if (N->isMachineOpcode()) {
2368 return nullptr; // Already selected.
2371 // In case any misguided DAG-level optimizations form an ADD with a
2372 // TargetConstant operand, crash here instead of miscompiling (by selecting
2373 // an r+r add instead of some kind of r+i add).
2374 if (N->getOpcode() == ISD::ADD &&
2375 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2376 llvm_unreachable("Invalid ADD with TargetConstant operand");
2378 // Try matching complex bit permutations before doing anything else.
2379 if (SDNode *NN = SelectBitPermutation(N))
2382 switch (N->getOpcode()) {
2385 case ISD::Constant: {
2386 if (N->getValueType(0) == MVT::i64)
2387 return SelectInt64(CurDAG, N);
2392 SDNode *SN = SelectSETCC(N);
2397 case PPCISD::GlobalBaseReg:
2398 return getGlobalBaseReg();
2400 case ISD::FrameIndex:
2401 return getFrameIndex(N, N);
2403 case PPCISD::MFOCRF: {
2404 SDValue InFlag = N->getOperand(1);
2405 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2406 N->getOperand(0), InFlag);
2409 case PPCISD::READ_TIME_BASE: {
2410 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2411 MVT::Other, N->getOperand(0));
2414 case PPCISD::SRA_ADDZE: {
2415 SDValue N0 = N->getOperand(0);
2417 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2418 getConstantIntValue(), N->getValueType(0));
2419 if (N->getValueType(0) == MVT::i64) {
2421 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2423 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2424 SDValue(Op, 0), SDValue(Op, 1));
2426 assert(N->getValueType(0) == MVT::i32 &&
2427 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2429 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2431 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2432 SDValue(Op, 0), SDValue(Op, 1));
2437 // Handle preincrement loads.
2438 LoadSDNode *LD = cast<LoadSDNode>(N);
2439 EVT LoadedVT = LD->getMemoryVT();
2441 // Normal loads are handled by code generated from the .td file.
2442 if (LD->getAddressingMode() != ISD::PRE_INC)
2445 SDValue Offset = LD->getOffset();
2446 if (Offset.getOpcode() == ISD::TargetConstant ||
2447 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2450 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2451 if (LD->getValueType(0) != MVT::i64) {
2452 // Handle PPC32 integer and normal FP loads.
2453 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2454 switch (LoadedVT.getSimpleVT().SimpleTy) {
2455 default: llvm_unreachable("Invalid PPC load type!");
2456 case MVT::f64: Opcode = PPC::LFDU; break;
2457 case MVT::f32: Opcode = PPC::LFSU; break;
2458 case MVT::i32: Opcode = PPC::LWZU; break;
2459 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2461 case MVT::i8: Opcode = PPC::LBZU; break;
2464 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2465 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2466 switch (LoadedVT.getSimpleVT().SimpleTy) {
2467 default: llvm_unreachable("Invalid PPC load type!");
2468 case MVT::i64: Opcode = PPC::LDU; break;
2469 case MVT::i32: Opcode = PPC::LWZU8; break;
2470 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2472 case MVT::i8: Opcode = PPC::LBZU8; break;
2476 SDValue Chain = LD->getChain();
2477 SDValue Base = LD->getBasePtr();
2478 SDValue Ops[] = { Offset, Base, Chain };
2479 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2480 LD->getValueType(0),
2481 PPCLowering->getPointerTy(),
2485 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2486 if (LD->getValueType(0) != MVT::i64) {
2487 // Handle PPC32 integer and normal FP loads.
2488 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2489 switch (LoadedVT.getSimpleVT().SimpleTy) {
2490 default: llvm_unreachable("Invalid PPC load type!");
2491 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2492 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2493 case MVT::f64: Opcode = PPC::LFDUX; break;
2494 case MVT::f32: Opcode = PPC::LFSUX; break;
2495 case MVT::i32: Opcode = PPC::LWZUX; break;
2496 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2498 case MVT::i8: Opcode = PPC::LBZUX; break;
2501 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2502 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2503 "Invalid sext update load");
2504 switch (LoadedVT.getSimpleVT().SimpleTy) {
2505 default: llvm_unreachable("Invalid PPC load type!");
2506 case MVT::i64: Opcode = PPC::LDUX; break;
2507 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2508 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2510 case MVT::i8: Opcode = PPC::LBZUX8; break;
2514 SDValue Chain = LD->getChain();
2515 SDValue Base = LD->getBasePtr();
2516 SDValue Ops[] = { Base, Offset, Chain };
2517 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2518 LD->getValueType(0),
2519 PPCLowering->getPointerTy(),
2525 unsigned Imm, Imm2, SH, MB, ME;
2528 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2529 // with a mask, emit rlwinm
2530 if (isInt32Immediate(N->getOperand(1), Imm) &&
2531 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2532 SDValue Val = N->getOperand(0).getOperand(0);
2533 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2534 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2536 // If this is just a masked value where the input is not handled above, and
2537 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2538 if (isInt32Immediate(N->getOperand(1), Imm) &&
2539 isRunOfOnes(Imm, MB, ME) &&
2540 N->getOperand(0).getOpcode() != ISD::ROTL) {
2541 SDValue Val = N->getOperand(0);
2542 SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
2543 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2545 // If this is a 64-bit zero-extension mask, emit rldicl.
2546 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2548 SDValue Val = N->getOperand(0);
2549 MB = 64 - countTrailingOnes(Imm64);
2552 // If the operand is a logical right shift, we can fold it into this
2553 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2554 // for n <= mb. The right shift is really a left rotate followed by a
2555 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2557 if (Val.getOpcode() == ISD::SRL &&
2558 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2559 assert(Imm < 64 && "Illegal shift amount");
2560 Val = Val.getOperand(0);
2564 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
2565 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2567 // AND X, 0 -> 0, not "rlwinm 32".
2568 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2569 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2572 // ISD::OR doesn't get all the bitfield insertion fun.
2573 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2574 if (isInt32Immediate(N->getOperand(1), Imm) &&
2575 N->getOperand(0).getOpcode() == ISD::OR &&
2576 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2579 if (isRunOfOnes(Imm, MB, ME)) {
2580 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2581 N->getOperand(0).getOperand(1),
2582 getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
2583 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2587 // Other cases are autogenerated.
2591 if (N->getValueType(0) == MVT::i32)
2592 if (SDNode *I = SelectBitfieldInsert(N))
2596 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2597 isIntS16Immediate(N->getOperand(1), Imm)) {
2598 APInt LHSKnownZero, LHSKnownOne;
2599 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2601 // If this is equivalent to an add, then we can fold it with the
2602 // FrameIndex calculation.
2603 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2604 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2607 // Other cases are autogenerated.
2612 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2613 isIntS16Immediate(N->getOperand(1), Imm))
2614 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2619 unsigned Imm, SH, MB, ME;
2620 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2621 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2622 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2623 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2624 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2627 // Other cases are autogenerated.
2631 unsigned Imm, SH, MB, ME;
2632 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2633 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2634 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2635 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2636 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2639 // Other cases are autogenerated.
2642 // FIXME: Remove this once the ANDI glue bug is fixed:
2643 case PPCISD::ANDIo_1_EQ_BIT:
2644 case PPCISD::ANDIo_1_GT_BIT: {
2648 EVT InVT = N->getOperand(0).getValueType();
2649 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2650 "Invalid input type for ANDIo_1_EQ_BIT");
2652 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2653 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2655 CurDAG->getTargetConstant(1, InVT)), 0);
2656 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2658 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2659 PPC::sub_eq : PPC::sub_gt, MVT::i32);
2661 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2663 SDValue(AndI.getNode(), 1) /* glue */);
2665 case ISD::SELECT_CC: {
2666 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2667 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2668 bool isPPC64 = (PtrVT == MVT::i64);
2670 // If this is a select of i1 operands, we'll pattern match it.
2671 if (PPCSubTarget->useCRBits() &&
2672 N->getOperand(0).getValueType() == MVT::i1)
2675 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2677 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2678 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2679 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2680 if (N1C->isNullValue() && N3C->isNullValue() &&
2681 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2682 // FIXME: Implement this optzn for PPC64.
2683 N->getValueType(0) == MVT::i32) {
2685 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2686 N->getOperand(0), getI32Imm(~0U));
2687 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2688 SDValue(Tmp, 0), N->getOperand(0),
2692 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2694 if (N->getValueType(0) == MVT::i1) {
2695 // An i1 select is: (c & t) | (!c & f).
2697 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2701 default: llvm_unreachable("Invalid CC index");
2702 case 0: SRI = PPC::sub_lt; break;
2703 case 1: SRI = PPC::sub_gt; break;
2704 case 2: SRI = PPC::sub_eq; break;
2705 case 3: SRI = PPC::sub_un; break;
2708 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2710 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2712 SDValue C = Inv ? NotCCBit : CCBit,
2713 NotC = Inv ? CCBit : NotCCBit;
2715 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2716 C, N->getOperand(2)), 0);
2717 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2718 NotC, N->getOperand(3)), 0);
2720 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2723 unsigned BROpc = getPredicateForSetCC(CC);
2725 unsigned SelectCCOp;
2726 if (N->getValueType(0) == MVT::i32)
2727 SelectCCOp = PPC::SELECT_CC_I4;
2728 else if (N->getValueType(0) == MVT::i64)
2729 SelectCCOp = PPC::SELECT_CC_I8;
2730 else if (N->getValueType(0) == MVT::f32)
2731 SelectCCOp = PPC::SELECT_CC_F4;
2732 else if (N->getValueType(0) == MVT::f64)
2733 if (PPCSubTarget->hasVSX())
2734 SelectCCOp = PPC::SELECT_CC_VSFRC;
2736 SelectCCOp = PPC::SELECT_CC_F8;
2737 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2738 SelectCCOp = PPC::SELECT_CC_QFRC;
2739 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2740 SelectCCOp = PPC::SELECT_CC_QSRC;
2741 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2742 SelectCCOp = PPC::SELECT_CC_QBRC;
2743 else if (N->getValueType(0) == MVT::v2f64 ||
2744 N->getValueType(0) == MVT::v2i64)
2745 SelectCCOp = PPC::SELECT_CC_VSRC;
2747 SelectCCOp = PPC::SELECT_CC_VRRC;
2749 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2751 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2754 if (PPCSubTarget->hasVSX()) {
2755 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2756 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2760 case ISD::VECTOR_SHUFFLE:
2761 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2762 N->getValueType(0) == MVT::v2i64)) {
2763 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2765 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2766 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2769 for (int i = 0; i < 2; ++i)
2770 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2775 // For little endian, we must swap the input operands and adjust
2776 // the mask elements (reverse and invert them).
2777 if (PPCSubTarget->isLittleEndian()) {
2778 std::swap(Op1, Op2);
2779 unsigned tmp = DM[0];
2784 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
2786 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2787 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2788 isa<LoadSDNode>(Op1.getOperand(0))) {
2789 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2790 SDValue Base, Offset;
2792 if (LD->isUnindexed() &&
2793 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2794 SDValue Chain = LD->getChain();
2795 SDValue Ops[] = { Base, Offset, Chain };
2796 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2797 N->getValueType(0), Ops);
2801 SDValue Ops[] = { Op1, Op2, DMV };
2802 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2808 bool IsPPC64 = PPCSubTarget->isPPC64();
2809 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2810 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2811 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2812 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2815 case PPCISD::COND_BRANCH: {
2816 // Op #0 is the Chain.
2817 // Op #1 is the PPC::PRED_* number.
2819 // Op #3 is the Dest MBB
2820 // Op #4 is the Flag.
2821 // Prevent PPC::PRED_* from being selected into LI.
2823 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
2824 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2825 N->getOperand(0), N->getOperand(4) };
2826 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2829 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2830 unsigned PCC = getPredicateForSetCC(CC);
2832 if (N->getOperand(2).getValueType() == MVT::i1) {
2836 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2837 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2838 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2839 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2840 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2841 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2842 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2845 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2846 N->getOperand(Swap ? 3 : 2),
2847 N->getOperand(Swap ? 2 : 3)), 0);
2848 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2849 BitComp, N->getOperand(4), N->getOperand(0));
2852 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2853 SDValue Ops[] = { getI32Imm(PCC), CondCode,
2854 N->getOperand(4), N->getOperand(0) };
2855 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2858 // FIXME: Should custom lower this.
2859 SDValue Chain = N->getOperand(0);
2860 SDValue Target = N->getOperand(1);
2861 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2862 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2863 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2865 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2867 case PPCISD::TOC_ENTRY: {
2868 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2869 "Only supported for 64-bit ABI and 32-bit SVR4");
2870 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2871 SDValue GA = N->getOperand(0);
2872 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2873 MVT::i32, GA, N->getOperand(1)));
2876 // For medium and large code model, we generate two instructions as
2877 // described below. Otherwise we allow SelectCodeCommon to handle this,
2878 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2879 CodeModel::Model CModel = TM.getCodeModel();
2880 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2883 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2884 // If it is an externally defined symbol, a symbol with common linkage,
2885 // a non-local function address, or a jump table address, or if we are
2886 // generating code for large code model, we generate:
2887 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2888 // Otherwise we generate:
2889 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2890 SDValue GA = N->getOperand(0);
2891 SDValue TOCbase = N->getOperand(1);
2892 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2895 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2896 CModel == CodeModel::Large)
2897 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2898 MVT::i64, GA, SDValue(Tmp, 0)));
2900 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2901 const GlobalValue *GValue = G->getGlobal();
2902 if ((GValue->getType()->getElementType()->isFunctionTy() &&
2903 (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2904 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2905 GValue->hasAvailableExternallyLinkage())
2906 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2907 MVT::i64, GA, SDValue(Tmp, 0)));
2910 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2911 SDValue(Tmp, 0), GA);
2913 case PPCISD::PPC32_PICGOT: {
2914 // Generate a PIC-safe GOT reference.
2915 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2916 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2917 return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(), MVT::i32);
2919 case PPCISD::VADD_SPLAT: {
2920 // This expands into one of three sequences, depending on whether
2921 // the first operand is odd or even, positive or negative.
2922 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2923 isa<ConstantSDNode>(N->getOperand(1)) &&
2924 "Invalid operand on VADD_SPLAT!");
2926 int Elt = N->getConstantOperandVal(0);
2927 int EltSize = N->getConstantOperandVal(1);
2928 unsigned Opc1, Opc2, Opc3;
2932 Opc1 = PPC::VSPLTISB;
2933 Opc2 = PPC::VADDUBM;
2934 Opc3 = PPC::VSUBUBM;
2936 } else if (EltSize == 2) {
2937 Opc1 = PPC::VSPLTISH;
2938 Opc2 = PPC::VADDUHM;
2939 Opc3 = PPC::VSUBUHM;
2942 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2943 Opc1 = PPC::VSPLTISW;
2944 Opc2 = PPC::VADDUWM;
2945 Opc3 = PPC::VSUBUWM;
2949 if ((Elt & 1) == 0) {
2950 // Elt is even, in the range [-32,-18] + [16,30].
2952 // Convert: VADD_SPLAT elt, size
2953 // Into: tmp = VSPLTIS[BHW] elt
2954 // VADDU[BHW]M tmp, tmp
2955 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2956 SDValue EltVal = getI32Imm(Elt >> 1);
2957 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2958 SDValue TmpVal = SDValue(Tmp, 0);
2959 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2961 } else if (Elt > 0) {
2962 // Elt is odd and positive, in the range [17,31].
2964 // Convert: VADD_SPLAT elt, size
2965 // Into: tmp1 = VSPLTIS[BHW] elt-16
2966 // tmp2 = VSPLTIS[BHW] -16
2967 // VSUBU[BHW]M tmp1, tmp2
2968 SDValue EltVal = getI32Imm(Elt - 16);
2969 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2970 EltVal = getI32Imm(-16);
2971 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2972 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2976 // Elt is odd and negative, in the range [-31,-17].
2978 // Convert: VADD_SPLAT elt, size
2979 // Into: tmp1 = VSPLTIS[BHW] elt+16
2980 // tmp2 = VSPLTIS[BHW] -16
2981 // VADDU[BHW]M tmp1, tmp2
2982 SDValue EltVal = getI32Imm(Elt + 16);
2983 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2984 EltVal = getI32Imm(-16);
2985 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2986 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
2992 return SelectCode(N);
2995 // If the target supports the cmpb instruction, do the idiom recognition here.
2996 // We don't do this as a DAG combine because we don't want to do it as nodes
2997 // are being combined (because we might miss part of the eventual idiom). We
2998 // don't want to do it during instruction selection because we want to reuse
2999 // the logic for lowering the masking operations already part of the
3000 // instruction selector.
3001 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3004 assert(N->getOpcode() == ISD::OR &&
3005 "Only OR nodes are supported for CMPB");
3008 if (!PPCSubTarget->hasCMPB())
3011 if (N->getValueType(0) != MVT::i32 &&
3012 N->getValueType(0) != MVT::i64)
3015 EVT VT = N->getValueType(0);
3018 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3019 uint64_t Mask = 0, Alt = 0;
3021 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3022 uint64_t &Mask, uint64_t &Alt,
3023 SDValue &LHS, SDValue &RHS) {
3024 if (O.getOpcode() != ISD::SELECT_CC)
3026 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3028 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3029 !isa<ConstantSDNode>(O.getOperand(3)))
3032 uint64_t PM = O.getConstantOperandVal(2);
3033 uint64_t PAlt = O.getConstantOperandVal(3);
3034 for (b = 0; b < 8; ++b) {
3035 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3036 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3045 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3046 O.getConstantOperandVal(1) != 0) {
3047 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3048 if (Op0.getOpcode() == ISD::TRUNCATE)
3049 Op0 = Op0.getOperand(0);
3050 if (Op1.getOpcode() == ISD::TRUNCATE)
3051 Op1 = Op1.getOperand(0);
3053 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3054 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3055 isa<ConstantSDNode>(Op0.getOperand(1))) {
3057 unsigned Bits = Op0.getValueType().getSizeInBits();
3060 if (Op0.getConstantOperandVal(1) != Bits-8)
3063 LHS = Op0.getOperand(0);
3064 RHS = Op1.getOperand(0);
3068 // When we have small integers (i16 to be specific), the form present
3069 // post-legalization uses SETULT in the SELECT_CC for the
3070 // higher-order byte, depending on the fact that the
3071 // even-higher-order bytes are known to all be zero, for example:
3072 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3073 // (so when the second byte is the same, because all higher-order
3074 // bits from bytes 3 and 4 are known to be zero, the result of the
3075 // xor can be at most 255)
3076 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3077 isa<ConstantSDNode>(O.getOperand(1))) {
3079 uint64_t ULim = O.getConstantOperandVal(1);
3080 if (ULim != (UINT64_C(1) << b*8))
3083 // Now we need to make sure that the upper bytes are known to be
3085 unsigned Bits = Op0.getValueType().getSizeInBits();
3086 if (!CurDAG->MaskedValueIsZero(Op0,
3087 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3090 LHS = Op0.getOperand(0);
3091 RHS = Op0.getOperand(1);
3098 if (CC != ISD::SETEQ)
3101 SDValue Op = O.getOperand(0);
3102 if (Op.getOpcode() == ISD::AND) {
3103 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3105 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3108 SDValue XOR = Op.getOperand(0);
3109 if (XOR.getOpcode() == ISD::TRUNCATE)
3110 XOR = XOR.getOperand(0);
3111 if (XOR.getOpcode() != ISD::XOR)
3114 LHS = XOR.getOperand(0);
3115 RHS = XOR.getOperand(1);
3117 } else if (Op.getOpcode() == ISD::SRL) {
3118 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3120 unsigned Bits = Op.getValueType().getSizeInBits();
3123 if (Op.getConstantOperandVal(1) != Bits-8)
3126 SDValue XOR = Op.getOperand(0);
3127 if (XOR.getOpcode() == ISD::TRUNCATE)
3128 XOR = XOR.getOperand(0);
3129 if (XOR.getOpcode() != ISD::XOR)
3132 LHS = XOR.getOperand(0);
3133 RHS = XOR.getOperand(1);
3140 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3141 while (!Queue.empty()) {
3142 SDValue V = Queue.pop_back_val();
3144 for (const SDValue &O : V.getNode()->ops()) {
3146 uint64_t M = 0, A = 0;
3148 if (O.getOpcode() == ISD::OR) {
3150 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3154 BytesFound[b] = true;
3157 } else if ((LHS == ORHS && RHS == OLHS) ||
3158 (RHS == ORHS && LHS == OLHS)) {
3159 BytesFound[b] = true;
3171 unsigned LastB = 0, BCnt = 0;
3172 for (unsigned i = 0; i < 8; ++i)
3173 if (BytesFound[LastB]) {
3178 if (!LastB || BCnt < 2)
3181 // Because we'll be zero-extending the output anyway if don't have a specific
3182 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3183 if (LHS.getValueType() != VT) {
3184 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3185 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3188 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3190 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3191 if (NonTrivialMask && !Alt) {
3192 // Res = Mask & CMPB
3193 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, CurDAG->getConstant(Mask, VT));
3195 // Res = (CMPB & Mask) | (~CMPB & Alt)
3196 // Which, as suggested here:
3197 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3198 // can be written as:
3199 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3200 // useful because the (Alt ^ Mask) can be pre-computed.
3201 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3202 CurDAG->getConstant(Mask ^ Alt, VT));
3203 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, CurDAG->getConstant(Alt, VT));
3209 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3210 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3211 // involves constant materialization of a 0 or a 1 or both. If the result of
3212 // the extension is then operated upon by some operator that can be constant
3213 // folded with a constant 0 or 1, and that constant can be materialized using
3214 // only one instruction (like a zero or one), then we should fold in those
3215 // operations with the select.
3216 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3217 if (!PPCSubTarget->useCRBits())
3220 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3221 N->getOpcode() != ISD::SIGN_EXTEND &&
3222 N->getOpcode() != ISD::ANY_EXTEND)
3225 if (N->getOperand(0).getValueType() != MVT::i1)
3228 if (!N->hasOneUse())
3232 EVT VT = N->getValueType(0);
3233 SDValue Cond = N->getOperand(0);
3235 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, VT);
3236 SDValue ConstFalse = CurDAG->getConstant(0, VT);
3239 SDNode *User = *N->use_begin();
3240 if (User->getNumOperands() != 2)
3243 auto TryFold = [this, N, User](SDValue Val) {
3244 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3245 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3246 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3248 return CurDAG->FoldConstantArithmetic(User->getOpcode(),
3249 User->getValueType(0),
3250 O0.getNode(), O1.getNode());
3253 SDValue TrueRes = TryFold(ConstTrue);
3256 SDValue FalseRes = TryFold(ConstFalse);
3260 // For us to materialize these using one instruction, we must be able to
3261 // represent them as signed 16-bit integers.
3262 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3263 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3264 if (!isInt<16>(True) || !isInt<16>(False))
3267 // We can replace User with a new SELECT node, and try again to see if we
3268 // can fold the select with its user.
3269 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3271 ConstTrue = TrueRes;
3272 ConstFalse = FalseRes;
3273 } while (N->hasOneUse());
3276 void PPCDAGToDAGISel::PreprocessISelDAG() {
3277 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3280 bool MadeChange = false;
3281 while (Position != CurDAG->allnodes_begin()) {
3282 SDNode *N = --Position;
3287 switch (N->getOpcode()) {
3290 Res = combineToCMPB(N);
3295 foldBoolExts(Res, N);
3298 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3299 DEBUG(N->dump(CurDAG));
3300 DEBUG(dbgs() << "\nNew: ");
3301 DEBUG(Res.getNode()->dump(CurDAG));
3302 DEBUG(dbgs() << "\n");
3304 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3310 CurDAG->RemoveDeadNodes();
3313 /// PostprocessISelDAG - Perform some late peephole optimizations
3314 /// on the DAG representation.
3315 void PPCDAGToDAGISel::PostprocessISelDAG() {
3317 // Skip peepholes at -O0.
3318 if (TM.getOptLevel() == CodeGenOpt::None)
3323 PeepholePPC64ZExt();
3326 // Check if all users of this node will become isel where the second operand
3327 // is the constant zero. If this is so, and if we can negate the condition,
3328 // then we can flip the true and false operands. This will allow the zero to
3329 // be folded with the isel so that we don't need to materialize a register
3331 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3332 // If we're not using isel, then this does not matter.
3333 if (!PPCSubTarget->hasISEL())
3336 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3339 if (!User->isMachineOpcode())
3341 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3342 User->getMachineOpcode() != PPC::SELECT_I8)
3345 SDNode *Op2 = User->getOperand(2).getNode();
3346 if (!Op2->isMachineOpcode())
3349 if (Op2->getMachineOpcode() != PPC::LI &&
3350 Op2->getMachineOpcode() != PPC::LI8)
3353 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3357 if (!C->isNullValue())
3364 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3365 SmallVector<SDNode *, 4> ToReplace;
3366 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3369 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3370 User->getMachineOpcode() == PPC::SELECT_I8) &&
3371 "Must have all select users");
3372 ToReplace.push_back(User);
3375 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3376 UE = ToReplace.end(); UI != UE; ++UI) {
3379 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3380 User->getValueType(0), User->getOperand(0),
3381 User->getOperand(2),
3382 User->getOperand(1));
3384 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3385 DEBUG(User->dump(CurDAG));
3386 DEBUG(dbgs() << "\nNew: ");
3387 DEBUG(ResNode->dump(CurDAG));
3388 DEBUG(dbgs() << "\n");
3390 ReplaceUses(User, ResNode);
3394 void PPCDAGToDAGISel::PeepholeCROps() {
3398 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3399 E = CurDAG->allnodes_end(); I != E; ++I) {
3400 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3401 if (!MachineNode || MachineNode->use_empty())
3403 SDNode *ResNode = MachineNode;
3405 bool Op1Set = false, Op1Unset = false,
3407 Op2Set = false, Op2Unset = false,
3410 unsigned Opcode = MachineNode->getMachineOpcode();
3421 SDValue Op = MachineNode->getOperand(1);
3422 if (Op.isMachineOpcode()) {
3423 if (Op.getMachineOpcode() == PPC::CRSET)
3425 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3427 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3428 Op.getOperand(0) == Op.getOperand(1))
3434 case PPC::SELECT_I4:
3435 case PPC::SELECT_I8:
3436 case PPC::SELECT_F4:
3437 case PPC::SELECT_F8:
3438 case PPC::SELECT_QFRC:
3439 case PPC::SELECT_QSRC:
3440 case PPC::SELECT_QBRC:
3441 case PPC::SELECT_VRRC:
3442 case PPC::SELECT_VSFRC:
3443 case PPC::SELECT_VSRC: {
3444 SDValue Op = MachineNode->getOperand(0);
3445 if (Op.isMachineOpcode()) {
3446 if (Op.getMachineOpcode() == PPC::CRSET)
3448 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3450 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3451 Op.getOperand(0) == Op.getOperand(1))
3458 bool SelectSwap = false;
3462 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3464 ResNode = MachineNode->getOperand(0).getNode();
3467 ResNode = MachineNode->getOperand(1).getNode();
3470 ResNode = MachineNode->getOperand(0).getNode();
3471 else if (Op1Unset || Op2Unset)
3472 // x & 0 = 0 & y = 0
3473 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3476 // ~x & y = andc(y, x)
3477 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3478 MVT::i1, MachineNode->getOperand(1),
3479 MachineNode->getOperand(0).
3482 // x & ~y = andc(x, y)
3483 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3484 MVT::i1, MachineNode->getOperand(0),
3485 MachineNode->getOperand(1).
3487 else if (AllUsersSelectZero(MachineNode))
3488 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3489 MVT::i1, MachineNode->getOperand(0),
3490 MachineNode->getOperand(1)),
3494 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3495 // nand(x, x) -> nor(x, x)
3496 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3497 MVT::i1, MachineNode->getOperand(0),
3498 MachineNode->getOperand(0));
3500 // nand(1, y) -> nor(y, y)
3501 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3502 MVT::i1, MachineNode->getOperand(1),
3503 MachineNode->getOperand(1));
3505 // nand(x, 1) -> nor(x, x)
3506 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3507 MVT::i1, MachineNode->getOperand(0),
3508 MachineNode->getOperand(0));
3509 else if (Op1Unset || Op2Unset)
3510 // nand(x, 0) = nand(0, y) = 1
3511 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3514 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3515 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3516 MVT::i1, MachineNode->getOperand(0).
3518 MachineNode->getOperand(1));
3520 // nand(x, ~y) = ~x | y = orc(y, x)
3521 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3522 MVT::i1, MachineNode->getOperand(1).
3524 MachineNode->getOperand(0));
3525 else if (AllUsersSelectZero(MachineNode))
3526 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3527 MVT::i1, MachineNode->getOperand(0),
3528 MachineNode->getOperand(1)),
3532 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3534 ResNode = MachineNode->getOperand(0).getNode();
3535 else if (Op1Set || Op2Set)
3536 // x | 1 = 1 | y = 1
3537 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3541 ResNode = MachineNode->getOperand(1).getNode();
3544 ResNode = MachineNode->getOperand(0).getNode();
3546 // ~x | y = orc(y, x)
3547 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3548 MVT::i1, MachineNode->getOperand(1),
3549 MachineNode->getOperand(0).
3552 // x | ~y = orc(x, y)
3553 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3554 MVT::i1, MachineNode->getOperand(0),
3555 MachineNode->getOperand(1).
3557 else if (AllUsersSelectZero(MachineNode))
3558 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3559 MVT::i1, MachineNode->getOperand(0),
3560 MachineNode->getOperand(1)),
3564 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3566 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3569 // xor(1, y) -> nor(y, y)
3570 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3571 MVT::i1, MachineNode->getOperand(1),
3572 MachineNode->getOperand(1));
3574 // xor(x, 1) -> nor(x, x)
3575 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3576 MVT::i1, MachineNode->getOperand(0),
3577 MachineNode->getOperand(0));
3580 ResNode = MachineNode->getOperand(1).getNode();
3583 ResNode = MachineNode->getOperand(0).getNode();
3585 // xor(~x, y) = eqv(x, y)
3586 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3587 MVT::i1, MachineNode->getOperand(0).
3589 MachineNode->getOperand(1));
3591 // xor(x, ~y) = eqv(x, y)
3592 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3593 MVT::i1, MachineNode->getOperand(0),
3594 MachineNode->getOperand(1).
3596 else if (AllUsersSelectZero(MachineNode))
3597 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3598 MVT::i1, MachineNode->getOperand(0),
3599 MachineNode->getOperand(1)),
3603 if (Op1Set || Op2Set)
3605 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3608 // nor(0, y) = ~y -> nor(y, y)
3609 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3610 MVT::i1, MachineNode->getOperand(1),
3611 MachineNode->getOperand(1));
3614 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3615 MVT::i1, MachineNode->getOperand(0),
3616 MachineNode->getOperand(0));
3618 // nor(~x, y) = andc(x, y)
3619 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3620 MVT::i1, MachineNode->getOperand(0).
3622 MachineNode->getOperand(1));
3624 // nor(x, ~y) = andc(y, x)
3625 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3626 MVT::i1, MachineNode->getOperand(1).
3628 MachineNode->getOperand(0));
3629 else if (AllUsersSelectZero(MachineNode))
3630 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3631 MVT::i1, MachineNode->getOperand(0),
3632 MachineNode->getOperand(1)),
3636 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3638 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3642 ResNode = MachineNode->getOperand(1).getNode();
3645 ResNode = MachineNode->getOperand(0).getNode();
3647 // eqv(0, y) = ~y -> nor(y, y)
3648 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3649 MVT::i1, MachineNode->getOperand(1),
3650 MachineNode->getOperand(1));
3653 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3654 MVT::i1, MachineNode->getOperand(0),
3655 MachineNode->getOperand(0));
3657 // eqv(~x, y) = xor(x, y)
3658 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3659 MVT::i1, MachineNode->getOperand(0).
3661 MachineNode->getOperand(1));
3663 // eqv(x, ~y) = xor(x, y)
3664 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3665 MVT::i1, MachineNode->getOperand(0),
3666 MachineNode->getOperand(1).
3668 else if (AllUsersSelectZero(MachineNode))
3669 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3670 MVT::i1, MachineNode->getOperand(0),
3671 MachineNode->getOperand(1)),
3675 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3677 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3681 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3682 MVT::i1, MachineNode->getOperand(1),
3683 MachineNode->getOperand(1));
3684 else if (Op1Unset || Op2Set)
3685 // andc(0, y) = andc(x, 1) = 0
3686 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3690 ResNode = MachineNode->getOperand(0).getNode();
3692 // andc(~x, y) = ~(x | y) = nor(x, y)
3693 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3694 MVT::i1, MachineNode->getOperand(0).
3696 MachineNode->getOperand(1));
3698 // andc(x, ~y) = x & y
3699 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3700 MVT::i1, MachineNode->getOperand(0),
3701 MachineNode->getOperand(1).
3703 else if (AllUsersSelectZero(MachineNode))
3704 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3705 MVT::i1, MachineNode->getOperand(1),
3706 MachineNode->getOperand(0)),
3710 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3712 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3714 else if (Op1Set || Op2Unset)
3715 // orc(1, y) = orc(x, 0) = 1
3716 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3720 ResNode = MachineNode->getOperand(0).getNode();
3723 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3724 MVT::i1, MachineNode->getOperand(1),
3725 MachineNode->getOperand(1));
3727 // orc(~x, y) = ~(x & y) = nand(x, y)
3728 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3729 MVT::i1, MachineNode->getOperand(0).
3731 MachineNode->getOperand(1));
3733 // orc(x, ~y) = x | y
3734 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3735 MVT::i1, MachineNode->getOperand(0),
3736 MachineNode->getOperand(1).
3738 else if (AllUsersSelectZero(MachineNode))
3739 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3740 MVT::i1, MachineNode->getOperand(1),
3741 MachineNode->getOperand(0)),
3744 case PPC::SELECT_I4:
3745 case PPC::SELECT_I8:
3746 case PPC::SELECT_F4:
3747 case PPC::SELECT_F8:
3748 case PPC::SELECT_QFRC:
3749 case PPC::SELECT_QSRC:
3750 case PPC::SELECT_QBRC:
3751 case PPC::SELECT_VRRC:
3752 case PPC::SELECT_VSFRC:
3753 case PPC::SELECT_VSRC:
3755 ResNode = MachineNode->getOperand(1).getNode();
3757 ResNode = MachineNode->getOperand(2).getNode();
3759 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3761 MachineNode->getValueType(0),
3762 MachineNode->getOperand(0).
3764 MachineNode->getOperand(2),
3765 MachineNode->getOperand(1));
3770 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3774 MachineNode->getOperand(0).
3776 MachineNode->getOperand(1),
3777 MachineNode->getOperand(2));
3778 // FIXME: Handle Op1Set, Op1Unset here too.
3782 // If we're inverting this node because it is used only by selects that
3783 // we'd like to swap, then swap the selects before the node replacement.
3785 SwapAllSelectUsers(MachineNode);
3787 if (ResNode != MachineNode) {
3788 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3789 DEBUG(MachineNode->dump(CurDAG));
3790 DEBUG(dbgs() << "\nNew: ");
3791 DEBUG(ResNode->dump(CurDAG));
3792 DEBUG(dbgs() << "\n");
3794 ReplaceUses(MachineNode, ResNode);
3799 CurDAG->RemoveDeadNodes();
3800 } while (IsModified);
3803 // Gather the set of 32-bit operations that are known to have their
3804 // higher-order 32 bits zero, where ToPromote contains all such operations.
3805 static bool PeepholePPC64ZExtGather(SDValue Op32,
3806 SmallPtrSetImpl<SDNode *> &ToPromote) {
3807 if (!Op32.isMachineOpcode())
3810 // First, check for the "frontier" instructions (those that will clear the
3811 // higher-order 32 bits.
3813 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3814 // around. If it does not, then these instructions will clear the
3815 // higher-order bits.
3816 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3817 Op32.getMachineOpcode() == PPC::RLWNM) &&
3818 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3819 ToPromote.insert(Op32.getNode());
3823 // SLW and SRW always clear the higher-order bits.
3824 if (Op32.getMachineOpcode() == PPC::SLW ||
3825 Op32.getMachineOpcode() == PPC::SRW) {
3826 ToPromote.insert(Op32.getNode());
3830 // For LI and LIS, we need the immediate to be positive (so that it is not
3832 if (Op32.getMachineOpcode() == PPC::LI ||
3833 Op32.getMachineOpcode() == PPC::LIS) {
3834 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3837 ToPromote.insert(Op32.getNode());
3841 // LHBRX and LWBRX always clear the higher-order bits.
3842 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3843 Op32.getMachineOpcode() == PPC::LWBRX) {
3844 ToPromote.insert(Op32.getNode());
3848 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3849 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3850 ToPromote.insert(Op32.getNode());
3854 // Next, check for those instructions we can look through.
3856 // Assuming the mask does not wrap around, then the higher-order bits are
3857 // taken directly from the first operand.
3858 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3859 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3860 SmallPtrSet<SDNode *, 16> ToPromote1;
3861 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3864 ToPromote.insert(Op32.getNode());
3865 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3869 // For OR, the higher-order bits are zero if that is true for both operands.
3870 // For SELECT_I4, the same is true (but the relevant operand numbers are
3872 if (Op32.getMachineOpcode() == PPC::OR ||
3873 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3874 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3875 SmallPtrSet<SDNode *, 16> ToPromote1;
3876 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3878 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3881 ToPromote.insert(Op32.getNode());
3882 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3886 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3887 // zero, and also for the constant to be positive (so that it is not sign
3889 if (Op32.getMachineOpcode() == PPC::ORI ||
3890 Op32.getMachineOpcode() == PPC::ORIS) {
3891 SmallPtrSet<SDNode *, 16> ToPromote1;
3892 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3894 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3897 ToPromote.insert(Op32.getNode());
3898 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3902 // The higher-order bits of AND are zero if that is true for at least one of
3904 if (Op32.getMachineOpcode() == PPC::AND) {
3905 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3907 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3909 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3910 if (!Op0OK && !Op1OK)
3913 ToPromote.insert(Op32.getNode());
3916 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3919 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3924 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3925 // of the first operand, or if the second operand is positive (so that it is
3926 // not sign extended).
3927 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3928 Op32.getMachineOpcode() == PPC::ANDISo) {
3929 SmallPtrSet<SDNode *, 16> ToPromote1;
3931 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3932 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3933 if (!Op0OK && !Op1OK)
3936 ToPromote.insert(Op32.getNode());
3939 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3947 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3948 if (!PPCSubTarget->isPPC64())
3951 // When we zero-extend from i32 to i64, we use a pattern like this:
3952 // def : Pat<(i64 (zext i32:$in)),
3953 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3955 // There are several 32-bit shift/rotate instructions, however, that will
3956 // clear the higher-order bits of their output, rendering the RLDICL
3957 // unnecessary. When that happens, we remove it here, and redefine the
3958 // relevant 32-bit operation to be a 64-bit operation.
3960 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3963 bool MadeChange = false;
3964 while (Position != CurDAG->allnodes_begin()) {
3965 SDNode *N = --Position;
3966 // Skip dead nodes and any non-machine opcodes.
3967 if (N->use_empty() || !N->isMachineOpcode())
3970 if (N->getMachineOpcode() != PPC::RLDICL)
3973 if (N->getConstantOperandVal(1) != 0 ||
3974 N->getConstantOperandVal(2) != 32)
3977 SDValue ISR = N->getOperand(0);
3978 if (!ISR.isMachineOpcode() ||
3979 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3982 if (!ISR.hasOneUse())
3985 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
3988 SDValue IDef = ISR.getOperand(0);
3989 if (!IDef.isMachineOpcode() ||
3990 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
3993 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
3994 // can get rid of it.
3996 SDValue Op32 = ISR->getOperand(1);
3997 if (!Op32.isMachineOpcode())
4000 // There are some 32-bit instructions that always clear the high-order 32
4001 // bits, there are also some instructions (like AND) that we can look
4003 SmallPtrSet<SDNode *, 16> ToPromote;
4004 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4007 // If the ToPromote set contains nodes that have uses outside of the set
4008 // (except for the original INSERT_SUBREG), then abort the transformation.
4009 bool OutsideUse = false;
4010 for (SDNode *PN : ToPromote) {
4011 for (SDNode *UN : PN->uses()) {
4012 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4026 // We now know that this zero extension can be removed by promoting to
4027 // nodes in ToPromote to 64-bit operations, where for operations in the
4028 // frontier of the set, we need to insert INSERT_SUBREGs for their
4030 for (SDNode *PN : ToPromote) {
4032 switch (PN->getMachineOpcode()) {
4034 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4035 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4036 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4037 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4038 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4039 case PPC::LI: NewOpcode = PPC::LI8; break;
4040 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4041 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4042 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4043 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4044 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4045 case PPC::OR: NewOpcode = PPC::OR8; break;
4046 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4047 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4048 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4049 case PPC::AND: NewOpcode = PPC::AND8; break;
4050 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4051 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4054 // Note: During the replacement process, the nodes will be in an
4055 // inconsistent state (some instructions will have operands with values
4056 // of the wrong type). Once done, however, everything should be right
4059 SmallVector<SDValue, 4> Ops;
4060 for (const SDValue &V : PN->ops()) {
4061 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4062 !isa<ConstantSDNode>(V)) {
4063 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4065 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4066 ISR.getNode()->getVTList(), ReplOpOps);
4067 Ops.push_back(SDValue(ReplOp, 0));
4073 // Because all to-be-promoted nodes only have users that are other
4074 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4075 // the i32 result value type with i64.
4077 SmallVector<EVT, 2> NewVTs;
4078 SDVTList VTs = PN->getVTList();
4079 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4080 if (VTs.VTs[i] == MVT::i32)
4081 NewVTs.push_back(MVT::i64);
4083 NewVTs.push_back(VTs.VTs[i]);
4085 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4086 DEBUG(PN->dump(CurDAG));
4088 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4090 DEBUG(dbgs() << "\nNew: ");
4091 DEBUG(PN->dump(CurDAG));
4092 DEBUG(dbgs() << "\n");
4095 // Now we replace the original zero extend and its associated INSERT_SUBREG
4096 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4099 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4100 DEBUG(N->dump(CurDAG));
4101 DEBUG(dbgs() << "\nNew: ");
4102 DEBUG(Op32.getNode()->dump(CurDAG));
4103 DEBUG(dbgs() << "\n");
4105 ReplaceUses(N, Op32.getNode());
4109 CurDAG->RemoveDeadNodes();
4112 void PPCDAGToDAGISel::PeepholePPC64() {
4113 // These optimizations are currently supported only for 64-bit SVR4.
4114 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4117 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4120 while (Position != CurDAG->allnodes_begin()) {
4121 SDNode *N = --Position;
4122 // Skip dead nodes and any non-machine opcodes.
4123 if (N->use_empty() || !N->isMachineOpcode())
4127 unsigned StorageOpcode = N->getMachineOpcode();
4129 switch (StorageOpcode) {
4160 // If this is a load or store with a zero offset, we may be able to
4161 // fold an add-immediate into the memory operation.
4162 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
4163 N->getConstantOperandVal(FirstOp) != 0)
4166 SDValue Base = N->getOperand(FirstOp + 1);
4167 if (!Base.isMachineOpcode())
4171 bool ReplaceFlags = true;
4173 // When the feeding operation is an add-immediate of some sort,
4174 // determine whether we need to add relocation information to the
4175 // target flags on the immediate operand when we fold it into the
4176 // load instruction.
4178 // For something like ADDItocL, the relocation information is
4179 // inferred from the opcode; when we process it in the AsmPrinter,
4180 // we add the necessary relocation there. A load, though, can receive
4181 // relocation from various flavors of ADDIxxx, so we need to carry
4182 // the relocation information in the target flags.
4183 switch (Base.getMachineOpcode()) {
4188 // In some cases (such as TLS) the relocation information
4189 // is already in place on the operand, so copying the operand
4191 ReplaceFlags = false;
4192 // For these cases, the immediate may not be divisible by 4, in
4193 // which case the fold is illegal for DS-form instructions. (The
4194 // other cases provide aligned addresses and are always safe.)
4195 if ((StorageOpcode == PPC::LWA ||
4196 StorageOpcode == PPC::LD ||
4197 StorageOpcode == PPC::STD) &&
4198 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4199 Base.getConstantOperandVal(1) % 4 != 0))
4202 case PPC::ADDIdtprelL:
4203 Flags = PPCII::MO_DTPREL_LO;
4205 case PPC::ADDItlsldL:
4206 Flags = PPCII::MO_TLSLD_LO;
4209 Flags = PPCII::MO_TOC_LO;
4213 // We found an opportunity. Reverse the operands from the add
4214 // immediate and substitute them into the load or store. If
4215 // needed, update the target flags for the immediate operand to
4216 // reflect the necessary relocation information.
4217 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4218 DEBUG(Base->dump(CurDAG));
4219 DEBUG(dbgs() << "\nN: ");
4220 DEBUG(N->dump(CurDAG));
4221 DEBUG(dbgs() << "\n");
4223 SDValue ImmOpnd = Base.getOperand(1);
4225 // If the relocation information isn't already present on the
4226 // immediate operand, add it now.
4228 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4230 const GlobalValue *GV = GA->getGlobal();
4231 // We can't perform this optimization for data whose alignment
4232 // is insufficient for the instruction encoding.
4233 if (GV->getAlignment() < 4 &&
4234 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4235 StorageOpcode == PPC::LWA)) {
4236 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4239 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4240 } else if (ConstantPoolSDNode *CP =
4241 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4242 const Constant *C = CP->getConstVal();
4243 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4249 if (FirstOp == 1) // Store
4250 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4251 Base.getOperand(0), N->getOperand(3));
4253 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4256 // The add-immediate may now be dead, in which case remove it.
4257 if (Base.getNode()->use_empty())
4258 CurDAG->RemoveDeadNode(Base.getNode());
4263 /// createPPCISelDag - This pass converts a legalized DAG into a
4264 /// PowerPC-specific DAG, ready for instruction scheduling.
4266 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4267 return new PPCDAGToDAGISel(TM);
4270 static void initializePassOnce(PassRegistry &Registry) {
4271 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4272 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4273 nullptr, false, false);
4274 Registry.registerPass(*PI, true);
4277 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4278 CALL_ONCE_INITIALIZATION(initializePassOnce);