1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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 "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
35 Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
37 //===--------------------------------------------------------------------===//
38 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
39 /// instructions for SelectionDAG operations.
41 class PPCDAGToDAGISel : public SelectionDAGISel {
43 PPCTargetLowering PPCLowering;
44 unsigned GlobalBaseReg;
46 PPCDAGToDAGISel(PPCTargetMachine &tm)
47 : SelectionDAGISel(PPCLowering), TM(tm),
48 PPCLowering(*TM.getTargetLowering()) {}
50 virtual bool runOnFunction(Function &Fn) {
51 // Make sure we re-emit a set of the global base reg if necessary
53 SelectionDAGISel::runOnFunction(Fn);
59 /// getI32Imm - Return a target constant with the specified value, of type
61 inline SDOperand getI32Imm(unsigned Imm) {
62 return CurDAG->getTargetConstant(Imm, MVT::i32);
65 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
66 /// base register. Return the virtual register that holds this value.
67 SDOperand getGlobalBaseReg();
69 // Select - Convert the specified operand from a target-independent to a
70 // target-specific node if it hasn't already been changed.
71 void Select(SDOperand &Result, SDOperand Op);
73 SDNode *SelectBitfieldInsert(SDNode *N);
75 /// SelectCC - Select a comparison of the specified values with the
76 /// specified condition code, returning the CR# of the expression.
77 SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
79 /// SelectAddrImm - Returns true if the address N can be represented by
80 /// a base register plus a signed 16-bit displacement [r+imm].
81 bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
83 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
84 /// represented as an indexed [r+r] operation. Returns false if it can
85 /// be represented by [r+imm], which are preferred.
86 bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
88 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
89 /// represented as an indexed [r+r] operation.
90 bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
92 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
93 /// inline asm expressions.
94 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
96 std::vector<SDOperand> &OutOps,
99 switch (ConstraintCode) {
100 default: return true;
102 if (!SelectAddrIdx(Op, Op0, Op1))
103 SelectAddrImm(Op, Op0, Op1);
105 case 'o': // offsetable
106 if (!SelectAddrImm(Op, Op0, Op1)) {
107 Select(Op0, Op); // r+0.
111 case 'v': // not offsetable
112 SelectAddrIdxOnly(Op, Op0, Op1);
116 OutOps.push_back(Op0);
117 OutOps.push_back(Op1);
121 SDOperand BuildSDIVSequence(SDNode *N);
122 SDOperand BuildUDIVSequence(SDNode *N);
124 /// InstructionSelectBasicBlock - This callback is invoked by
125 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
126 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
128 void InsertVRSaveCode(Function &Fn);
130 virtual const char *getPassName() const {
131 return "PowerPC DAG->DAG Pattern Instruction Selection";
134 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for this
135 /// target when scheduling the DAG.
136 virtual HazardRecognizer *CreateTargetHazardRecognizer() {
137 // Should use subtarget info to pick the right hazard recognizer. For
138 // now, always return a PPC970 recognizer.
139 const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
140 assert(II && "No InstrInfo?");
141 return new PPCHazardRecognizer970(*II);
144 // Include the pieces autogenerated from the target description.
145 #include "PPCGenDAGISel.inc"
148 SDOperand SelectSETCC(SDOperand Op);
149 SDOperand SelectCALL(SDOperand Op);
153 /// InstructionSelectBasicBlock - This callback is invoked by
154 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
155 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
158 // The selection process is inherently a bottom-up recursive process (users
159 // select their uses before themselves). Given infinite stack space, we
160 // could just start selecting on the root and traverse the whole graph. In
161 // practice however, this causes us to run out of stack space on large basic
162 // blocks. To avoid this problem, select the entry node, then all its uses,
163 // iteratively instead of recursively.
164 std::vector<SDOperand> Worklist;
165 Worklist.push_back(DAG.getEntryNode());
167 // Note that we can do this in the PPC target (scanning forward across token
168 // chain edges) because no nodes ever get folded across these edges. On a
169 // target like X86 which supports load/modify/store operations, this would
170 // have to be more careful.
171 while (!Worklist.empty()) {
172 SDOperand Node = Worklist.back();
175 // Chose from the least deep of the top two nodes.
176 if (!Worklist.empty() &&
177 Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
178 std::swap(Worklist.back(), Node);
180 if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
181 Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
182 CodeGenMap.count(Node)) continue;
184 for (SDNode::use_iterator UI = Node.Val->use_begin(),
185 E = Node.Val->use_end(); UI != E; ++UI) {
186 // Scan the values. If this use has a value that is a token chain, add it
189 for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
190 if (User->getValueType(i) == MVT::Other) {
191 Worklist.push_back(SDOperand(User, i));
196 // Finally, legalize this node.
201 // Select target instructions for the DAG.
202 DAG.setRoot(SelectRoot(DAG.getRoot()));
204 DAG.RemoveDeadNodes();
206 // Emit machine code to BB.
207 ScheduleAndEmitDAG(DAG);
210 /// InsertVRSaveCode - Once the entire function has been instruction selected,
211 /// all virtual registers are created and all machine instructions are built,
212 /// check to see if we need to save/restore VRSAVE. If so, do it.
213 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
214 // Check to see if this function uses vector registers, which means we have to
215 // save and restore the VRSAVE register and update it with the regs we use.
217 // In this case, there will be virtual registers of vector type type created
218 // by the scheduler. Detect them now.
219 MachineFunction &Fn = MachineFunction::get(&F);
220 SSARegMap *RegMap = Fn.getSSARegMap();
221 bool HasVectorVReg = false;
222 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
223 e = RegMap->getLastVirtReg()+1; i != e; ++i)
224 if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
225 HasVectorVReg = true;
228 if (!HasVectorVReg) return; // nothing to do.
230 // If we have a vector register, we want to emit code into the entry and exit
231 // blocks to save and restore the VRSAVE register. We do this here (instead
232 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
234 // 1. This (trivially) reduces the load on the register allocator, by not
235 // having to represent the live range of the VRSAVE register.
236 // 2. This (more significantly) allows us to create a temporary virtual
237 // register to hold the saved VRSAVE value, allowing this temporary to be
238 // register allocated, instead of forcing it to be spilled to the stack.
240 // Create two vregs - one to hold the VRSAVE register that is live-in to the
241 // function and one for the value after having bits or'd into it.
242 unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
243 unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
245 MachineBasicBlock &EntryBB = *Fn.begin();
246 // Emit the following code into the entry block:
247 // InVRSAVE = MFVRSAVE
248 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
249 // MTVRSAVE UpdatedVRSAVE
250 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
251 BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
252 BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
253 BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
255 // Find all return blocks, outputting a restore in each epilog.
256 const TargetInstrInfo &TII = *TM.getInstrInfo();
257 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
258 if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
259 IP = BB->end(); --IP;
261 // Skip over all terminator instructions, which are part of the return
263 MachineBasicBlock::iterator I2 = IP;
264 while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
267 // Emit: MTVRSAVE InVRSave
268 BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
274 /// getGlobalBaseReg - Output the instructions required to put the
275 /// base address to use for accessing globals into a register.
277 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
278 if (!GlobalBaseReg) {
279 // Insert the set of GlobalBaseReg into the first MBB of the function
280 MachineBasicBlock &FirstMBB = BB->getParent()->front();
281 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
282 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
283 // FIXME: when we get to LP64, we will need to create the appropriate
284 // type of register here.
285 GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
286 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
287 BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
289 return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
293 // isIntImmediate - This method tests to see if a constant operand.
294 // If so Imm will receive the 32 bit value.
295 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
296 if (N->getOpcode() == ISD::Constant) {
297 Imm = cast<ConstantSDNode>(N)->getValue();
303 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
304 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
305 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
306 // not, since all 1s are not contiguous.
307 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
308 if (isShiftedMask_32(Val)) {
309 // look for the first non-zero bit
310 MB = CountLeadingZeros_32(Val);
311 // look for the first zero bit after the run of ones
312 ME = CountLeadingZeros_32((Val - 1) ^ Val);
315 Val = ~Val; // invert mask
316 if (isShiftedMask_32(Val)) {
317 // effectively look for the first zero bit
318 ME = CountLeadingZeros_32(Val) - 1;
319 // effectively look for the first one bit after the run of zeros
320 MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
328 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
329 // and mask opcode and mask operation.
330 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
331 unsigned &SH, unsigned &MB, unsigned &ME) {
332 // Don't even go down this path for i64, since different logic will be
333 // necessary for rldicl/rldicr/rldimi.
334 if (N->getValueType(0) != MVT::i32)
338 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
339 unsigned Opcode = N->getOpcode();
340 if (N->getNumOperands() != 2 ||
341 !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
344 if (Opcode == ISD::SHL) {
345 // apply shift left to mask if it comes first
346 if (IsShiftMask) Mask = Mask << Shift;
347 // determine which bits are made indeterminant by shift
348 Indeterminant = ~(0xFFFFFFFFu << Shift);
349 } else if (Opcode == ISD::SRL) {
350 // apply shift right to mask if it comes first
351 if (IsShiftMask) Mask = Mask >> Shift;
352 // determine which bits are made indeterminant by shift
353 Indeterminant = ~(0xFFFFFFFFu >> Shift);
354 // adjust for the left rotate
360 // if the mask doesn't intersect any Indeterminant bits
361 if (Mask && !(Mask & Indeterminant)) {
363 // make sure the mask is still a mask (wrap arounds may not be)
364 return isRunOfOnes(Mask, MB, ME);
369 // isOpcWithIntImmediate - This method tests to see if the node is a specific
370 // opcode and that it has a immediate integer right operand.
371 // If so Imm will receive the 32 bit value.
372 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
373 return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
376 // isIntImmediate - This method tests to see if a constant operand.
377 // If so Imm will receive the 32 bit value.
378 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
379 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
380 Imm = (unsigned)CN->getSignExtended();
386 /// SelectBitfieldInsert - turn an or of two masked values into
387 /// the rotate left word immediate then mask insert (rlwimi) instruction.
388 /// Returns true on success, false if the caller still needs to select OR.
390 /// Patterns matched:
391 /// 1. or shl, and 5. or and, and
392 /// 2. or and, shl 6. or shl, shr
393 /// 3. or shr, and 7. or shr, shl
395 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
396 bool IsRotate = false;
397 unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
400 SDOperand Op0 = N->getOperand(0);
401 SDOperand Op1 = N->getOperand(1);
403 unsigned Op0Opc = Op0.getOpcode();
404 unsigned Op1Opc = Op1.getOpcode();
406 // Verify that we have the correct opcodes
407 if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
409 if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
412 // Generate Mask value for Target
413 if (isIntImmediate(Op0.getOperand(1), Value)) {
415 case ISD::SHL: TgtMask <<= Value; break;
416 case ISD::SRL: TgtMask >>= Value; break;
417 case ISD::AND: TgtMask &= Value; break;
423 // Generate Mask value for Insert
424 if (!isIntImmediate(Op1.getOperand(1), Value))
431 if (Op0Opc == ISD::SRL) IsRotate = true;
437 if (Op0Opc == ISD::SHL) IsRotate = true;
444 // If both of the inputs are ANDs and one of them has a logical shift by
445 // constant as its input, make that AND the inserted value so that we can
446 // combine the shift into the rotate part of the rlwimi instruction
447 bool IsAndWithShiftOp = false;
448 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
449 if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
450 Op1.getOperand(0).getOpcode() == ISD::SRL) {
451 if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
452 SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
453 IsAndWithShiftOp = true;
455 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
456 Op0.getOperand(0).getOpcode() == ISD::SRL) {
457 if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
459 std::swap(TgtMask, InsMask);
460 SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
461 IsAndWithShiftOp = true;
466 // Verify that the Target mask and Insert mask together form a full word mask
467 // and that the Insert mask is a run of set bits (which implies both are runs
468 // of set bits). Given that, Select the arguments and generate the rlwimi
471 if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
472 bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
473 bool Op0IsAND = Op0Opc == ISD::AND;
474 // Check for rotlwi / rotrwi here, a special case of bitfield insert
475 // where both bitfield halves are sourced from the same value.
476 if (IsRotate && fullMask &&
477 N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
479 Select(Tmp, N->getOperand(0).getOperand(0));
480 return CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Tmp,
481 getI32Imm(SH), getI32Imm(0), getI32Imm(31));
483 SDOperand Tmp1, Tmp2;
484 Select(Tmp1, ((Op0IsAND && fullMask) ? Op0.getOperand(0) : Op0));
485 Select(Tmp2, (IsAndWithShiftOp ? Op1.getOperand(0).getOperand(0)
486 : Op1.getOperand(0)));
487 return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
488 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
493 /// SelectAddrImm - Returns true if the address N can be represented by
494 /// a base register plus a signed 16-bit displacement [r+imm].
495 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp,
497 // If this can be more profitably realized as r+r, fail.
498 if (SelectAddrIdx(N, Disp, Base))
501 if (N.getOpcode() == ISD::ADD) {
503 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
504 Disp = getI32Imm(imm & 0xFFFF);
505 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
506 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
508 Base = N.getOperand(0);
510 return true; // [r+i]
511 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
512 // Match LOAD (ADD (X, Lo(G))).
513 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
514 && "Cannot handle constant offsets yet!");
515 Disp = N.getOperand(1).getOperand(0); // The global address.
516 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
517 Disp.getOpcode() == ISD::TargetConstantPool);
518 Base = N.getOperand(0);
519 return true; // [&g+r]
521 } else if (N.getOpcode() == ISD::OR) {
523 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
524 // If this is an or of disjoint bitfields, we can codegen this as an add
525 // (for better address arithmetic) if the LHS and RHS of the OR are
526 // provably disjoint.
527 uint64_t LHSKnownZero, LHSKnownOne;
528 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
529 LHSKnownZero, LHSKnownOne);
530 if ((LHSKnownZero|~imm) == ~0U) {
531 // If all of the bits are known zero on the LHS or RHS, the add won't
533 Base = N.getOperand(0);
534 Disp = getI32Imm(imm & 0xFFFF);
540 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
541 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
544 return true; // [r+0]
547 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
548 /// represented as an indexed [r+r] operation. Returns false if it can
549 /// be represented by [r+imm], which are preferred.
550 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base,
553 if (N.getOpcode() == ISD::ADD) {
554 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
556 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
559 Base = N.getOperand(0);
560 Index = N.getOperand(1);
562 } else if (N.getOpcode() == ISD::OR) {
563 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
564 return false; // r+i can fold it if we can.
566 // If this is an or of disjoint bitfields, we can codegen this as an add
567 // (for better address arithmetic) if the LHS and RHS of the OR are provably
569 uint64_t LHSKnownZero, LHSKnownOne;
570 uint64_t RHSKnownZero, RHSKnownOne;
571 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
572 LHSKnownZero, LHSKnownOne);
575 PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
576 RHSKnownZero, RHSKnownOne);
577 // If all of the bits are known zero on the LHS or RHS, the add won't
579 if ((LHSKnownZero | RHSKnownZero) == ~0U) {
580 Base = N.getOperand(0);
581 Index = N.getOperand(1);
590 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
591 /// represented as an indexed [r+r] operation.
592 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base,
594 // Check to see if we can easily represent this as an [r+r] address. This
595 // will fail if it thinks that the address is more profitably represented as
596 // reg+imm, e.g. where imm = 0.
597 if (!SelectAddrIdx(N, Base, Index)) {
598 // Nope, do it the hard way.
599 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
605 /// SelectCC - Select a comparison of the specified values with the specified
606 /// condition code, returning the CR# of the expression.
607 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
609 // Always select the LHS.
612 // Use U to determine whether the SETCC immediate range is signed or not.
613 if (MVT::isInteger(LHS.getValueType())) {
614 bool U = ISD::isUnsignedIntSetCC(CC);
616 if (isIntImmediate(RHS, Imm) &&
617 ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
618 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
619 MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
621 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
623 } else if (LHS.getValueType() == MVT::f32) {
625 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
628 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
632 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
634 static unsigned getBCCForSetCC(ISD::CondCode CC) {
636 default: assert(0 && "Unknown condition!"); abort();
637 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
638 case ISD::SETEQ: return PPC::BEQ;
639 case ISD::SETONE: // FIXME: This is incorrect see PR642.
640 case ISD::SETNE: return PPC::BNE;
641 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
643 case ISD::SETLT: return PPC::BLT;
644 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
646 case ISD::SETLE: return PPC::BLE;
647 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
649 case ISD::SETGT: return PPC::BGT;
650 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
652 case ISD::SETGE: return PPC::BGE;
654 case ISD::SETO: return PPC::BUN;
655 case ISD::SETUO: return PPC::BNU;
660 /// getCRIdxForSetCC - Return the index of the condition register field
661 /// associated with the SetCC condition, and whether or not the field is
662 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
663 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
665 default: assert(0 && "Unknown condition!"); abort();
666 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
668 case ISD::SETLT: Inv = false; return 0;
669 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
671 case ISD::SETGE: Inv = true; return 0;
672 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
674 case ISD::SETGT: Inv = false; return 1;
675 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
677 case ISD::SETLE: Inv = true; return 1;
678 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
679 case ISD::SETEQ: Inv = false; return 2;
680 case ISD::SETONE: // FIXME: This is incorrect see PR642.
681 case ISD::SETNE: Inv = true; return 2;
682 case ISD::SETO: Inv = true; return 3;
683 case ISD::SETUO: Inv = false; return 3;
688 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
691 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
692 if (isIntImmediate(N->getOperand(1), Imm)) {
693 // We can codegen setcc op, imm very efficiently compared to a brcond.
694 // Check for those cases here.
698 Select(Op, N->getOperand(0));
702 Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
703 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
704 getI32Imm(5), getI32Imm(31));
707 SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
708 Op, getI32Imm(~0U)), 0);
709 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
713 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
714 getI32Imm(31), getI32Imm(31));
717 SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
718 T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
719 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
720 getI32Imm(31), getI32Imm(31));
723 } else if (Imm == ~0U) { // setcc op, -1
725 Select(Op, N->getOperand(0));
729 Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
730 Op, getI32Imm(1)), 0);
731 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
732 SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
736 Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
737 SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
739 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0), Op,
743 SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
745 SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
747 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
748 getI32Imm(31), getI32Imm(31));
751 Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
752 getI32Imm(1), getI32Imm(31),
754 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
760 unsigned Idx = getCRIdxForSetCC(CC, Inv);
761 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
764 // Force the ccreg into CR7.
765 SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
767 SDOperand InFlag(0, 0); // Null incoming flag value.
768 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg,
771 if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
772 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
775 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
778 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
779 getI32Imm((32-(3-Idx)) & 31),
780 getI32Imm(31), getI32Imm(31));
783 SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
784 getI32Imm((32-(3-Idx)) & 31),
785 getI32Imm(31),getI32Imm(31)), 0);
786 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
790 /// isCallCompatibleAddress - Return true if the specified 32-bit value is
791 /// representable in the immediate field of a Bx instruction.
792 static bool isCallCompatibleAddress(ConstantSDNode *C) {
793 int Addr = C->getValue();
794 if (Addr & 3) return false; // Low 2 bits are implicitly zero.
795 return (Addr << 6 >> 6) == Addr; // Top 6 bits have to be sext of immediate.
798 SDOperand PPCDAGToDAGISel::SelectCALL(SDOperand Op) {
801 Select(Chain, N->getOperand(0));
804 std::vector<SDOperand> CallOperands;
806 if (GlobalAddressSDNode *GASD =
807 dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
808 CallOpcode = PPC::BL;
809 CallOperands.push_back(N->getOperand(1));
810 } else if (ExternalSymbolSDNode *ESSDN =
811 dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
812 CallOpcode = PPC::BL;
813 CallOperands.push_back(N->getOperand(1));
814 } else if (isa<ConstantSDNode>(N->getOperand(1)) &&
815 isCallCompatibleAddress(cast<ConstantSDNode>(N->getOperand(1)))) {
816 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
817 CallOpcode = PPC::BLA;
818 CallOperands.push_back(getI32Imm((int)C->getValue() >> 2));
820 // Copy the callee address into the CTR register.
822 Select(Callee, N->getOperand(1));
823 Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee,
826 // Copy the callee address into R12 on darwin.
827 SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
828 Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
830 CallOperands.push_back(R12);
831 CallOpcode = PPC::BCTRL;
834 unsigned GPR_idx = 0, FPR_idx = 0;
835 static const unsigned GPR[] = {
836 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
837 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
839 static const unsigned FPR[] = {
840 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
841 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
844 SDOperand InFlag; // Null incoming flag value.
846 for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
847 unsigned DestReg = 0;
848 MVT::ValueType RegTy = N->getOperand(i).getValueType();
849 if (RegTy == MVT::i32) {
850 assert(GPR_idx < 8 && "Too many int args");
851 DestReg = GPR[GPR_idx++];
853 assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
854 "Unpromoted integer arg?");
855 assert(FPR_idx < 13 && "Too many fp args");
856 DestReg = FPR[FPR_idx++];
859 if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
861 Select(Val, N->getOperand(i));
862 Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
863 InFlag = Chain.getValue(1);
864 CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
868 // Finally, once everything is in registers to pass to the call, emit the
871 CallOperands.push_back(InFlag); // Strong dep on register copies.
873 CallOperands.push_back(Chain); // Weak dep on whatever occurs before
874 Chain = SDOperand(CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
877 std::vector<SDOperand> CallResults;
879 // If the call has results, copy the values out of the ret val registers.
880 switch (N->getValueType(0)) {
881 default: assert(0 && "Unexpected ret value!");
882 case MVT::Other: break;
884 if (N->getValueType(1) == MVT::i32) {
885 Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32,
886 Chain.getValue(1)).getValue(1);
887 CallResults.push_back(Chain.getValue(0));
888 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
889 Chain.getValue(2)).getValue(1);
890 CallResults.push_back(Chain.getValue(0));
892 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
893 Chain.getValue(1)).getValue(1);
894 CallResults.push_back(Chain.getValue(0));
899 Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
900 Chain.getValue(1)).getValue(1);
901 CallResults.push_back(Chain.getValue(0));
905 CallResults.push_back(Chain);
906 for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
907 CodeGenMap[Op.getValue(i)] = CallResults[i];
908 return CallResults[Op.ResNo];
911 // Select - Convert the specified operand from a target-independent to a
912 // target-specific node if it hasn't already been changed.
913 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
915 if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
916 N->getOpcode() < PPCISD::FIRST_NUMBER) {
918 return; // Already selected.
921 // If this has already been converted, use it.
922 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
923 if (CGMI != CodeGenMap.end()) {
924 Result = CGMI->second;
928 switch (N->getOpcode()) {
931 Result = SelectSETCC(Op);
934 Result = SelectCALL(Op);
936 case PPCISD::GlobalBaseReg:
937 Result = getGlobalBaseReg();
940 case ISD::FrameIndex: {
941 int FI = cast<FrameIndexSDNode>(N)->getIndex();
942 if (N->hasOneUse()) {
943 Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
944 CurDAG->getTargetFrameIndex(FI, MVT::i32),
948 Result = CodeGenMap[Op] =
949 SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
950 CurDAG->getTargetFrameIndex(FI, MVT::i32),
955 // FIXME: since this depends on the setting of the carry flag from the srawi
956 // we should really be making notes about that for the scheduler.
957 // FIXME: It sure would be nice if we could cheaply recognize the
958 // srl/add/sra pattern the dag combiner will generate for this as
959 // sra/addze rather than having to handle sdiv ourselves. oh well.
961 if (isIntImmediate(N->getOperand(1), Imm)) {
963 Select(N0, N->getOperand(0));
964 if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
966 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
967 N0, getI32Imm(Log2_32(Imm)));
968 Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
969 SDOperand(Op, 0), SDOperand(Op, 1));
970 } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
972 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
973 N0, getI32Imm(Log2_32(-Imm)));
975 SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
976 SDOperand(Op, 0), SDOperand(Op, 1)),
978 Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
983 // Other cases are autogenerated.
988 // If this is an and of a value rotated between 0 and 31 bits and then and'd
989 // with a mask, emit rlwinm
990 if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
991 isShiftedMask_32(~Imm))) {
994 if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
995 Select(Val, N->getOperand(0).getOperand(0));
996 } else if (Imm == 0) {
997 // AND X, 0 -> 0, not "rlwinm 32".
998 Select(Result, N->getOperand(1));
1001 Select(Val, N->getOperand(0));
1002 isRunOfOnes(Imm, MB, ME);
1005 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
1006 getI32Imm(SH), getI32Imm(MB),
1010 // ISD::OR doesn't get all the bitfield insertion fun.
1011 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1012 if (isIntImmediate(N->getOperand(1), Imm) &&
1013 N->getOperand(0).getOpcode() == ISD::OR &&
1014 isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
1017 if (isRunOfOnes(Imm, MB, ME)) {
1018 SDOperand Tmp1, Tmp2;
1019 Select(Tmp1, N->getOperand(0).getOperand(0));
1020 Select(Tmp2, N->getOperand(0).getOperand(1));
1021 Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1023 getI32Imm(0), getI32Imm(MB),
1029 // Other cases are autogenerated.
1033 if (SDNode *I = SelectBitfieldInsert(N)) {
1034 Result = CodeGenMap[Op] = SDOperand(I, 0);
1038 // Other cases are autogenerated.
1041 unsigned Imm, SH, MB, ME;
1042 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1043 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1045 Select(Val, N->getOperand(0).getOperand(0));
1046 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1047 Val, getI32Imm(SH), getI32Imm(MB),
1052 // Other cases are autogenerated.
1056 unsigned Imm, SH, MB, ME;
1057 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1058 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1060 Select(Val, N->getOperand(0).getOperand(0));
1061 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1062 Val, getI32Imm(SH & 0x1F), getI32Imm(MB),
1067 // Other cases are autogenerated.
1070 case ISD::SELECT_CC: {
1071 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1073 // handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
1074 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1075 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1076 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1077 if (N1C->isNullValue() && N3C->isNullValue() &&
1078 N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1080 Select(LHS, N->getOperand(0));
1082 CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1083 LHS, getI32Imm(~0U));
1084 Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1085 SDOperand(Tmp, 0), LHS,
1090 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1091 unsigned BROpc = getBCCForSetCC(CC);
1093 bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1094 unsigned SelectCCOp;
1095 if (MVT::isInteger(N->getValueType(0)))
1096 SelectCCOp = PPC::SELECT_CC_Int;
1097 else if (N->getValueType(0) == MVT::f32)
1098 SelectCCOp = PPC::SELECT_CC_F4;
1100 SelectCCOp = PPC::SELECT_CC_F8;
1102 Select(N2, N->getOperand(2));
1103 Select(N3, N->getOperand(3));
1104 Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1105 N2, N3, getI32Imm(BROpc));
1110 Select(Chain, N->getOperand(0));
1111 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1112 SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1113 Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other,
1114 CondCode, getI32Imm(getBCCForSetCC(CC)),
1115 N->getOperand(4), Chain);
1120 SelectCode(Result, Op);
1124 /// createPPCISelDag - This pass converts a legalized DAG into a
1125 /// PowerPC-specific DAG, ready for instruction scheduling.
1127 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1128 return new PPCDAGToDAGISel(TM);