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, SDLoc dl) {
94 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
97 /// getI64Imm - Return a target constant with the specified value, of type
99 inline SDValue getI64Imm(uint64_t Imm, SDLoc dl) {
100 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
103 /// getSmallIPtrImm - Return a target constant of pointer type.
104 inline SDValue getSmallIPtrImm(unsigned Imm, SDLoc dl) {
105 return CurDAG->getTargetConstant(
106 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
109 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
110 /// rotate and mask opcode and mask operation.
111 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
112 unsigned &SH, unsigned &MB, unsigned &ME);
114 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
115 /// base register. Return the virtual register that holds this value.
116 SDNode *getGlobalBaseReg();
118 SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
120 // Select - Convert the specified operand from a target-independent to a
121 // target-specific node if it hasn't already been changed.
122 SDNode *Select(SDNode *N) override;
124 SDNode *SelectBitfieldInsert(SDNode *N);
125 SDNode *SelectBitPermutation(SDNode *N);
127 /// SelectCC - Select a comparison of the specified values with the
128 /// specified condition code, returning the CR# of the expression.
129 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
131 /// SelectAddrImm - Returns true if the address N can be represented by
132 /// a base register plus a signed 16-bit displacement [r+imm].
133 bool SelectAddrImm(SDValue N, SDValue &Disp,
135 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
138 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
139 /// immediate field. Note that the operand at this point is already the
140 /// result of a prior SelectAddressRegImm call.
141 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
142 if (N.getOpcode() == ISD::TargetConstant ||
143 N.getOpcode() == ISD::TargetGlobalAddress) {
151 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
152 /// represented as an indexed [r+r] operation. Returns false if it can
153 /// be represented by [r+imm], which are preferred.
154 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
155 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
158 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
159 /// represented as an indexed [r+r] operation.
160 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
161 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
164 /// SelectAddrImmX4 - Returns true if the address N can be represented by
165 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
166 /// Suitable for use by STD and friends.
167 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
168 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
171 // Select an address into a single register.
172 bool SelectAddr(SDValue N, SDValue &Base) {
177 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
178 /// inline asm expressions. It is always correct to compute the value into
179 /// a register. The case of adding a (possibly relocatable) constant to a
180 /// register can be improved, but it is wrong to substitute Reg+Reg for
181 /// Reg in an asm, because the load or store opcode would have to change.
182 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
183 unsigned ConstraintID,
184 std::vector<SDValue> &OutOps) override {
186 switch(ConstraintID) {
188 errs() << "ConstraintID: " << ConstraintID << "\n";
189 llvm_unreachable("Unexpected asm memory constraint");
190 case InlineAsm::Constraint_es:
191 case InlineAsm::Constraint_i:
192 case InlineAsm::Constraint_m:
193 case InlineAsm::Constraint_o:
194 case InlineAsm::Constraint_Q:
195 case InlineAsm::Constraint_Z:
196 case InlineAsm::Constraint_Zy:
197 // We need to make sure that this one operand does not end up in r0
198 // (because we might end up lowering this as 0(%op)).
199 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
200 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
202 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
204 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
205 dl, Op.getValueType(),
208 OutOps.push_back(NewOp);
214 void InsertVRSaveCode(MachineFunction &MF);
216 const char *getPassName() const override {
217 return "PowerPC DAG->DAG Pattern Instruction Selection";
220 // Include the pieces autogenerated from the target description.
221 #include "PPCGenDAGISel.inc"
224 SDNode *SelectSETCC(SDNode *N);
226 void PeepholePPC64();
227 void PeepholePPC64ZExt();
228 void PeepholeCROps();
230 SDValue combineToCMPB(SDNode *N);
231 void foldBoolExts(SDValue &Res, SDNode *&N);
233 bool AllUsersSelectZero(SDNode *N);
234 void SwapAllSelectUsers(SDNode *N);
236 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
240 /// InsertVRSaveCode - Once the entire function has been instruction selected,
241 /// all virtual registers are created and all machine instructions are built,
242 /// check to see if we need to save/restore VRSAVE. If so, do it.
243 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
244 // Check to see if this function uses vector registers, which means we have to
245 // save and restore the VRSAVE register and update it with the regs we use.
247 // In this case, there will be virtual registers of vector type created
248 // by the scheduler. Detect them now.
249 bool HasVectorVReg = false;
250 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
251 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
252 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
253 HasVectorVReg = true;
257 if (!HasVectorVReg) return; // nothing to do.
259 // If we have a vector register, we want to emit code into the entry and exit
260 // blocks to save and restore the VRSAVE register. We do this here (instead
261 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
263 // 1. This (trivially) reduces the load on the register allocator, by not
264 // having to represent the live range of the VRSAVE register.
265 // 2. This (more significantly) allows us to create a temporary virtual
266 // register to hold the saved VRSAVE value, allowing this temporary to be
267 // register allocated, instead of forcing it to be spilled to the stack.
269 // Create two vregs - one to hold the VRSAVE register that is live-in to the
270 // function and one for the value after having bits or'd into it.
271 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
272 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
274 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
275 MachineBasicBlock &EntryBB = *Fn.begin();
277 // Emit the following code into the entry block:
278 // InVRSAVE = MFVRSAVE
279 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
280 // MTVRSAVE UpdatedVRSAVE
281 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
282 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
283 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
284 UpdatedVRSAVE).addReg(InVRSAVE);
285 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
287 // Find all return blocks, outputting a restore in each epilog.
288 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
289 if (BB->isReturnBlock()) {
290 IP = BB->end(); --IP;
292 // Skip over all terminator instructions, which are part of the return
294 MachineBasicBlock::iterator I2 = IP;
295 while (I2 != BB->begin() && (--I2)->isTerminator())
298 // Emit: MTVRSAVE InVRSave
299 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
305 /// getGlobalBaseReg - Output the instructions required to put the
306 /// base address to use for accessing globals into a register.
308 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
309 if (!GlobalBaseReg) {
310 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
311 // Insert the set of GlobalBaseReg into the first MBB of the function
312 MachineBasicBlock &FirstMBB = MF->front();
313 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
314 const Module *M = MF->getFunction()->getParent();
317 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
318 if (PPCSubTarget->isTargetELF()) {
319 GlobalBaseReg = PPC::R30;
320 if (M->getPICLevel() == PICLevel::Small) {
321 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
322 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
323 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
325 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
326 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
327 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
328 BuildMI(FirstMBB, MBBI, dl,
329 TII.get(PPC::UpdateGBR), GlobalBaseReg)
330 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
331 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
335 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
336 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
337 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
340 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
341 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
342 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
345 return CurDAG->getRegister(GlobalBaseReg,
346 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
350 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
351 /// or 64-bit immediate, and if the value can be accurately represented as a
352 /// sign extension from a 16-bit value. If so, this returns true and the
354 static bool isIntS16Immediate(SDNode *N, short &Imm) {
355 if (N->getOpcode() != ISD::Constant)
358 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
359 if (N->getValueType(0) == MVT::i32)
360 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
362 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
365 static bool isIntS16Immediate(SDValue Op, short &Imm) {
366 return isIntS16Immediate(Op.getNode(), Imm);
370 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
371 /// operand. If so Imm will receive the 32-bit value.
372 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
373 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
374 Imm = cast<ConstantSDNode>(N)->getZExtValue();
380 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
381 /// operand. If so Imm will receive the 64-bit value.
382 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
383 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
384 Imm = cast<ConstantSDNode>(N)->getZExtValue();
390 // isInt32Immediate - This method tests to see if a constant operand.
391 // If so Imm will receive the 32 bit value.
392 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
393 return isInt32Immediate(N.getNode(), Imm);
397 // isOpcWithIntImmediate - This method tests to see if the node is a specific
398 // opcode and that it has a immediate integer right operand.
399 // If so Imm will receive the 32 bit value.
400 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
401 return N->getOpcode() == Opc
402 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
405 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
407 int FI = cast<FrameIndexSDNode>(N)->getIndex();
408 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
409 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
411 return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
412 getSmallIPtrImm(Offset, dl));
413 return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
414 getSmallIPtrImm(Offset, dl));
417 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
418 bool isShiftMask, unsigned &SH,
419 unsigned &MB, unsigned &ME) {
420 // Don't even go down this path for i64, since different logic will be
421 // necessary for rldicl/rldicr/rldimi.
422 if (N->getValueType(0) != MVT::i32)
426 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
427 unsigned Opcode = N->getOpcode();
428 if (N->getNumOperands() != 2 ||
429 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
432 if (Opcode == ISD::SHL) {
433 // apply shift left to mask if it comes first
434 if (isShiftMask) Mask = Mask << Shift;
435 // determine which bits are made indeterminant by shift
436 Indeterminant = ~(0xFFFFFFFFu << Shift);
437 } else if (Opcode == ISD::SRL) {
438 // apply shift right to mask if it comes first
439 if (isShiftMask) Mask = Mask >> Shift;
440 // determine which bits are made indeterminant by shift
441 Indeterminant = ~(0xFFFFFFFFu >> Shift);
442 // adjust for the left rotate
444 } else if (Opcode == ISD::ROTL) {
450 // if the mask doesn't intersect any Indeterminant bits
451 if (Mask && !(Mask & Indeterminant)) {
453 // make sure the mask is still a mask (wrap arounds may not be)
454 return isRunOfOnes(Mask, MB, ME);
459 /// SelectBitfieldInsert - turn an or of two masked values into
460 /// the rotate left word immediate then mask insert (rlwimi) instruction.
461 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
462 SDValue Op0 = N->getOperand(0);
463 SDValue Op1 = N->getOperand(1);
466 APInt LKZ, LKO, RKZ, RKO;
467 CurDAG->computeKnownBits(Op0, LKZ, LKO);
468 CurDAG->computeKnownBits(Op1, RKZ, RKO);
470 unsigned TargetMask = LKZ.getZExtValue();
471 unsigned InsertMask = RKZ.getZExtValue();
473 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
474 unsigned Op0Opc = Op0.getOpcode();
475 unsigned Op1Opc = Op1.getOpcode();
476 unsigned Value, SH = 0;
477 TargetMask = ~TargetMask;
478 InsertMask = ~InsertMask;
480 // If the LHS has a foldable shift and the RHS does not, then swap it to the
481 // RHS so that we can fold the shift into the insert.
482 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
483 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
484 Op0.getOperand(0).getOpcode() == ISD::SRL) {
485 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
486 Op1.getOperand(0).getOpcode() != ISD::SRL) {
488 std::swap(Op0Opc, Op1Opc);
489 std::swap(TargetMask, InsertMask);
492 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
493 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
494 Op1.getOperand(0).getOpcode() != ISD::SRL) {
496 std::swap(Op0Opc, Op1Opc);
497 std::swap(TargetMask, InsertMask);
502 if (isRunOfOnes(InsertMask, MB, ME)) {
505 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
506 isInt32Immediate(Op1.getOperand(1), Value)) {
507 Op1 = Op1.getOperand(0);
508 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
510 if (Op1Opc == ISD::AND) {
511 // The AND mask might not be a constant, and we need to make sure that
512 // if we're going to fold the masking with the insert, all bits not
513 // know to be zero in the mask are known to be one.
515 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
516 bool CanFoldMask = InsertMask == MKO.getZExtValue();
518 unsigned SHOpc = Op1.getOperand(0).getOpcode();
519 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
520 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
521 // Note that Value must be in range here (less than 32) because
522 // otherwise there would not be any bits set in InsertMask.
523 Op1 = Op1.getOperand(0).getOperand(0);
524 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
529 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
531 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
537 // Predict the number of instructions that would be generated by calling
539 static unsigned SelectInt64CountDirect(int64_t Imm) {
540 // Assume no remaining bits.
541 unsigned Remainder = 0;
542 // Assume no shift required.
545 // If it can't be represented as a 32 bit value.
546 if (!isInt<32>(Imm)) {
547 Shift = countTrailingZeros<uint64_t>(Imm);
548 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
550 // If the shifted value fits 32 bits.
551 if (isInt<32>(ImmSh)) {
552 // Go with the shifted value.
555 // Still stuck with a 64 bit value.
562 // Intermediate operand.
565 // Handle first 32 bits.
566 unsigned Lo = Imm & 0xFFFF;
569 if (isInt<16>(Imm)) {
573 // Handle the Hi bits and Lo bits.
580 // If no shift, we're done.
581 if (!Shift) return Result;
583 // Shift for next step if the upper 32-bits were not zero.
587 // Add in the last bits as required.
588 if ((Remainder >> 16) & 0xFFFF)
590 if (Remainder & 0xFFFF)
596 static uint64_t Rot64(uint64_t Imm, unsigned R) {
597 return (Imm << R) | (Imm >> (64 - R));
600 static unsigned SelectInt64Count(int64_t Imm) {
601 unsigned Count = SelectInt64CountDirect(Imm);
605 for (unsigned r = 1; r < 63; ++r) {
606 uint64_t RImm = Rot64(Imm, r);
607 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
608 Count = std::min(Count, RCount);
610 // See comments in SelectInt64 for an explanation of the logic below.
611 unsigned LS = findLastSet(RImm);
615 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
616 uint64_t RImmWithOnes = RImm | OnesMask;
618 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
619 Count = std::min(Count, RCount);
625 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
626 // (above) needs to be kept in sync with this function.
627 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
628 // Assume no remaining bits.
629 unsigned Remainder = 0;
630 // Assume no shift required.
633 // If it can't be represented as a 32 bit value.
634 if (!isInt<32>(Imm)) {
635 Shift = countTrailingZeros<uint64_t>(Imm);
636 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
638 // If the shifted value fits 32 bits.
639 if (isInt<32>(ImmSh)) {
640 // Go with the shifted value.
643 // Still stuck with a 64 bit value.
650 // Intermediate operand.
653 // Handle first 32 bits.
654 unsigned Lo = Imm & 0xFFFF;
655 unsigned Hi = (Imm >> 16) & 0xFFFF;
657 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
658 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
662 if (isInt<16>(Imm)) {
664 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
666 // Handle the Hi bits.
667 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
668 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
670 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
671 SDValue(Result, 0), getI32Imm(Lo));
674 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
677 // If no shift, we're done.
678 if (!Shift) return Result;
680 // Shift for next step if the upper 32-bits were not zero.
682 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
685 getI32Imm(63 - Shift));
688 // Add in the last bits as required.
689 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
690 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
691 SDValue(Result, 0), getI32Imm(Hi));
693 if ((Lo = Remainder & 0xFFFF)) {
694 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
695 SDValue(Result, 0), getI32Imm(Lo));
701 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
702 unsigned Count = SelectInt64CountDirect(Imm);
704 return SelectInt64Direct(CurDAG, dl, Imm);
711 for (unsigned r = 1; r < 63; ++r) {
712 uint64_t RImm = Rot64(Imm, r);
713 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
714 if (RCount < Count) {
721 // If the immediate to generate has many trailing zeros, it might be
722 // worthwhile to generate a rotated value with too many leading ones
723 // (because that's free with li/lis's sign-extension semantics), and then
724 // mask them off after rotation.
726 unsigned LS = findLastSet(RImm);
727 // We're adding (63-LS) higher-order ones, and we expect to mask them off
728 // after performing the inverse rotation by (64-r). So we need that:
729 // 63-LS == 64-r => LS == r-1
733 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
734 uint64_t RImmWithOnes = RImm | OnesMask;
736 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
737 if (RCount < Count) {
740 MatImm = RImmWithOnes;
746 return SelectInt64Direct(CurDAG, dl, Imm);
748 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
749 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
752 SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, MatImm), 0);
753 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
754 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
757 // Select a 64-bit constant.
758 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
762 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
763 return SelectInt64(CurDAG, dl, Imm);
767 class BitPermutationSelector {
771 // The bit number in the value, using a convention where bit 0 is the
780 ValueBit(SDValue V, unsigned I, Kind K = Variable)
781 : V(V), Idx(I), K(K) {}
782 ValueBit(Kind K = Variable)
783 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
785 bool isZero() const {
786 return K == ConstZero;
789 bool hasValue() const {
790 return K == Variable;
793 SDValue getValue() const {
794 assert(hasValue() && "Cannot get the value of a constant bit");
798 unsigned getValueBitIndex() const {
799 assert(hasValue() && "Cannot get the value bit index of a constant bit");
804 // A bit group has the same underlying value and the same rotate factor.
808 unsigned StartIdx, EndIdx;
810 // This rotation amount assumes that the lower 32 bits of the quantity are
811 // replicated in the high 32 bits by the rotation operator (which is done
812 // by rlwinm and friends in 64-bit mode).
814 // Did converting to Repl32 == true change the rotation factor? If it did,
815 // it decreased it by 32.
817 // Was this group coalesced after setting Repl32 to true?
818 bool Repl32Coalesced;
820 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
821 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
822 Repl32Coalesced(false) {
823 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
824 " [" << S << ", " << E << "]\n");
828 // Information on each (Value, RLAmt) pair (like the number of groups
829 // associated with each) used to choose the lowering method.
830 struct ValueRotInfo {
834 unsigned FirstGroupStartIdx;
838 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
841 // For sorting (in reverse order) by NumGroups, and then by
842 // FirstGroupStartIdx.
843 bool operator < (const ValueRotInfo &Other) const {
844 // We need to sort so that the non-Repl32 come first because, when we're
845 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
846 // masking operation.
847 if (Repl32 < Other.Repl32)
849 else if (Repl32 > Other.Repl32)
851 else if (NumGroups > Other.NumGroups)
853 else if (NumGroups < Other.NumGroups)
855 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
861 // Return true if something interesting was deduced, return false if we're
862 // providing only a generic representation of V (or something else likewise
863 // uninteresting for instruction selection).
864 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
865 switch (V.getOpcode()) {
868 if (isa<ConstantSDNode>(V.getOperand(1))) {
869 unsigned RotAmt = V.getConstantOperandVal(1);
871 SmallVector<ValueBit, 64> LHSBits(Bits.size());
872 getValueBits(V.getOperand(0), LHSBits);
874 for (unsigned i = 0; i < Bits.size(); ++i)
875 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
881 if (isa<ConstantSDNode>(V.getOperand(1))) {
882 unsigned ShiftAmt = V.getConstantOperandVal(1);
884 SmallVector<ValueBit, 64> LHSBits(Bits.size());
885 getValueBits(V.getOperand(0), LHSBits);
887 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
888 Bits[i] = LHSBits[i - ShiftAmt];
890 for (unsigned i = 0; i < ShiftAmt; ++i)
891 Bits[i] = ValueBit(ValueBit::ConstZero);
897 if (isa<ConstantSDNode>(V.getOperand(1))) {
898 unsigned ShiftAmt = V.getConstantOperandVal(1);
900 SmallVector<ValueBit, 64> LHSBits(Bits.size());
901 getValueBits(V.getOperand(0), LHSBits);
903 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
904 Bits[i] = LHSBits[i + ShiftAmt];
906 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
907 Bits[i] = ValueBit(ValueBit::ConstZero);
913 if (isa<ConstantSDNode>(V.getOperand(1))) {
914 uint64_t Mask = V.getConstantOperandVal(1);
916 SmallVector<ValueBit, 64> LHSBits(Bits.size());
917 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
919 for (unsigned i = 0; i < Bits.size(); ++i)
920 if (((Mask >> i) & 1) == 1)
921 Bits[i] = LHSBits[i];
923 Bits[i] = ValueBit(ValueBit::ConstZero);
925 // Mark this as interesting, only if the LHS was also interesting. This
926 // prevents the overall procedure from matching a single immediate 'and'
927 // (which is non-optimal because such an and might be folded with other
928 // things if we don't select it here).
933 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
934 getValueBits(V.getOperand(0), LHSBits);
935 getValueBits(V.getOperand(1), RHSBits);
937 bool AllDisjoint = true;
938 for (unsigned i = 0; i < Bits.size(); ++i)
939 if (LHSBits[i].isZero())
940 Bits[i] = RHSBits[i];
941 else if (RHSBits[i].isZero())
942 Bits[i] = LHSBits[i];
955 for (unsigned i = 0; i < Bits.size(); ++i)
956 Bits[i] = ValueBit(V, i);
961 // For each value (except the constant ones), compute the left-rotate amount
962 // to get it from its original to final position.
963 void computeRotationAmounts() {
965 RLAmt.resize(Bits.size());
966 for (unsigned i = 0; i < Bits.size(); ++i)
967 if (Bits[i].hasValue()) {
968 unsigned VBI = Bits[i].getValueBitIndex();
972 RLAmt[i] = Bits.size() - (VBI - i);
973 } else if (Bits[i].isZero()) {
975 RLAmt[i] = UINT32_MAX;
977 llvm_unreachable("Unknown value bit type");
981 // Collect groups of consecutive bits with the same underlying value and
982 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
983 // they break up groups.
984 void collectBitGroups(bool LateMask) {
987 unsigned LastRLAmt = RLAmt[0];
988 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
989 unsigned LastGroupStartIdx = 0;
990 for (unsigned i = 1; i < Bits.size(); ++i) {
991 unsigned ThisRLAmt = RLAmt[i];
992 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
993 if (LateMask && !ThisValue) {
994 ThisValue = LastValue;
995 ThisRLAmt = LastRLAmt;
996 // If we're doing late masking, then the first bit group always starts
997 // at zero (even if the first bits were zero).
998 if (BitGroups.empty())
999 LastGroupStartIdx = 0;
1002 // If this bit has the same underlying value and the same rotate factor as
1003 // the last one, then they're part of the same group.
1004 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1007 if (LastValue.getNode())
1008 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1010 LastRLAmt = ThisRLAmt;
1011 LastValue = ThisValue;
1012 LastGroupStartIdx = i;
1014 if (LastValue.getNode())
1015 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1018 if (BitGroups.empty())
1021 // We might be able to combine the first and last groups.
1022 if (BitGroups.size() > 1) {
1023 // If the first and last groups are the same, then remove the first group
1024 // in favor of the last group, making the ending index of the last group
1025 // equal to the ending index of the to-be-removed first group.
1026 if (BitGroups[0].StartIdx == 0 &&
1027 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1028 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1029 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1030 DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1031 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1032 BitGroups.erase(BitGroups.begin());
1037 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1038 // associated with each. If there is a degeneracy, pick the one that occurs
1039 // first (in the final value).
1040 void collectValueRotInfo() {
1043 for (auto &BG : BitGroups) {
1044 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1045 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1047 VRI.RLAmt = BG.RLAmt;
1048 VRI.Repl32 = BG.Repl32;
1050 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1053 // Now that we've collected the various ValueRotInfo instances, we need to
1055 ValueRotsVec.clear();
1056 for (auto &I : ValueRots) {
1057 ValueRotsVec.push_back(I.second);
1059 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1062 // In 64-bit mode, rlwinm and friends have a rotation operator that
1063 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1064 // indices of these instructions can only be in the lower 32 bits, so they
1065 // can only represent some 64-bit bit groups. However, when they can be used,
1066 // the 32-bit replication can be used to represent, as a single bit group,
1067 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1068 // groups when possible. Returns true if any of the bit groups were
1070 void assignRepl32BitGroups() {
1071 // If we have bits like this:
1073 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1074 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1075 // Groups: | RLAmt = 8 | RLAmt = 40 |
1077 // But, making use of a 32-bit operation that replicates the low-order 32
1078 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1081 auto IsAllLow32 = [this](BitGroup & BG) {
1082 if (BG.StartIdx <= BG.EndIdx) {
1083 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1084 if (!Bits[i].hasValue())
1086 if (Bits[i].getValueBitIndex() >= 32)
1090 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1091 if (!Bits[i].hasValue())
1093 if (Bits[i].getValueBitIndex() >= 32)
1096 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1097 if (!Bits[i].hasValue())
1099 if (Bits[i].getValueBitIndex() >= 32)
1107 for (auto &BG : BitGroups) {
1108 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1109 if (IsAllLow32(BG)) {
1110 if (BG.RLAmt >= 32) {
1117 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1118 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1119 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1124 // Now walk through the bit groups, consolidating where possible.
1125 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1126 // We might want to remove this bit group by merging it with the previous
1127 // group (which might be the ending group).
1128 auto IP = (I == BitGroups.begin()) ?
1129 std::prev(BitGroups.end()) : std::prev(I);
1130 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1131 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1133 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1134 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1135 " [" << I->StartIdx << ", " << I->EndIdx <<
1136 "] with group with range [" <<
1137 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1139 IP->EndIdx = I->EndIdx;
1140 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1141 IP->Repl32Coalesced = true;
1142 I = BitGroups.erase(I);
1145 // There is a special case worth handling: If there is a single group
1146 // covering the entire upper 32 bits, and it can be merged with both
1147 // the next and previous groups (which might be the same group), then
1148 // do so. If it is the same group (so there will be only one group in
1149 // total), then we need to reverse the order of the range so that it
1150 // covers the entire 64 bits.
1151 if (I->StartIdx == 32 && I->EndIdx == 63) {
1152 assert(std::next(I) == BitGroups.end() &&
1153 "bit group ends at index 63 but there is another?");
1154 auto IN = BitGroups.begin();
1156 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1157 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1158 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1161 DEBUG(dbgs() << "\tcombining bit group for " <<
1162 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1163 " [" << I->StartIdx << ", " << I->EndIdx <<
1164 "] with 32-bit replicated groups with ranges [" <<
1165 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1166 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1169 // There is only one other group; change it to cover the whole
1170 // range (backward, so that it can still be Repl32 but cover the
1171 // whole 64-bit range).
1174 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1175 IP->Repl32Coalesced = true;
1176 I = BitGroups.erase(I);
1178 // There are two separate groups, one before this group and one
1179 // after us (at the beginning). We're going to remove this group,
1180 // but also the group at the very beginning.
1181 IP->EndIdx = IN->EndIdx;
1182 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1183 IP->Repl32Coalesced = true;
1184 I = BitGroups.erase(I);
1185 BitGroups.erase(BitGroups.begin());
1188 // This must be the last group in the vector (and we might have
1189 // just invalidated the iterator above), so break here.
1199 SDValue getI32Imm(unsigned Imm, SDLoc dl) {
1200 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1203 uint64_t getZerosMask() {
1205 for (unsigned i = 0; i < Bits.size(); ++i) {
1206 if (Bits[i].hasValue())
1208 Mask |= (UINT64_C(1) << i);
1214 // Depending on the number of groups for a particular value, it might be
1215 // better to rotate, mask explicitly (using andi/andis), and then or the
1216 // result. Select this part of the result first.
1217 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1218 if (BPermRewriterNoMasking)
1221 for (ValueRotInfo &VRI : ValueRotsVec) {
1223 for (unsigned i = 0; i < Bits.size(); ++i) {
1224 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1226 if (RLAmt[i] != VRI.RLAmt)
1231 // Compute the masks for andi/andis that would be necessary.
1232 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1233 assert((ANDIMask != 0 || ANDISMask != 0) &&
1234 "No set bits in mask for value bit groups");
1235 bool NeedsRotate = VRI.RLAmt != 0;
1237 // We're trying to minimize the number of instructions. If we have one
1238 // group, using one of andi/andis can break even. If we have three
1239 // groups, we can use both andi and andis and break even (to use both
1240 // andi and andis we also need to or the results together). We need four
1241 // groups if we also need to rotate. To use andi/andis we need to do more
1242 // than break even because rotate-and-mask instructions tend to be easier
1245 // FIXME: We've biased here against using andi/andis, which is right for
1246 // POWER cores, but not optimal everywhere. For example, on the A2,
1247 // andi/andis have single-cycle latency whereas the rotate-and-mask
1248 // instructions take two cycles, and it would be better to bias toward
1249 // andi/andis in break-even cases.
1251 unsigned NumAndInsts = (unsigned) NeedsRotate +
1252 (unsigned) (ANDIMask != 0) +
1253 (unsigned) (ANDISMask != 0) +
1254 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1255 (unsigned) (bool) Res;
1257 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1258 " RL: " << VRI.RLAmt << ":" <<
1259 "\n\t\t\tisel using masking: " << NumAndInsts <<
1260 " using rotates: " << VRI.NumGroups << "\n");
1262 if (NumAndInsts >= VRI.NumGroups)
1265 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1267 if (InstCnt) *InstCnt += NumAndInsts;
1272 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1273 getI32Imm(31, dl) };
1274 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1280 SDValue ANDIVal, ANDISVal;
1282 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1283 VRot, getI32Imm(ANDIMask, dl)), 0);
1285 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1286 VRot, getI32Imm(ANDISMask, dl)), 0);
1290 TotalVal = ANDISVal;
1294 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1295 ANDIVal, ANDISVal), 0);
1300 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1303 // Now, remove all groups with this underlying value and rotation
1305 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1306 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1311 // Instruction selection for the 32-bit case.
1312 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1316 if (InstCnt) *InstCnt = 0;
1318 // Take care of cases that should use andi/andis first.
1319 SelectAndParts32(dl, Res, InstCnt);
1321 // If we've not yet selected a 'starting' instruction, and we have no zeros
1322 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1323 // number of groups), and start with this rotated value.
1324 if ((!HasZeros || LateMask) && !Res) {
1325 ValueRotInfo &VRI = ValueRotsVec[0];
1327 if (InstCnt) *InstCnt += 1;
1329 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1330 getI32Imm(31, dl) };
1331 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1337 // Now, remove all groups with this underlying value and rotation factor.
1338 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1339 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1343 if (InstCnt) *InstCnt += BitGroups.size();
1345 // Insert the other groups (one at a time).
1346 for (auto &BG : BitGroups) {
1349 { BG.V, getI32Imm(BG.RLAmt, dl),
1350 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1351 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1352 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1355 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1356 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1357 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1358 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1363 unsigned Mask = (unsigned) getZerosMask();
1365 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1366 assert((ANDIMask != 0 || ANDISMask != 0) &&
1367 "No set bits in zeros mask?");
1369 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1370 (unsigned) (ANDISMask != 0) +
1371 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1373 SDValue ANDIVal, ANDISVal;
1375 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1376 Res, getI32Imm(ANDIMask, dl)), 0);
1378 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1379 Res, getI32Imm(ANDISMask, dl)), 0);
1386 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1387 ANDIVal, ANDISVal), 0);
1390 return Res.getNode();
1393 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1394 unsigned MaskStart, unsigned MaskEnd,
1396 // In the notation used by the instructions, 'start' and 'end' are reversed
1397 // because bits are counted from high to low order.
1398 unsigned InstMaskStart = 64 - MaskEnd - 1,
1399 InstMaskEnd = 64 - MaskStart - 1;
1404 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1405 InstMaskEnd == 63 - RLAmt)
1411 // For 64-bit values, not all combinations of rotates and masks are
1412 // available. Produce one if it is available.
1413 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1414 unsigned MaskStart, unsigned MaskEnd,
1415 unsigned *InstCnt = nullptr) {
1416 // In the notation used by the instructions, 'start' and 'end' are reversed
1417 // because bits are counted from high to low order.
1418 unsigned InstMaskStart = 64 - MaskEnd - 1,
1419 InstMaskEnd = 64 - MaskStart - 1;
1421 if (InstCnt) *InstCnt += 1;
1424 // This rotation amount assumes that the lower 32 bits of the quantity
1425 // are replicated in the high 32 bits by the rotation operator (which is
1426 // done by rlwinm and friends).
1427 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1428 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1430 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1431 getI32Imm(InstMaskEnd - 32, dl) };
1432 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1436 if (InstMaskEnd == 63) {
1438 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1439 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1442 if (InstMaskStart == 0) {
1444 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1445 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1448 if (InstMaskEnd == 63 - RLAmt) {
1450 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1451 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1454 // We cannot do this with a single instruction, so we'll use two. The
1455 // problem is that we're not free to choose both a rotation amount and mask
1456 // start and end independently. We can choose an arbitrary mask start and
1457 // end, but then the rotation amount is fixed. Rotation, however, can be
1458 // inverted, and so by applying an "inverse" rotation first, we can get the
1460 if (InstCnt) *InstCnt += 1;
1462 // The rotation mask for the second instruction must be MaskStart.
1463 unsigned RLAmt2 = MaskStart;
1464 // The first instruction must rotate V so that the overall rotation amount
1466 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1468 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1469 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1472 // For 64-bit values, not all combinations of rotates and masks are
1473 // available. Produce a rotate-mask-and-insert if one is available.
1474 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1475 bool Repl32, unsigned MaskStart,
1476 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1477 // In the notation used by the instructions, 'start' and 'end' are reversed
1478 // because bits are counted from high to low order.
1479 unsigned InstMaskStart = 64 - MaskEnd - 1,
1480 InstMaskEnd = 64 - MaskStart - 1;
1482 if (InstCnt) *InstCnt += 1;
1485 // This rotation amount assumes that the lower 32 bits of the quantity
1486 // are replicated in the high 32 bits by the rotation operator (which is
1487 // done by rlwinm and friends).
1488 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1489 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1491 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1492 getI32Imm(InstMaskEnd - 32, dl) };
1493 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1497 if (InstMaskEnd == 63 - RLAmt) {
1499 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1500 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1503 // We cannot do this with a single instruction, so we'll use two. The
1504 // problem is that we're not free to choose both a rotation amount and mask
1505 // start and end independently. We can choose an arbitrary mask start and
1506 // end, but then the rotation amount is fixed. Rotation, however, can be
1507 // inverted, and so by applying an "inverse" rotation first, we can get the
1509 if (InstCnt) *InstCnt += 1;
1511 // The rotation mask for the second instruction must be MaskStart.
1512 unsigned RLAmt2 = MaskStart;
1513 // The first instruction must rotate V so that the overall rotation amount
1515 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1517 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1518 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1521 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1522 if (BPermRewriterNoMasking)
1525 // The idea here is the same as in the 32-bit version, but with additional
1526 // complications from the fact that Repl32 might be true. Because we
1527 // aggressively convert bit groups to Repl32 form (which, for small
1528 // rotation factors, involves no other change), and then coalesce, it might
1529 // be the case that a single 64-bit masking operation could handle both
1530 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1531 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1532 // completely capture the new combined bit group.
1534 for (ValueRotInfo &VRI : ValueRotsVec) {
1537 // We need to add to the mask all bits from the associated bit groups.
1538 // If Repl32 is false, we need to add bits from bit groups that have
1539 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1540 // group is trivially convertable if it overlaps only with the lower 32
1541 // bits, and the group has not been coalesced.
1542 auto MatchingBG = [VRI](const BitGroup &BG) {
1546 unsigned EffRLAmt = BG.RLAmt;
1547 if (!VRI.Repl32 && BG.Repl32) {
1548 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1549 !BG.Repl32Coalesced) {
1555 } else if (VRI.Repl32 != BG.Repl32) {
1559 if (VRI.RLAmt != EffRLAmt)
1565 for (auto &BG : BitGroups) {
1566 if (!MatchingBG(BG))
1569 if (BG.StartIdx <= BG.EndIdx) {
1570 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1571 Mask |= (UINT64_C(1) << i);
1573 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1574 Mask |= (UINT64_C(1) << i);
1575 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1576 Mask |= (UINT64_C(1) << i);
1580 // We can use the 32-bit andi/andis technique if the mask does not
1581 // require any higher-order bits. This can save an instruction compared
1582 // to always using the general 64-bit technique.
1583 bool Use32BitInsts = isUInt<32>(Mask);
1584 // Compute the masks for andi/andis that would be necessary.
1585 unsigned ANDIMask = (Mask & UINT16_MAX),
1586 ANDISMask = (Mask >> 16) & UINT16_MAX;
1588 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1590 unsigned NumAndInsts = (unsigned) NeedsRotate +
1591 (unsigned) (bool) Res;
1593 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1594 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1596 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1598 unsigned NumRLInsts = 0;
1599 bool FirstBG = true;
1600 for (auto &BG : BitGroups) {
1601 if (!MatchingBG(BG))
1604 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1609 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1610 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1611 "\n\t\t\tisel using masking: " << NumAndInsts <<
1612 " using rotates: " << NumRLInsts << "\n");
1614 // When we'd use andi/andis, we bias toward using the rotates (andi only
1615 // has a record form, and is cracked on POWER cores). However, when using
1616 // general 64-bit constant formation, bias toward the constant form,
1617 // because that exposes more opportunities for CSE.
1618 if (NumAndInsts > NumRLInsts)
1620 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1623 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1625 if (InstCnt) *InstCnt += NumAndInsts;
1628 // We actually need to generate a rotation if we have a non-zero rotation
1629 // factor or, in the Repl32 case, if we care about any of the
1630 // higher-order replicated bits. In the latter case, we generate a mask
1631 // backward so that it actually includes the entire 64 bits.
1632 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1633 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1634 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1639 if (Use32BitInsts) {
1640 assert((ANDIMask != 0 || ANDISMask != 0) &&
1641 "No set bits in mask when using 32-bit ands for 64-bit value");
1643 SDValue ANDIVal, ANDISVal;
1645 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1646 VRot, getI32Imm(ANDIMask, dl)), 0);
1648 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1649 VRot, getI32Imm(ANDISMask, dl)), 0);
1652 TotalVal = ANDISVal;
1656 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1657 ANDIVal, ANDISVal), 0);
1659 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1661 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1662 VRot, TotalVal), 0);
1668 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1671 // Now, remove all groups with this underlying value and rotation
1673 eraseMatchingBitGroups(MatchingBG);
1677 // Instruction selection for the 64-bit case.
1678 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1682 if (InstCnt) *InstCnt = 0;
1684 // Take care of cases that should use andi/andis first.
1685 SelectAndParts64(dl, Res, InstCnt);
1687 // If we've not yet selected a 'starting' instruction, and we have no zeros
1688 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1689 // number of groups), and start with this rotated value.
1690 if ((!HasZeros || LateMask) && !Res) {
1691 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1692 // groups will come first, and so the VRI representing the largest number
1693 // of groups might not be first (it might be the first Repl32 groups).
1694 unsigned MaxGroupsIdx = 0;
1695 if (!ValueRotsVec[0].Repl32) {
1696 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1697 if (ValueRotsVec[i].Repl32) {
1698 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1704 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1705 bool NeedsRotate = false;
1708 } else if (VRI.Repl32) {
1709 for (auto &BG : BitGroups) {
1710 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1711 BG.Repl32 != VRI.Repl32)
1714 // We don't need a rotate if the bit group is confined to the lower
1716 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1725 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1726 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1731 // Now, remove all groups with this underlying value and rotation factor.
1733 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1734 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1735 BG.Repl32 == VRI.Repl32;
1739 // Because 64-bit rotates are more flexible than inserts, we might have a
1740 // preference regarding which one we do first (to save one instruction).
1742 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1743 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1745 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1747 if (I != BitGroups.begin()) {
1750 BitGroups.insert(BitGroups.begin(), BG);
1757 // Insert the other groups (one at a time).
1758 for (auto &BG : BitGroups) {
1760 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1761 BG.EndIdx, InstCnt);
1763 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1764 BG.StartIdx, BG.EndIdx, InstCnt);
1768 uint64_t Mask = getZerosMask();
1770 // We can use the 32-bit andi/andis technique if the mask does not
1771 // require any higher-order bits. This can save an instruction compared
1772 // to always using the general 64-bit technique.
1773 bool Use32BitInsts = isUInt<32>(Mask);
1774 // Compute the masks for andi/andis that would be necessary.
1775 unsigned ANDIMask = (Mask & UINT16_MAX),
1776 ANDISMask = (Mask >> 16) & UINT16_MAX;
1778 if (Use32BitInsts) {
1779 assert((ANDIMask != 0 || ANDISMask != 0) &&
1780 "No set bits in mask when using 32-bit ands for 64-bit value");
1782 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1783 (unsigned) (ANDISMask != 0) +
1784 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1786 SDValue ANDIVal, ANDISVal;
1788 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1789 Res, getI32Imm(ANDIMask, dl)), 0);
1791 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1792 Res, getI32Imm(ANDISMask, dl)), 0);
1799 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1800 ANDIVal, ANDISVal), 0);
1802 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1804 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1806 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1811 return Res.getNode();
1814 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1815 // Fill in BitGroups.
1816 collectBitGroups(LateMask);
1817 if (BitGroups.empty())
1820 // For 64-bit values, figure out when we can use 32-bit instructions.
1821 if (Bits.size() == 64)
1822 assignRepl32BitGroups();
1824 // Fill in ValueRotsVec.
1825 collectValueRotInfo();
1827 if (Bits.size() == 32) {
1828 return Select32(N, LateMask, InstCnt);
1830 assert(Bits.size() == 64 && "Not 64 bits here?");
1831 return Select64(N, LateMask, InstCnt);
1837 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1838 BitGroups.erase(std::remove_if(BitGroups.begin(), BitGroups.end(), F),
1842 SmallVector<ValueBit, 64> Bits;
1845 SmallVector<unsigned, 64> RLAmt;
1847 SmallVector<BitGroup, 16> BitGroups;
1849 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1850 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1852 SelectionDAG *CurDAG;
1855 BitPermutationSelector(SelectionDAG *DAG)
1858 // Here we try to match complex bit permutations into a set of
1859 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1860 // known to produce optimial code for common cases (like i32 byte swapping).
1861 SDNode *Select(SDNode *N) {
1862 Bits.resize(N->getValueType(0).getSizeInBits());
1863 if (!getValueBits(SDValue(N, 0), Bits))
1866 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1867 " selection for: ");
1868 DEBUG(N->dump(CurDAG));
1870 // Fill it RLAmt and set HasZeros.
1871 computeRotationAmounts();
1874 return Select(N, false);
1876 // We currently have two techniques for handling results with zeros: early
1877 // masking (the default) and late masking. Late masking is sometimes more
1878 // efficient, but because the structure of the bit groups is different, it
1879 // is hard to tell without generating both and comparing the results. With
1880 // late masking, we ignore zeros in the resulting value when inserting each
1881 // set of bit groups, and then mask in the zeros at the end. With early
1882 // masking, we only insert the non-zero parts of the result at every step.
1884 unsigned InstCnt, InstCntLateMask;
1885 DEBUG(dbgs() << "\tEarly masking:\n");
1886 SDNode *RN = Select(N, false, &InstCnt);
1887 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1889 DEBUG(dbgs() << "\tLate masking:\n");
1890 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1891 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1894 if (InstCnt <= InstCntLateMask) {
1895 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1899 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1903 } // anonymous namespace
1905 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1906 if (N->getValueType(0) != MVT::i32 &&
1907 N->getValueType(0) != MVT::i64)
1910 if (!UseBitPermRewriter)
1913 switch (N->getOpcode()) {
1920 BitPermutationSelector BPS(CurDAG);
1921 return BPS.Select(N);
1928 /// SelectCC - Select a comparison of the specified values with the specified
1929 /// condition code, returning the CR# of the expression.
1930 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1931 ISD::CondCode CC, SDLoc dl) {
1932 // Always select the LHS.
1935 if (LHS.getValueType() == MVT::i32) {
1937 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1938 if (isInt32Immediate(RHS, Imm)) {
1939 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1940 if (isUInt<16>(Imm))
1941 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1942 getI32Imm(Imm & 0xFFFF, dl)),
1944 // If this is a 16-bit signed immediate, fold it.
1945 if (isInt<16>((int)Imm))
1946 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1947 getI32Imm(Imm & 0xFFFF, dl)),
1950 // For non-equality comparisons, the default code would materialize the
1951 // constant, then compare against it, like this:
1953 // ori r2, r2, 22136
1955 // Since we are just comparing for equality, we can emit this instead:
1956 // xoris r0,r3,0x1234
1957 // cmplwi cr0,r0,0x5678
1959 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
1960 getI32Imm(Imm >> 16, dl)), 0);
1961 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1962 getI32Imm(Imm & 0xFFFF, dl)), 0);
1965 } else if (ISD::isUnsignedIntSetCC(CC)) {
1966 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
1967 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1968 getI32Imm(Imm & 0xFFFF, dl)), 0);
1972 if (isIntS16Immediate(RHS, SImm))
1973 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1974 getI32Imm((int)SImm & 0xFFFF,
1979 } else if (LHS.getValueType() == MVT::i64) {
1981 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1982 if (isInt64Immediate(RHS.getNode(), Imm)) {
1983 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1984 if (isUInt<16>(Imm))
1985 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
1986 getI32Imm(Imm & 0xFFFF, dl)),
1988 // If this is a 16-bit signed immediate, fold it.
1990 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1991 getI32Imm(Imm & 0xFFFF, dl)),
1994 // For non-equality comparisons, the default code would materialize the
1995 // constant, then compare against it, like this:
1997 // ori r2, r2, 22136
1999 // Since we are just comparing for equality, we can emit this instead:
2000 // xoris r0,r3,0x1234
2001 // cmpldi cr0,r0,0x5678
2003 if (isUInt<32>(Imm)) {
2004 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2005 getI64Imm(Imm >> 16, dl)), 0);
2006 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2007 getI64Imm(Imm & 0xFFFF, dl)),
2012 } else if (ISD::isUnsignedIntSetCC(CC)) {
2013 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2014 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2015 getI64Imm(Imm & 0xFFFF, dl)), 0);
2019 if (isIntS16Immediate(RHS, SImm))
2020 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2021 getI64Imm(SImm & 0xFFFF, dl)),
2025 } else if (LHS.getValueType() == MVT::f32) {
2028 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2029 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2031 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2034 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2040 llvm_unreachable("Should be lowered by legalize!");
2041 default: llvm_unreachable("Unknown condition!");
2043 case ISD::SETEQ: return PPC::PRED_EQ;
2045 case ISD::SETNE: return PPC::PRED_NE;
2047 case ISD::SETLT: return PPC::PRED_LT;
2049 case ISD::SETLE: return PPC::PRED_LE;
2051 case ISD::SETGT: return PPC::PRED_GT;
2053 case ISD::SETGE: return PPC::PRED_GE;
2054 case ISD::SETO: return PPC::PRED_NU;
2055 case ISD::SETUO: return PPC::PRED_UN;
2056 // These two are invalid for floating point. Assume we have int.
2057 case ISD::SETULT: return PPC::PRED_LT;
2058 case ISD::SETUGT: return PPC::PRED_GT;
2062 /// getCRIdxForSetCC - Return the index of the condition register field
2063 /// associated with the SetCC condition, and whether or not the field is
2064 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2065 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2068 default: llvm_unreachable("Unknown condition!");
2070 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2072 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2074 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2075 case ISD::SETUO: return 3; // Bit #3 = SETUO
2077 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2079 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2081 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2082 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2087 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2088 // These are invalid for floating point. Assume integer.
2089 case ISD::SETULT: return 0;
2090 case ISD::SETUGT: return 1;
2094 // getVCmpInst: return the vector compare instruction for the specified
2095 // vector type and condition code. Since this is for altivec specific code,
2096 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2097 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2098 bool HasVSX, bool &Swap, bool &Negate) {
2102 if (VecVT.isFloatingPoint()) {
2103 /* Handle some cases by swapping input operands. */
2105 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2106 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2107 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2108 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2109 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2110 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2113 /* Handle some cases by negating the result. */
2115 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2116 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2117 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2118 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2121 /* We have instructions implementing the remaining cases. */
2125 if (VecVT == MVT::v4f32)
2126 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2127 else if (VecVT == MVT::v2f64)
2128 return PPC::XVCMPEQDP;
2132 if (VecVT == MVT::v4f32)
2133 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2134 else if (VecVT == MVT::v2f64)
2135 return PPC::XVCMPGTDP;
2139 if (VecVT == MVT::v4f32)
2140 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2141 else if (VecVT == MVT::v2f64)
2142 return PPC::XVCMPGEDP;
2147 llvm_unreachable("Invalid floating-point vector compare condition");
2149 /* Handle some cases by swapping input operands. */
2151 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2152 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2153 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2154 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2157 /* Handle some cases by negating the result. */
2159 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2160 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2161 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2162 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2165 /* We have instructions implementing the remaining cases. */
2169 if (VecVT == MVT::v16i8)
2170 return PPC::VCMPEQUB;
2171 else if (VecVT == MVT::v8i16)
2172 return PPC::VCMPEQUH;
2173 else if (VecVT == MVT::v4i32)
2174 return PPC::VCMPEQUW;
2175 else if (VecVT == MVT::v2i64)
2176 return PPC::VCMPEQUD;
2179 if (VecVT == MVT::v16i8)
2180 return PPC::VCMPGTSB;
2181 else if (VecVT == MVT::v8i16)
2182 return PPC::VCMPGTSH;
2183 else if (VecVT == MVT::v4i32)
2184 return PPC::VCMPGTSW;
2185 else if (VecVT == MVT::v2i64)
2186 return PPC::VCMPGTSD;
2189 if (VecVT == MVT::v16i8)
2190 return PPC::VCMPGTUB;
2191 else if (VecVT == MVT::v8i16)
2192 return PPC::VCMPGTUH;
2193 else if (VecVT == MVT::v4i32)
2194 return PPC::VCMPGTUW;
2195 else if (VecVT == MVT::v2i64)
2196 return PPC::VCMPGTUD;
2201 llvm_unreachable("Invalid integer vector compare condition");
2205 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2208 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2210 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2211 bool isPPC64 = (PtrVT == MVT::i64);
2213 if (!PPCSubTarget->useCRBits() &&
2214 isInt32Immediate(N->getOperand(1), Imm)) {
2215 // We can codegen setcc op, imm very efficiently compared to a brcond.
2216 // Check for those cases here.
2219 SDValue Op = N->getOperand(0);
2223 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2224 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2225 getI32Imm(31, dl) };
2226 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2231 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2232 Op, getI32Imm(~0U, dl)), 0);
2233 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2237 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2238 getI32Imm(31, dl) };
2239 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2243 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2244 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2245 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2246 getI32Imm(31, dl) };
2247 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2250 } else if (Imm == ~0U) { // setcc op, -1
2251 SDValue Op = N->getOperand(0);
2256 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2257 Op, getI32Imm(1, dl)), 0);
2258 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2259 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2262 0), Op.getValue(1));
2265 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2266 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2267 Op, getI32Imm(~0U, dl));
2268 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2269 Op, SDValue(AD, 1));
2272 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2273 getI32Imm(1, dl)), 0);
2274 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2276 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2277 getI32Imm(31, dl) };
2278 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2281 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2282 getI32Imm(31, dl) };
2283 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2284 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2291 SDValue LHS = N->getOperand(0);
2292 SDValue RHS = N->getOperand(1);
2294 // Altivec Vector compare instructions do not set any CR register by default and
2295 // vector compare operations return the same type as the operands.
2296 if (LHS.getValueType().isVector()) {
2297 if (PPCSubTarget->hasQPX())
2300 EVT VecVT = LHS.getValueType();
2302 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2303 PPCSubTarget->hasVSX(), Swap, Negate);
2305 std::swap(LHS, RHS);
2307 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2309 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2310 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2315 return CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2318 if (PPCSubTarget->useCRBits())
2322 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2323 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2326 // Force the ccreg into CR7.
2327 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2329 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2330 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2331 InFlag).getValue(1);
2333 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2336 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2337 getI32Imm(31, dl), getI32Imm(31, dl) };
2339 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2341 // Get the specified bit.
2343 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2344 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2347 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2348 // Transfer memoperands.
2349 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2350 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2351 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2356 // Select - Convert the specified operand from a target-independent to a
2357 // target-specific node if it hasn't already been changed.
2358 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2360 if (N->isMachineOpcode()) {
2362 return nullptr; // Already selected.
2365 // In case any misguided DAG-level optimizations form an ADD with a
2366 // TargetConstant operand, crash here instead of miscompiling (by selecting
2367 // an r+r add instead of some kind of r+i add).
2368 if (N->getOpcode() == ISD::ADD &&
2369 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2370 llvm_unreachable("Invalid ADD with TargetConstant operand");
2372 // Try matching complex bit permutations before doing anything else.
2373 if (SDNode *NN = SelectBitPermutation(N))
2376 switch (N->getOpcode()) {
2379 case ISD::Constant: {
2380 if (N->getValueType(0) == MVT::i64)
2381 return SelectInt64(CurDAG, N);
2386 SDNode *SN = SelectSETCC(N);
2391 case PPCISD::GlobalBaseReg:
2392 return getGlobalBaseReg();
2394 case ISD::FrameIndex:
2395 return getFrameIndex(N, N);
2397 case PPCISD::MFOCRF: {
2398 SDValue InFlag = N->getOperand(1);
2399 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2400 N->getOperand(0), InFlag);
2403 case PPCISD::READ_TIME_BASE: {
2404 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2405 MVT::Other, N->getOperand(0));
2408 case PPCISD::SRA_ADDZE: {
2409 SDValue N0 = N->getOperand(0);
2411 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2412 getConstantIntValue(), dl,
2413 N->getValueType(0));
2414 if (N->getValueType(0) == MVT::i64) {
2416 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2418 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2419 SDValue(Op, 0), SDValue(Op, 1));
2421 assert(N->getValueType(0) == MVT::i32 &&
2422 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2424 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2426 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2427 SDValue(Op, 0), SDValue(Op, 1));
2432 // Handle preincrement loads.
2433 LoadSDNode *LD = cast<LoadSDNode>(N);
2434 EVT LoadedVT = LD->getMemoryVT();
2436 // Normal loads are handled by code generated from the .td file.
2437 if (LD->getAddressingMode() != ISD::PRE_INC)
2440 SDValue Offset = LD->getOffset();
2441 if (Offset.getOpcode() == ISD::TargetConstant ||
2442 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2445 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2446 if (LD->getValueType(0) != MVT::i64) {
2447 // Handle PPC32 integer and normal FP loads.
2448 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2449 switch (LoadedVT.getSimpleVT().SimpleTy) {
2450 default: llvm_unreachable("Invalid PPC load type!");
2451 case MVT::f64: Opcode = PPC::LFDU; break;
2452 case MVT::f32: Opcode = PPC::LFSU; break;
2453 case MVT::i32: Opcode = PPC::LWZU; break;
2454 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2456 case MVT::i8: Opcode = PPC::LBZU; break;
2459 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2460 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2461 switch (LoadedVT.getSimpleVT().SimpleTy) {
2462 default: llvm_unreachable("Invalid PPC load type!");
2463 case MVT::i64: Opcode = PPC::LDU; break;
2464 case MVT::i32: Opcode = PPC::LWZU8; break;
2465 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2467 case MVT::i8: Opcode = PPC::LBZU8; break;
2471 SDValue Chain = LD->getChain();
2472 SDValue Base = LD->getBasePtr();
2473 SDValue Ops[] = { Offset, Base, Chain };
2474 return transferMemOperands(
2475 N, CurDAG->getMachineNode(
2476 Opcode, dl, LD->getValueType(0),
2477 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other,
2481 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2482 if (LD->getValueType(0) != MVT::i64) {
2483 // Handle PPC32 integer and normal FP loads.
2484 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2485 switch (LoadedVT.getSimpleVT().SimpleTy) {
2486 default: llvm_unreachable("Invalid PPC load type!");
2487 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2488 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2489 case MVT::f64: Opcode = PPC::LFDUX; break;
2490 case MVT::f32: Opcode = PPC::LFSUX; break;
2491 case MVT::i32: Opcode = PPC::LWZUX; break;
2492 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2494 case MVT::i8: Opcode = PPC::LBZUX; break;
2497 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2498 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2499 "Invalid sext update load");
2500 switch (LoadedVT.getSimpleVT().SimpleTy) {
2501 default: llvm_unreachable("Invalid PPC load type!");
2502 case MVT::i64: Opcode = PPC::LDUX; break;
2503 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2504 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2506 case MVT::i8: Opcode = PPC::LBZUX8; break;
2510 SDValue Chain = LD->getChain();
2511 SDValue Base = LD->getBasePtr();
2512 SDValue Ops[] = { Base, Offset, Chain };
2513 return transferMemOperands(
2514 N, CurDAG->getMachineNode(
2515 Opcode, dl, LD->getValueType(0),
2516 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other,
2522 unsigned Imm, Imm2, SH, MB, ME;
2525 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2526 // with a mask, emit rlwinm
2527 if (isInt32Immediate(N->getOperand(1), Imm) &&
2528 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2529 SDValue Val = N->getOperand(0).getOperand(0);
2530 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2531 getI32Imm(ME, dl) };
2532 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2534 // If this is just a masked value where the input is not handled above, and
2535 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2536 if (isInt32Immediate(N->getOperand(1), Imm) &&
2537 isRunOfOnes(Imm, MB, ME) &&
2538 N->getOperand(0).getOpcode() != ISD::ROTL) {
2539 SDValue Val = N->getOperand(0);
2540 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2541 getI32Imm(ME, dl) };
2542 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2544 // If this is a 64-bit zero-extension mask, emit rldicl.
2545 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2547 SDValue Val = N->getOperand(0);
2548 MB = 64 - countTrailingOnes(Imm64);
2551 // If the operand is a logical right shift, we can fold it into this
2552 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2553 // for n <= mb. The right shift is really a left rotate followed by a
2554 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2556 if (Val.getOpcode() == ISD::SRL &&
2557 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2558 assert(Imm < 64 && "Illegal shift amount");
2559 Val = Val.getOperand(0);
2563 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2564 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2566 // AND X, 0 -> 0, not "rlwinm 32".
2567 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2568 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2571 // ISD::OR doesn't get all the bitfield insertion fun.
2572 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
2574 if (isInt32Immediate(N->getOperand(1), Imm) &&
2575 N->getOperand(0).getOpcode() == ISD::OR &&
2576 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2577 // The idea here is to check whether this is equivalent to:
2578 // (c1 & m) | (x & ~m)
2579 // where m is a run-of-ones mask. The logic here is that, for each bit in
2581 // - if both are 1, then the output will be 1.
2582 // - if both are 0, then the output will be 0.
2583 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
2585 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
2587 // If that last condition is never the case, then we can form m from the
2588 // bits that are the same between c1 and c2.
2590 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
2591 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2592 N->getOperand(0).getOperand(1),
2593 getI32Imm(0, dl), getI32Imm(MB, dl),
2594 getI32Imm(ME, dl) };
2595 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2599 // Other cases are autogenerated.
2603 if (N->getValueType(0) == MVT::i32)
2604 if (SDNode *I = SelectBitfieldInsert(N))
2608 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2609 isIntS16Immediate(N->getOperand(1), Imm)) {
2610 APInt LHSKnownZero, LHSKnownOne;
2611 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2613 // If this is equivalent to an add, then we can fold it with the
2614 // FrameIndex calculation.
2615 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2616 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2619 // Other cases are autogenerated.
2624 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2625 isIntS16Immediate(N->getOperand(1), Imm))
2626 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
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, dl), getI32Imm(MB, dl),
2636 getI32Imm(ME, dl) };
2637 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2640 // Other cases are autogenerated.
2644 unsigned Imm, SH, MB, ME;
2645 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2646 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2647 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2648 getI32Imm(SH, dl), getI32Imm(MB, dl),
2649 getI32Imm(ME, dl) };
2650 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2653 // Other cases are autogenerated.
2656 // FIXME: Remove this once the ANDI glue bug is fixed:
2657 case PPCISD::ANDIo_1_EQ_BIT:
2658 case PPCISD::ANDIo_1_GT_BIT: {
2662 EVT InVT = N->getOperand(0).getValueType();
2663 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2664 "Invalid input type for ANDIo_1_EQ_BIT");
2666 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2667 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2669 CurDAG->getTargetConstant(1, dl, InVT)),
2671 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2673 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2674 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2676 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2678 SDValue(AndI.getNode(), 1) /* glue */);
2680 case ISD::SELECT_CC: {
2681 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2683 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2684 bool isPPC64 = (PtrVT == MVT::i64);
2686 // If this is a select of i1 operands, we'll pattern match it.
2687 if (PPCSubTarget->useCRBits() &&
2688 N->getOperand(0).getValueType() == MVT::i1)
2691 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2693 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2694 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2695 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2696 if (N1C->isNullValue() && N3C->isNullValue() &&
2697 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2698 // FIXME: Implement this optzn for PPC64.
2699 N->getValueType(0) == MVT::i32) {
2701 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2702 N->getOperand(0), getI32Imm(~0U, dl));
2703 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2704 SDValue(Tmp, 0), N->getOperand(0),
2708 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2710 if (N->getValueType(0) == MVT::i1) {
2711 // An i1 select is: (c & t) | (!c & f).
2713 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2717 default: llvm_unreachable("Invalid CC index");
2718 case 0: SRI = PPC::sub_lt; break;
2719 case 1: SRI = PPC::sub_gt; break;
2720 case 2: SRI = PPC::sub_eq; break;
2721 case 3: SRI = PPC::sub_un; break;
2724 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2726 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2728 SDValue C = Inv ? NotCCBit : CCBit,
2729 NotC = Inv ? CCBit : NotCCBit;
2731 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2732 C, N->getOperand(2)), 0);
2733 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2734 NotC, N->getOperand(3)), 0);
2736 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2739 unsigned BROpc = getPredicateForSetCC(CC);
2741 unsigned SelectCCOp;
2742 if (N->getValueType(0) == MVT::i32)
2743 SelectCCOp = PPC::SELECT_CC_I4;
2744 else if (N->getValueType(0) == MVT::i64)
2745 SelectCCOp = PPC::SELECT_CC_I8;
2746 else if (N->getValueType(0) == MVT::f32)
2747 if (PPCSubTarget->hasP8Vector())
2748 SelectCCOp = PPC::SELECT_CC_VSSRC;
2750 SelectCCOp = PPC::SELECT_CC_F4;
2751 else if (N->getValueType(0) == MVT::f64)
2752 if (PPCSubTarget->hasVSX())
2753 SelectCCOp = PPC::SELECT_CC_VSFRC;
2755 SelectCCOp = PPC::SELECT_CC_F8;
2756 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2757 SelectCCOp = PPC::SELECT_CC_QFRC;
2758 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2759 SelectCCOp = PPC::SELECT_CC_QSRC;
2760 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2761 SelectCCOp = PPC::SELECT_CC_QBRC;
2762 else if (N->getValueType(0) == MVT::v2f64 ||
2763 N->getValueType(0) == MVT::v2i64)
2764 SelectCCOp = PPC::SELECT_CC_VSRC;
2766 SelectCCOp = PPC::SELECT_CC_VRRC;
2768 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2769 getI32Imm(BROpc, dl) };
2770 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2773 if (PPCSubTarget->hasVSX()) {
2774 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2775 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2779 case ISD::VECTOR_SHUFFLE:
2780 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2781 N->getValueType(0) == MVT::v2i64)) {
2782 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2784 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2785 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2788 for (int i = 0; i < 2; ++i)
2789 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2794 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2795 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2796 isa<LoadSDNode>(Op1.getOperand(0))) {
2797 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2798 SDValue Base, Offset;
2800 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
2801 (LD->getMemoryVT() == MVT::f64 ||
2802 LD->getMemoryVT() == MVT::i64) &&
2803 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2804 SDValue Chain = LD->getChain();
2805 SDValue Ops[] = { Base, Offset, Chain };
2806 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2807 N->getValueType(0), Ops);
2811 // For little endian, we must swap the input operands and adjust
2812 // the mask elements (reverse and invert them).
2813 if (PPCSubTarget->isLittleEndian()) {
2814 std::swap(Op1, Op2);
2815 unsigned tmp = DM[0];
2820 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
2822 SDValue Ops[] = { Op1, Op2, DMV };
2823 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2829 bool IsPPC64 = PPCSubTarget->isPPC64();
2830 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2831 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2832 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2833 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2836 case PPCISD::COND_BRANCH: {
2837 // Op #0 is the Chain.
2838 // Op #1 is the PPC::PRED_* number.
2840 // Op #3 is the Dest MBB
2841 // Op #4 is the Flag.
2842 // Prevent PPC::PRED_* from being selected into LI.
2844 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(), dl);
2845 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2846 N->getOperand(0), N->getOperand(4) };
2847 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2850 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2851 unsigned PCC = getPredicateForSetCC(CC);
2853 if (N->getOperand(2).getValueType() == MVT::i1) {
2857 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2858 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2859 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2860 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2861 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2862 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2863 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2866 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2867 N->getOperand(Swap ? 3 : 2),
2868 N->getOperand(Swap ? 2 : 3)), 0);
2869 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2870 BitComp, N->getOperand(4), N->getOperand(0));
2873 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2874 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
2875 N->getOperand(4), N->getOperand(0) };
2876 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2879 // FIXME: Should custom lower this.
2880 SDValue Chain = N->getOperand(0);
2881 SDValue Target = N->getOperand(1);
2882 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2883 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2884 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2886 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2888 case PPCISD::TOC_ENTRY: {
2889 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2890 "Only supported for 64-bit ABI and 32-bit SVR4");
2891 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2892 SDValue GA = N->getOperand(0);
2893 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2894 MVT::i32, GA, N->getOperand(1)));
2897 // For medium and large code model, we generate two instructions as
2898 // described below. Otherwise we allow SelectCodeCommon to handle this,
2899 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2900 CodeModel::Model CModel = TM.getCodeModel();
2901 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2904 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2905 // If it must be toc-referenced according to PPCSubTarget, we generate:
2906 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2907 // Otherwise we generate:
2908 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2909 SDValue GA = N->getOperand(0);
2910 SDValue TOCbase = N->getOperand(1);
2911 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2914 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2915 CModel == CodeModel::Large)
2916 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2917 MVT::i64, GA, SDValue(Tmp, 0)));
2919 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2920 const GlobalValue *GV = G->getGlobal();
2921 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
2922 if (GVFlags & PPCII::MO_NLP_FLAG) {
2923 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2924 MVT::i64, GA, SDValue(Tmp, 0)));
2928 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2929 SDValue(Tmp, 0), GA);
2931 case PPCISD::PPC32_PICGOT: {
2932 // Generate a PIC-safe GOT reference.
2933 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2934 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2935 return CurDAG->SelectNodeTo(
2936 N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(CurDAG->getDataLayout()),
2939 case PPCISD::VADD_SPLAT: {
2940 // This expands into one of three sequences, depending on whether
2941 // the first operand is odd or even, positive or negative.
2942 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2943 isa<ConstantSDNode>(N->getOperand(1)) &&
2944 "Invalid operand on VADD_SPLAT!");
2946 int Elt = N->getConstantOperandVal(0);
2947 int EltSize = N->getConstantOperandVal(1);
2948 unsigned Opc1, Opc2, Opc3;
2952 Opc1 = PPC::VSPLTISB;
2953 Opc2 = PPC::VADDUBM;
2954 Opc3 = PPC::VSUBUBM;
2956 } else if (EltSize == 2) {
2957 Opc1 = PPC::VSPLTISH;
2958 Opc2 = PPC::VADDUHM;
2959 Opc3 = PPC::VSUBUHM;
2962 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2963 Opc1 = PPC::VSPLTISW;
2964 Opc2 = PPC::VADDUWM;
2965 Opc3 = PPC::VSUBUWM;
2969 if ((Elt & 1) == 0) {
2970 // Elt is even, in the range [-32,-18] + [16,30].
2972 // Convert: VADD_SPLAT elt, size
2973 // Into: tmp = VSPLTIS[BHW] elt
2974 // VADDU[BHW]M tmp, tmp
2975 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2976 SDValue EltVal = getI32Imm(Elt >> 1, dl);
2977 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2978 SDValue TmpVal = SDValue(Tmp, 0);
2979 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2981 } else if (Elt > 0) {
2982 // Elt is odd and positive, in the range [17,31].
2984 // Convert: VADD_SPLAT elt, size
2985 // Into: tmp1 = VSPLTIS[BHW] elt-16
2986 // tmp2 = VSPLTIS[BHW] -16
2987 // VSUBU[BHW]M tmp1, tmp2
2988 SDValue EltVal = getI32Imm(Elt - 16, dl);
2989 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2990 EltVal = getI32Imm(-16, dl);
2991 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2992 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2996 // Elt is odd and negative, in the range [-31,-17].
2998 // Convert: VADD_SPLAT elt, size
2999 // Into: tmp1 = VSPLTIS[BHW] elt+16
3000 // tmp2 = VSPLTIS[BHW] -16
3001 // VADDU[BHW]M tmp1, tmp2
3002 SDValue EltVal = getI32Imm(Elt + 16, dl);
3003 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3004 EltVal = getI32Imm(-16, dl);
3005 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3006 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3012 return SelectCode(N);
3015 // If the target supports the cmpb instruction, do the idiom recognition here.
3016 // We don't do this as a DAG combine because we don't want to do it as nodes
3017 // are being combined (because we might miss part of the eventual idiom). We
3018 // don't want to do it during instruction selection because we want to reuse
3019 // the logic for lowering the masking operations already part of the
3020 // instruction selector.
3021 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3024 assert(N->getOpcode() == ISD::OR &&
3025 "Only OR nodes are supported for CMPB");
3028 if (!PPCSubTarget->hasCMPB())
3031 if (N->getValueType(0) != MVT::i32 &&
3032 N->getValueType(0) != MVT::i64)
3035 EVT VT = N->getValueType(0);
3038 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3039 uint64_t Mask = 0, Alt = 0;
3041 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3042 uint64_t &Mask, uint64_t &Alt,
3043 SDValue &LHS, SDValue &RHS) {
3044 if (O.getOpcode() != ISD::SELECT_CC)
3046 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3048 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3049 !isa<ConstantSDNode>(O.getOperand(3)))
3052 uint64_t PM = O.getConstantOperandVal(2);
3053 uint64_t PAlt = O.getConstantOperandVal(3);
3054 for (b = 0; b < 8; ++b) {
3055 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3056 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3065 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3066 O.getConstantOperandVal(1) != 0) {
3067 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3068 if (Op0.getOpcode() == ISD::TRUNCATE)
3069 Op0 = Op0.getOperand(0);
3070 if (Op1.getOpcode() == ISD::TRUNCATE)
3071 Op1 = Op1.getOperand(0);
3073 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3074 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3075 isa<ConstantSDNode>(Op0.getOperand(1))) {
3077 unsigned Bits = Op0.getValueType().getSizeInBits();
3080 if (Op0.getConstantOperandVal(1) != Bits-8)
3083 LHS = Op0.getOperand(0);
3084 RHS = Op1.getOperand(0);
3088 // When we have small integers (i16 to be specific), the form present
3089 // post-legalization uses SETULT in the SELECT_CC for the
3090 // higher-order byte, depending on the fact that the
3091 // even-higher-order bytes are known to all be zero, for example:
3092 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3093 // (so when the second byte is the same, because all higher-order
3094 // bits from bytes 3 and 4 are known to be zero, the result of the
3095 // xor can be at most 255)
3096 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3097 isa<ConstantSDNode>(O.getOperand(1))) {
3099 uint64_t ULim = O.getConstantOperandVal(1);
3100 if (ULim != (UINT64_C(1) << b*8))
3103 // Now we need to make sure that the upper bytes are known to be
3105 unsigned Bits = Op0.getValueType().getSizeInBits();
3106 if (!CurDAG->MaskedValueIsZero(Op0,
3107 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3110 LHS = Op0.getOperand(0);
3111 RHS = Op0.getOperand(1);
3118 if (CC != ISD::SETEQ)
3121 SDValue Op = O.getOperand(0);
3122 if (Op.getOpcode() == ISD::AND) {
3123 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3125 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3128 SDValue XOR = Op.getOperand(0);
3129 if (XOR.getOpcode() == ISD::TRUNCATE)
3130 XOR = XOR.getOperand(0);
3131 if (XOR.getOpcode() != ISD::XOR)
3134 LHS = XOR.getOperand(0);
3135 RHS = XOR.getOperand(1);
3137 } else if (Op.getOpcode() == ISD::SRL) {
3138 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3140 unsigned Bits = Op.getValueType().getSizeInBits();
3143 if (Op.getConstantOperandVal(1) != Bits-8)
3146 SDValue XOR = Op.getOperand(0);
3147 if (XOR.getOpcode() == ISD::TRUNCATE)
3148 XOR = XOR.getOperand(0);
3149 if (XOR.getOpcode() != ISD::XOR)
3152 LHS = XOR.getOperand(0);
3153 RHS = XOR.getOperand(1);
3160 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3161 while (!Queue.empty()) {
3162 SDValue V = Queue.pop_back_val();
3164 for (const SDValue &O : V.getNode()->ops()) {
3166 uint64_t M = 0, A = 0;
3168 if (O.getOpcode() == ISD::OR) {
3170 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3174 BytesFound[b] = true;
3177 } else if ((LHS == ORHS && RHS == OLHS) ||
3178 (RHS == ORHS && LHS == OLHS)) {
3179 BytesFound[b] = true;
3191 unsigned LastB = 0, BCnt = 0;
3192 for (unsigned i = 0; i < 8; ++i)
3193 if (BytesFound[LastB]) {
3198 if (!LastB || BCnt < 2)
3201 // Because we'll be zero-extending the output anyway if don't have a specific
3202 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3203 if (LHS.getValueType() != VT) {
3204 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3205 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3208 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3210 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3211 if (NonTrivialMask && !Alt) {
3212 // Res = Mask & CMPB
3213 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3214 CurDAG->getConstant(Mask, dl, VT));
3216 // Res = (CMPB & Mask) | (~CMPB & Alt)
3217 // Which, as suggested here:
3218 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3219 // can be written as:
3220 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3221 // useful because the (Alt ^ Mask) can be pre-computed.
3222 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3223 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3224 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3225 CurDAG->getConstant(Alt, dl, VT));
3231 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3232 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3233 // involves constant materialization of a 0 or a 1 or both. If the result of
3234 // the extension is then operated upon by some operator that can be constant
3235 // folded with a constant 0 or 1, and that constant can be materialized using
3236 // only one instruction (like a zero or one), then we should fold in those
3237 // operations with the select.
3238 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3239 if (!PPCSubTarget->useCRBits())
3242 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3243 N->getOpcode() != ISD::SIGN_EXTEND &&
3244 N->getOpcode() != ISD::ANY_EXTEND)
3247 if (N->getOperand(0).getValueType() != MVT::i1)
3250 if (!N->hasOneUse())
3254 EVT VT = N->getValueType(0);
3255 SDValue Cond = N->getOperand(0);
3257 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3258 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3261 SDNode *User = *N->use_begin();
3262 if (User->getNumOperands() != 2)
3265 auto TryFold = [this, N, User, dl](SDValue Val) {
3266 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3267 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3268 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3270 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3271 User->getValueType(0),
3272 O0.getNode(), O1.getNode());
3275 SDValue TrueRes = TryFold(ConstTrue);
3278 SDValue FalseRes = TryFold(ConstFalse);
3282 // For us to materialize these using one instruction, we must be able to
3283 // represent them as signed 16-bit integers.
3284 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3285 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3286 if (!isInt<16>(True) || !isInt<16>(False))
3289 // We can replace User with a new SELECT node, and try again to see if we
3290 // can fold the select with its user.
3291 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3293 ConstTrue = TrueRes;
3294 ConstFalse = FalseRes;
3295 } while (N->hasOneUse());
3298 void PPCDAGToDAGISel::PreprocessISelDAG() {
3299 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3302 bool MadeChange = false;
3303 while (Position != CurDAG->allnodes_begin()) {
3304 SDNode *N = &*--Position;
3309 switch (N->getOpcode()) {
3312 Res = combineToCMPB(N);
3317 foldBoolExts(Res, N);
3320 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3321 DEBUG(N->dump(CurDAG));
3322 DEBUG(dbgs() << "\nNew: ");
3323 DEBUG(Res.getNode()->dump(CurDAG));
3324 DEBUG(dbgs() << "\n");
3326 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3332 CurDAG->RemoveDeadNodes();
3335 /// PostprocessISelDAG - Perform some late peephole optimizations
3336 /// on the DAG representation.
3337 void PPCDAGToDAGISel::PostprocessISelDAG() {
3339 // Skip peepholes at -O0.
3340 if (TM.getOptLevel() == CodeGenOpt::None)
3345 PeepholePPC64ZExt();
3348 // Check if all users of this node will become isel where the second operand
3349 // is the constant zero. If this is so, and if we can negate the condition,
3350 // then we can flip the true and false operands. This will allow the zero to
3351 // be folded with the isel so that we don't need to materialize a register
3353 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3354 // If we're not using isel, then this does not matter.
3355 if (!PPCSubTarget->hasISEL())
3358 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3361 if (!User->isMachineOpcode())
3363 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3364 User->getMachineOpcode() != PPC::SELECT_I8)
3367 SDNode *Op2 = User->getOperand(2).getNode();
3368 if (!Op2->isMachineOpcode())
3371 if (Op2->getMachineOpcode() != PPC::LI &&
3372 Op2->getMachineOpcode() != PPC::LI8)
3375 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3379 if (!C->isNullValue())
3386 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3387 SmallVector<SDNode *, 4> ToReplace;
3388 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3391 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3392 User->getMachineOpcode() == PPC::SELECT_I8) &&
3393 "Must have all select users");
3394 ToReplace.push_back(User);
3397 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3398 UE = ToReplace.end(); UI != UE; ++UI) {
3401 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3402 User->getValueType(0), User->getOperand(0),
3403 User->getOperand(2),
3404 User->getOperand(1));
3406 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3407 DEBUG(User->dump(CurDAG));
3408 DEBUG(dbgs() << "\nNew: ");
3409 DEBUG(ResNode->dump(CurDAG));
3410 DEBUG(dbgs() << "\n");
3412 ReplaceUses(User, ResNode);
3416 void PPCDAGToDAGISel::PeepholeCROps() {
3420 for (SDNode &Node : CurDAG->allnodes()) {
3421 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
3422 if (!MachineNode || MachineNode->use_empty())
3424 SDNode *ResNode = MachineNode;
3426 bool Op1Set = false, Op1Unset = false,
3428 Op2Set = false, Op2Unset = false,
3431 unsigned Opcode = MachineNode->getMachineOpcode();
3442 SDValue Op = MachineNode->getOperand(1);
3443 if (Op.isMachineOpcode()) {
3444 if (Op.getMachineOpcode() == PPC::CRSET)
3446 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3448 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3449 Op.getOperand(0) == Op.getOperand(1))
3455 case PPC::SELECT_I4:
3456 case PPC::SELECT_I8:
3457 case PPC::SELECT_F4:
3458 case PPC::SELECT_F8:
3459 case PPC::SELECT_QFRC:
3460 case PPC::SELECT_QSRC:
3461 case PPC::SELECT_QBRC:
3462 case PPC::SELECT_VRRC:
3463 case PPC::SELECT_VSFRC:
3464 case PPC::SELECT_VSSRC:
3465 case PPC::SELECT_VSRC: {
3466 SDValue Op = MachineNode->getOperand(0);
3467 if (Op.isMachineOpcode()) {
3468 if (Op.getMachineOpcode() == PPC::CRSET)
3470 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3472 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3473 Op.getOperand(0) == Op.getOperand(1))
3480 bool SelectSwap = false;
3484 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3486 ResNode = MachineNode->getOperand(0).getNode();
3489 ResNode = MachineNode->getOperand(1).getNode();
3492 ResNode = MachineNode->getOperand(0).getNode();
3493 else if (Op1Unset || Op2Unset)
3494 // x & 0 = 0 & y = 0
3495 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3498 // ~x & y = andc(y, x)
3499 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3500 MVT::i1, MachineNode->getOperand(1),
3501 MachineNode->getOperand(0).
3504 // x & ~y = andc(x, y)
3505 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3506 MVT::i1, MachineNode->getOperand(0),
3507 MachineNode->getOperand(1).
3509 else if (AllUsersSelectZero(MachineNode))
3510 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3511 MVT::i1, MachineNode->getOperand(0),
3512 MachineNode->getOperand(1)),
3516 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3517 // nand(x, x) -> nor(x, x)
3518 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3519 MVT::i1, MachineNode->getOperand(0),
3520 MachineNode->getOperand(0));
3522 // nand(1, y) -> nor(y, y)
3523 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3524 MVT::i1, MachineNode->getOperand(1),
3525 MachineNode->getOperand(1));
3527 // nand(x, 1) -> nor(x, x)
3528 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3529 MVT::i1, MachineNode->getOperand(0),
3530 MachineNode->getOperand(0));
3531 else if (Op1Unset || Op2Unset)
3532 // nand(x, 0) = nand(0, y) = 1
3533 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3536 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3537 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3538 MVT::i1, MachineNode->getOperand(0).
3540 MachineNode->getOperand(1));
3542 // nand(x, ~y) = ~x | y = orc(y, x)
3543 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3544 MVT::i1, MachineNode->getOperand(1).
3546 MachineNode->getOperand(0));
3547 else if (AllUsersSelectZero(MachineNode))
3548 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3549 MVT::i1, MachineNode->getOperand(0),
3550 MachineNode->getOperand(1)),
3554 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3556 ResNode = MachineNode->getOperand(0).getNode();
3557 else if (Op1Set || Op2Set)
3558 // x | 1 = 1 | y = 1
3559 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3563 ResNode = MachineNode->getOperand(1).getNode();
3566 ResNode = MachineNode->getOperand(0).getNode();
3568 // ~x | y = orc(y, x)
3569 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3570 MVT::i1, MachineNode->getOperand(1),
3571 MachineNode->getOperand(0).
3574 // x | ~y = orc(x, y)
3575 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3576 MVT::i1, MachineNode->getOperand(0),
3577 MachineNode->getOperand(1).
3579 else if (AllUsersSelectZero(MachineNode))
3580 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3581 MVT::i1, MachineNode->getOperand(0),
3582 MachineNode->getOperand(1)),
3586 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3588 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3591 // xor(1, y) -> nor(y, y)
3592 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3593 MVT::i1, MachineNode->getOperand(1),
3594 MachineNode->getOperand(1));
3596 // xor(x, 1) -> nor(x, x)
3597 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3598 MVT::i1, MachineNode->getOperand(0),
3599 MachineNode->getOperand(0));
3602 ResNode = MachineNode->getOperand(1).getNode();
3605 ResNode = MachineNode->getOperand(0).getNode();
3607 // xor(~x, y) = eqv(x, y)
3608 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3609 MVT::i1, MachineNode->getOperand(0).
3611 MachineNode->getOperand(1));
3613 // xor(x, ~y) = eqv(x, y)
3614 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3615 MVT::i1, MachineNode->getOperand(0),
3616 MachineNode->getOperand(1).
3618 else if (AllUsersSelectZero(MachineNode))
3619 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3620 MVT::i1, MachineNode->getOperand(0),
3621 MachineNode->getOperand(1)),
3625 if (Op1Set || Op2Set)
3627 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3630 // nor(0, y) = ~y -> nor(y, y)
3631 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3632 MVT::i1, MachineNode->getOperand(1),
3633 MachineNode->getOperand(1));
3636 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3637 MVT::i1, MachineNode->getOperand(0),
3638 MachineNode->getOperand(0));
3640 // nor(~x, y) = andc(x, y)
3641 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3642 MVT::i1, MachineNode->getOperand(0).
3644 MachineNode->getOperand(1));
3646 // nor(x, ~y) = andc(y, x)
3647 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3648 MVT::i1, MachineNode->getOperand(1).
3650 MachineNode->getOperand(0));
3651 else if (AllUsersSelectZero(MachineNode))
3652 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3653 MVT::i1, MachineNode->getOperand(0),
3654 MachineNode->getOperand(1)),
3658 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3660 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3664 ResNode = MachineNode->getOperand(1).getNode();
3667 ResNode = MachineNode->getOperand(0).getNode();
3669 // eqv(0, y) = ~y -> nor(y, y)
3670 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3671 MVT::i1, MachineNode->getOperand(1),
3672 MachineNode->getOperand(1));
3675 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3676 MVT::i1, MachineNode->getOperand(0),
3677 MachineNode->getOperand(0));
3679 // eqv(~x, y) = xor(x, y)
3680 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3681 MVT::i1, MachineNode->getOperand(0).
3683 MachineNode->getOperand(1));
3685 // eqv(x, ~y) = xor(x, y)
3686 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3687 MVT::i1, MachineNode->getOperand(0),
3688 MachineNode->getOperand(1).
3690 else if (AllUsersSelectZero(MachineNode))
3691 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3692 MVT::i1, MachineNode->getOperand(0),
3693 MachineNode->getOperand(1)),
3697 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3699 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3703 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3704 MVT::i1, MachineNode->getOperand(1),
3705 MachineNode->getOperand(1));
3706 else if (Op1Unset || Op2Set)
3707 // andc(0, y) = andc(x, 1) = 0
3708 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3712 ResNode = MachineNode->getOperand(0).getNode();
3714 // andc(~x, y) = ~(x | y) = nor(x, y)
3715 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3716 MVT::i1, MachineNode->getOperand(0).
3718 MachineNode->getOperand(1));
3720 // andc(x, ~y) = x & y
3721 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3722 MVT::i1, MachineNode->getOperand(0),
3723 MachineNode->getOperand(1).
3725 else if (AllUsersSelectZero(MachineNode))
3726 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3727 MVT::i1, MachineNode->getOperand(1),
3728 MachineNode->getOperand(0)),
3732 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3734 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3736 else if (Op1Set || Op2Unset)
3737 // orc(1, y) = orc(x, 0) = 1
3738 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3742 ResNode = MachineNode->getOperand(0).getNode();
3745 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3746 MVT::i1, MachineNode->getOperand(1),
3747 MachineNode->getOperand(1));
3749 // orc(~x, y) = ~(x & y) = nand(x, y)
3750 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3751 MVT::i1, MachineNode->getOperand(0).
3753 MachineNode->getOperand(1));
3755 // orc(x, ~y) = x | y
3756 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3757 MVT::i1, MachineNode->getOperand(0),
3758 MachineNode->getOperand(1).
3760 else if (AllUsersSelectZero(MachineNode))
3761 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3762 MVT::i1, MachineNode->getOperand(1),
3763 MachineNode->getOperand(0)),
3766 case PPC::SELECT_I4:
3767 case PPC::SELECT_I8:
3768 case PPC::SELECT_F4:
3769 case PPC::SELECT_F8:
3770 case PPC::SELECT_QFRC:
3771 case PPC::SELECT_QSRC:
3772 case PPC::SELECT_QBRC:
3773 case PPC::SELECT_VRRC:
3774 case PPC::SELECT_VSFRC:
3775 case PPC::SELECT_VSSRC:
3776 case PPC::SELECT_VSRC:
3778 ResNode = MachineNode->getOperand(1).getNode();
3780 ResNode = MachineNode->getOperand(2).getNode();
3782 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3784 MachineNode->getValueType(0),
3785 MachineNode->getOperand(0).
3787 MachineNode->getOperand(2),
3788 MachineNode->getOperand(1));
3793 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3797 MachineNode->getOperand(0).
3799 MachineNode->getOperand(1),
3800 MachineNode->getOperand(2));
3801 // FIXME: Handle Op1Set, Op1Unset here too.
3805 // If we're inverting this node because it is used only by selects that
3806 // we'd like to swap, then swap the selects before the node replacement.
3808 SwapAllSelectUsers(MachineNode);
3810 if (ResNode != MachineNode) {
3811 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3812 DEBUG(MachineNode->dump(CurDAG));
3813 DEBUG(dbgs() << "\nNew: ");
3814 DEBUG(ResNode->dump(CurDAG));
3815 DEBUG(dbgs() << "\n");
3817 ReplaceUses(MachineNode, ResNode);
3822 CurDAG->RemoveDeadNodes();
3823 } while (IsModified);
3826 // Gather the set of 32-bit operations that are known to have their
3827 // higher-order 32 bits zero, where ToPromote contains all such operations.
3828 static bool PeepholePPC64ZExtGather(SDValue Op32,
3829 SmallPtrSetImpl<SDNode *> &ToPromote) {
3830 if (!Op32.isMachineOpcode())
3833 // First, check for the "frontier" instructions (those that will clear the
3834 // higher-order 32 bits.
3836 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3837 // around. If it does not, then these instructions will clear the
3838 // higher-order bits.
3839 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3840 Op32.getMachineOpcode() == PPC::RLWNM) &&
3841 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3842 ToPromote.insert(Op32.getNode());
3846 // SLW and SRW always clear the higher-order bits.
3847 if (Op32.getMachineOpcode() == PPC::SLW ||
3848 Op32.getMachineOpcode() == PPC::SRW) {
3849 ToPromote.insert(Op32.getNode());
3853 // For LI and LIS, we need the immediate to be positive (so that it is not
3855 if (Op32.getMachineOpcode() == PPC::LI ||
3856 Op32.getMachineOpcode() == PPC::LIS) {
3857 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3860 ToPromote.insert(Op32.getNode());
3864 // LHBRX and LWBRX always clear the higher-order bits.
3865 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3866 Op32.getMachineOpcode() == PPC::LWBRX) {
3867 ToPromote.insert(Op32.getNode());
3871 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3872 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3873 ToPromote.insert(Op32.getNode());
3877 // Next, check for those instructions we can look through.
3879 // Assuming the mask does not wrap around, then the higher-order bits are
3880 // taken directly from the first operand.
3881 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3882 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3883 SmallPtrSet<SDNode *, 16> ToPromote1;
3884 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3887 ToPromote.insert(Op32.getNode());
3888 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3892 // For OR, the higher-order bits are zero if that is true for both operands.
3893 // For SELECT_I4, the same is true (but the relevant operand numbers are
3895 if (Op32.getMachineOpcode() == PPC::OR ||
3896 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3897 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3898 SmallPtrSet<SDNode *, 16> ToPromote1;
3899 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3901 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3904 ToPromote.insert(Op32.getNode());
3905 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3909 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3910 // zero, and also for the constant to be positive (so that it is not sign
3912 if (Op32.getMachineOpcode() == PPC::ORI ||
3913 Op32.getMachineOpcode() == PPC::ORIS) {
3914 SmallPtrSet<SDNode *, 16> ToPromote1;
3915 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3917 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3920 ToPromote.insert(Op32.getNode());
3921 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3925 // The higher-order bits of AND are zero if that is true for at least one of
3927 if (Op32.getMachineOpcode() == PPC::AND) {
3928 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3930 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3932 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3933 if (!Op0OK && !Op1OK)
3936 ToPromote.insert(Op32.getNode());
3939 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3942 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3947 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3948 // of the first operand, or if the second operand is positive (so that it is
3949 // not sign extended).
3950 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3951 Op32.getMachineOpcode() == PPC::ANDISo) {
3952 SmallPtrSet<SDNode *, 16> ToPromote1;
3954 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3955 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3956 if (!Op0OK && !Op1OK)
3959 ToPromote.insert(Op32.getNode());
3962 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3970 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3971 if (!PPCSubTarget->isPPC64())
3974 // When we zero-extend from i32 to i64, we use a pattern like this:
3975 // def : Pat<(i64 (zext i32:$in)),
3976 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3978 // There are several 32-bit shift/rotate instructions, however, that will
3979 // clear the higher-order bits of their output, rendering the RLDICL
3980 // unnecessary. When that happens, we remove it here, and redefine the
3981 // relevant 32-bit operation to be a 64-bit operation.
3983 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3986 bool MadeChange = false;
3987 while (Position != CurDAG->allnodes_begin()) {
3988 SDNode *N = &*--Position;
3989 // Skip dead nodes and any non-machine opcodes.
3990 if (N->use_empty() || !N->isMachineOpcode())
3993 if (N->getMachineOpcode() != PPC::RLDICL)
3996 if (N->getConstantOperandVal(1) != 0 ||
3997 N->getConstantOperandVal(2) != 32)
4000 SDValue ISR = N->getOperand(0);
4001 if (!ISR.isMachineOpcode() ||
4002 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4005 if (!ISR.hasOneUse())
4008 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4011 SDValue IDef = ISR.getOperand(0);
4012 if (!IDef.isMachineOpcode() ||
4013 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4016 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4017 // can get rid of it.
4019 SDValue Op32 = ISR->getOperand(1);
4020 if (!Op32.isMachineOpcode())
4023 // There are some 32-bit instructions that always clear the high-order 32
4024 // bits, there are also some instructions (like AND) that we can look
4026 SmallPtrSet<SDNode *, 16> ToPromote;
4027 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4030 // If the ToPromote set contains nodes that have uses outside of the set
4031 // (except for the original INSERT_SUBREG), then abort the transformation.
4032 bool OutsideUse = false;
4033 for (SDNode *PN : ToPromote) {
4034 for (SDNode *UN : PN->uses()) {
4035 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4049 // We now know that this zero extension can be removed by promoting to
4050 // nodes in ToPromote to 64-bit operations, where for operations in the
4051 // frontier of the set, we need to insert INSERT_SUBREGs for their
4053 for (SDNode *PN : ToPromote) {
4055 switch (PN->getMachineOpcode()) {
4057 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4058 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4059 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4060 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4061 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4062 case PPC::LI: NewOpcode = PPC::LI8; break;
4063 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4064 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4065 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4066 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4067 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4068 case PPC::OR: NewOpcode = PPC::OR8; break;
4069 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4070 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4071 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4072 case PPC::AND: NewOpcode = PPC::AND8; break;
4073 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4074 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4077 // Note: During the replacement process, the nodes will be in an
4078 // inconsistent state (some instructions will have operands with values
4079 // of the wrong type). Once done, however, everything should be right
4082 SmallVector<SDValue, 4> Ops;
4083 for (const SDValue &V : PN->ops()) {
4084 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4085 !isa<ConstantSDNode>(V)) {
4086 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4088 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4089 ISR.getNode()->getVTList(), ReplOpOps);
4090 Ops.push_back(SDValue(ReplOp, 0));
4096 // Because all to-be-promoted nodes only have users that are other
4097 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4098 // the i32 result value type with i64.
4100 SmallVector<EVT, 2> NewVTs;
4101 SDVTList VTs = PN->getVTList();
4102 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4103 if (VTs.VTs[i] == MVT::i32)
4104 NewVTs.push_back(MVT::i64);
4106 NewVTs.push_back(VTs.VTs[i]);
4108 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4109 DEBUG(PN->dump(CurDAG));
4111 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4113 DEBUG(dbgs() << "\nNew: ");
4114 DEBUG(PN->dump(CurDAG));
4115 DEBUG(dbgs() << "\n");
4118 // Now we replace the original zero extend and its associated INSERT_SUBREG
4119 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4122 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4123 DEBUG(N->dump(CurDAG));
4124 DEBUG(dbgs() << "\nNew: ");
4125 DEBUG(Op32.getNode()->dump(CurDAG));
4126 DEBUG(dbgs() << "\n");
4128 ReplaceUses(N, Op32.getNode());
4132 CurDAG->RemoveDeadNodes();
4135 void PPCDAGToDAGISel::PeepholePPC64() {
4136 // These optimizations are currently supported only for 64-bit SVR4.
4137 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4140 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4143 while (Position != CurDAG->allnodes_begin()) {
4144 SDNode *N = &*--Position;
4145 // Skip dead nodes and any non-machine opcodes.
4146 if (N->use_empty() || !N->isMachineOpcode())
4150 unsigned StorageOpcode = N->getMachineOpcode();
4152 switch (StorageOpcode) {
4183 // If this is a load or store with a zero offset, or within the alignment,
4184 // we may be able to fold an add-immediate into the memory operation.
4185 // The check against alignment is below, as it can't occur until we check
4186 // the arguments to N
4187 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4190 SDValue Base = N->getOperand(FirstOp + 1);
4191 if (!Base.isMachineOpcode())
4194 // On targets with fusion, we don't want this to fire and remove a fusion
4195 // opportunity, unless a) it results in another fusion opportunity or
4196 // b) optimizing for size.
4197 if (PPCSubTarget->hasFusion() &&
4198 (!MF->getFunction()->optForSize() && !Base.hasOneUse()))
4202 bool ReplaceFlags = true;
4204 // When the feeding operation is an add-immediate of some sort,
4205 // determine whether we need to add relocation information to the
4206 // target flags on the immediate operand when we fold it into the
4207 // load instruction.
4209 // For something like ADDItocL, the relocation information is
4210 // inferred from the opcode; when we process it in the AsmPrinter,
4211 // we add the necessary relocation there. A load, though, can receive
4212 // relocation from various flavors of ADDIxxx, so we need to carry
4213 // the relocation information in the target flags.
4214 switch (Base.getMachineOpcode()) {
4219 // In some cases (such as TLS) the relocation information
4220 // is already in place on the operand, so copying the operand
4222 ReplaceFlags = false;
4223 // For these cases, the immediate may not be divisible by 4, in
4224 // which case the fold is illegal for DS-form instructions. (The
4225 // other cases provide aligned addresses and are always safe.)
4226 if ((StorageOpcode == PPC::LWA ||
4227 StorageOpcode == PPC::LD ||
4228 StorageOpcode == PPC::STD) &&
4229 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4230 Base.getConstantOperandVal(1) % 4 != 0))
4233 case PPC::ADDIdtprelL:
4234 Flags = PPCII::MO_DTPREL_LO;
4236 case PPC::ADDItlsldL:
4237 Flags = PPCII::MO_TLSLD_LO;
4240 Flags = PPCII::MO_TOC_LO;
4244 SDValue ImmOpnd = Base.getOperand(1);
4245 int MaxDisplacement = 0;
4246 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4247 const GlobalValue *GV = GA->getGlobal();
4248 MaxDisplacement = GV->getAlignment() - 1;
4251 int Offset = N->getConstantOperandVal(FirstOp);
4252 if (Offset < 0 || Offset > MaxDisplacement)
4255 // We found an opportunity. Reverse the operands from the add
4256 // immediate and substitute them into the load or store. If
4257 // needed, update the target flags for the immediate operand to
4258 // reflect the necessary relocation information.
4259 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4260 DEBUG(Base->dump(CurDAG));
4261 DEBUG(dbgs() << "\nN: ");
4262 DEBUG(N->dump(CurDAG));
4263 DEBUG(dbgs() << "\n");
4265 // If the relocation information isn't already present on the
4266 // immediate operand, add it now.
4268 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4270 const GlobalValue *GV = GA->getGlobal();
4271 // We can't perform this optimization for data whose alignment
4272 // is insufficient for the instruction encoding.
4273 if (GV->getAlignment() < 4 &&
4274 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4275 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
4276 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4279 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
4280 } else if (ConstantPoolSDNode *CP =
4281 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4282 const Constant *C = CP->getConstVal();
4283 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4289 if (FirstOp == 1) // Store
4290 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4291 Base.getOperand(0), N->getOperand(3));
4293 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4296 // The add-immediate may now be dead, in which case remove it.
4297 if (Base.getNode()->use_empty())
4298 CurDAG->RemoveDeadNode(Base.getNode());
4303 /// createPPCISelDag - This pass converts a legalized DAG into a
4304 /// PowerPC-specific DAG, ready for instruction scheduling.
4306 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4307 return new PPCDAGToDAGISel(TM);
4310 static void initializePassOnce(PassRegistry &Registry) {
4311 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4312 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4313 nullptr, false, false);
4314 Registry.registerPass(*PI, true);
4317 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4318 CALL_ONCE_INITIALIZATION(initializePassOnce);