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 {
42 PPCTargetLowering PPCLowering;
43 unsigned GlobalBaseReg;
45 PPCDAGToDAGISel(PPCTargetMachine &TM)
46 : SelectionDAGISel(PPCLowering),
47 PPCLowering(*TM.getTargetLowering()){}
49 virtual bool runOnFunction(Function &Fn) {
50 // Make sure we re-emit a set of the global base reg if necessary
52 return SelectionDAGISel::runOnFunction(Fn);
55 /// getI32Imm - Return a target constant with the specified value, of type
57 inline SDOperand getI32Imm(unsigned Imm) {
58 return CurDAG->getTargetConstant(Imm, MVT::i32);
61 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
62 /// base register. Return the virtual register that holds this value.
63 SDOperand getGlobalBaseReg();
65 // Select - Convert the specified operand from a target-independent to a
66 // target-specific node if it hasn't already been changed.
67 void Select(SDOperand &Result, SDOperand Op);
69 SDNode *SelectBitfieldInsert(SDNode *N);
71 /// SelectCC - Select a comparison of the specified values with the
72 /// specified condition code, returning the CR# of the expression.
73 SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
75 /// SelectAddrImm - Returns true if the address N can be represented by
76 /// a base register plus a signed 16-bit displacement [r+imm].
77 bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
79 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
80 /// represented as an indexed [r+r] operation. Returns false if it can
81 /// be represented by [r+imm], which are preferred.
82 bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
84 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
85 /// represented as an indexed [r+r] operation.
86 bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
88 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
89 /// inline asm expressions.
90 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
92 std::vector<SDOperand> &OutOps,
95 switch (ConstraintCode) {
98 if (!SelectAddrIdx(Op, Op0, Op1))
99 SelectAddrImm(Op, Op0, Op1);
101 case 'o': // offsetable
102 if (!SelectAddrImm(Op, Op0, Op1)) {
103 Select(Op0, Op); // r+0.
107 case 'v': // not offsetable
108 SelectAddrIdxOnly(Op, Op0, Op1);
112 OutOps.push_back(Op0);
113 OutOps.push_back(Op1);
117 SDOperand BuildSDIVSequence(SDNode *N);
118 SDOperand BuildUDIVSequence(SDNode *N);
120 /// InstructionSelectBasicBlock - This callback is invoked by
121 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
122 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
124 virtual const char *getPassName() const {
125 return "PowerPC DAG->DAG Pattern Instruction Selection";
128 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for this
129 /// target when scheduling the DAG.
130 virtual HazardRecognizer *CreateTargetHazardRecognizer() {
131 // Should use subtarget info to pick the right hazard recognizer. For
132 // now, always return a PPC970 recognizer.
133 const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
134 assert(II && "No InstrInfo?");
135 return new PPCHazardRecognizer970(*II);
138 // Include the pieces autogenerated from the target description.
139 #include "PPCGenDAGISel.inc"
142 SDOperand SelectSETCC(SDOperand Op);
143 SDOperand SelectCALL(SDOperand Op);
147 /// InstructionSelectBasicBlock - This callback is invoked by
148 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
149 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
152 // The selection process is inherently a bottom-up recursive process (users
153 // select their uses before themselves). Given infinite stack space, we
154 // could just start selecting on the root and traverse the whole graph. In
155 // practice however, this causes us to run out of stack space on large basic
156 // blocks. To avoid this problem, select the entry node, then all its uses,
157 // iteratively instead of recursively.
158 std::vector<SDOperand> Worklist;
159 Worklist.push_back(DAG.getEntryNode());
161 // Note that we can do this in the PPC target (scanning forward across token
162 // chain edges) because no nodes ever get folded across these edges. On a
163 // target like X86 which supports load/modify/store operations, this would
164 // have to be more careful.
165 while (!Worklist.empty()) {
166 SDOperand Node = Worklist.back();
169 // Chose from the least deep of the top two nodes.
170 if (!Worklist.empty() &&
171 Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
172 std::swap(Worklist.back(), Node);
174 if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
175 Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
176 CodeGenMap.count(Node)) continue;
178 for (SDNode::use_iterator UI = Node.Val->use_begin(),
179 E = Node.Val->use_end(); UI != E; ++UI) {
180 // Scan the values. If this use has a value that is a token chain, add it
183 for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
184 if (User->getValueType(i) == MVT::Other) {
185 Worklist.push_back(SDOperand(User, i));
190 // Finally, legalize this node.
195 // Select target instructions for the DAG.
196 DAG.setRoot(SelectRoot(DAG.getRoot()));
198 DAG.RemoveDeadNodes();
200 // Emit machine code to BB.
201 ScheduleAndEmitDAG(DAG);
203 // Check to see if this function uses vector registers, which means we have to
204 // save and restore the VRSAVE register and update it with the regs we use.
206 // In this case, there will be virtual registers of vector type type created
207 // by the scheduler. Detect them now.
208 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
209 bool HasVectorVReg = false;
210 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
211 e = RegMap->getLastVirtReg(); i != e; ++i)
212 if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
213 HasVectorVReg = true;
217 // If we have a vector register, we want to emit code into the entry and exit
218 // blocks to save and restore the VRSAVE register. We do this here (instead
219 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
221 // 1. This (trivially) reduces the load on the register allocator, by not
222 // having to represent the live range of the VRSAVE register.
223 // 2. This (more significantly) allows us to create a temporary virtual
224 // register to hold the saved VRSAVE value, allowing this temporary to be
225 // register allocated, instead of forcing it to be spilled to the stack.
227 // Create two vregs - one to hold the VRSAVE register that is live-in to the
228 // function and one for the value after having bits or'd into it.
229 unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
230 unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
232 MachineFunction &MF = DAG.getMachineFunction();
233 MachineBasicBlock &EntryBB = *MF.begin();
234 // Emit the following code into the entry block:
235 // InVRSAVE = MFVRSAVE
236 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
237 // MTVRSAVE UpdatedVRSAVE
238 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
239 BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
240 BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
241 BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
243 // Find all return blocks, outputting a restore in each epilog.
244 const TargetInstrInfo &TII = *DAG.getTarget().getInstrInfo();
245 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
246 if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
247 IP = BB->end(); --IP;
249 // Skip over all terminator instructions, which are part of the return
251 MachineBasicBlock::iterator I2 = IP;
252 while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
255 // Emit: MTVRSAVE InVRSave
256 BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
261 /// getGlobalBaseReg - Output the instructions required to put the
262 /// base address to use for accessing globals into a register.
264 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
265 if (!GlobalBaseReg) {
266 // Insert the set of GlobalBaseReg into the first MBB of the function
267 MachineBasicBlock &FirstMBB = BB->getParent()->front();
268 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
269 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
270 // FIXME: when we get to LP64, we will need to create the appropriate
271 // type of register here.
272 GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
273 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
274 BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
276 return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
280 // isIntImmediate - This method tests to see if a constant operand.
281 // If so Imm will receive the 32 bit value.
282 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
283 if (N->getOpcode() == ISD::Constant) {
284 Imm = cast<ConstantSDNode>(N)->getValue();
290 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
291 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
292 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
293 // not, since all 1s are not contiguous.
294 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
295 if (isShiftedMask_32(Val)) {
296 // look for the first non-zero bit
297 MB = CountLeadingZeros_32(Val);
298 // look for the first zero bit after the run of ones
299 ME = CountLeadingZeros_32((Val - 1) ^ Val);
302 Val = ~Val; // invert mask
303 if (isShiftedMask_32(Val)) {
304 // effectively look for the first zero bit
305 ME = CountLeadingZeros_32(Val) - 1;
306 // effectively look for the first one bit after the run of zeros
307 MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
315 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
316 // and mask opcode and mask operation.
317 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
318 unsigned &SH, unsigned &MB, unsigned &ME) {
319 // Don't even go down this path for i64, since different logic will be
320 // necessary for rldicl/rldicr/rldimi.
321 if (N->getValueType(0) != MVT::i32)
325 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
326 unsigned Opcode = N->getOpcode();
327 if (N->getNumOperands() != 2 ||
328 !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
331 if (Opcode == ISD::SHL) {
332 // apply shift left to mask if it comes first
333 if (IsShiftMask) Mask = Mask << Shift;
334 // determine which bits are made indeterminant by shift
335 Indeterminant = ~(0xFFFFFFFFu << Shift);
336 } else if (Opcode == ISD::SRL) {
337 // apply shift right to mask if it comes first
338 if (IsShiftMask) Mask = Mask >> Shift;
339 // determine which bits are made indeterminant by shift
340 Indeterminant = ~(0xFFFFFFFFu >> Shift);
341 // adjust for the left rotate
347 // if the mask doesn't intersect any Indeterminant bits
348 if (Mask && !(Mask & Indeterminant)) {
350 // make sure the mask is still a mask (wrap arounds may not be)
351 return isRunOfOnes(Mask, MB, ME);
356 // isOpcWithIntImmediate - This method tests to see if the node is a specific
357 // opcode and that it has a immediate integer right operand.
358 // If so Imm will receive the 32 bit value.
359 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
360 return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
363 // isIntImmediate - This method tests to see if a constant operand.
364 // If so Imm will receive the 32 bit value.
365 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
366 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
367 Imm = (unsigned)CN->getSignExtended();
373 /// SelectBitfieldInsert - turn an or of two masked values into
374 /// the rotate left word immediate then mask insert (rlwimi) instruction.
375 /// Returns true on success, false if the caller still needs to select OR.
377 /// Patterns matched:
378 /// 1. or shl, and 5. or and, and
379 /// 2. or and, shl 6. or shl, shr
380 /// 3. or shr, and 7. or shr, shl
382 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
383 bool IsRotate = false;
384 unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
387 SDOperand Op0 = N->getOperand(0);
388 SDOperand Op1 = N->getOperand(1);
390 unsigned Op0Opc = Op0.getOpcode();
391 unsigned Op1Opc = Op1.getOpcode();
393 // Verify that we have the correct opcodes
394 if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
396 if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
399 // Generate Mask value for Target
400 if (isIntImmediate(Op0.getOperand(1), Value)) {
402 case ISD::SHL: TgtMask <<= Value; break;
403 case ISD::SRL: TgtMask >>= Value; break;
404 case ISD::AND: TgtMask &= Value; break;
410 // Generate Mask value for Insert
411 if (!isIntImmediate(Op1.getOperand(1), Value))
418 if (Op0Opc == ISD::SRL) IsRotate = true;
424 if (Op0Opc == ISD::SHL) IsRotate = true;
431 // If both of the inputs are ANDs and one of them has a logical shift by
432 // constant as its input, make that AND the inserted value so that we can
433 // combine the shift into the rotate part of the rlwimi instruction
434 bool IsAndWithShiftOp = false;
435 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
436 if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
437 Op1.getOperand(0).getOpcode() == ISD::SRL) {
438 if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
439 SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
440 IsAndWithShiftOp = true;
442 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
443 Op0.getOperand(0).getOpcode() == ISD::SRL) {
444 if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
446 std::swap(TgtMask, InsMask);
447 SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
448 IsAndWithShiftOp = true;
453 // Verify that the Target mask and Insert mask together form a full word mask
454 // and that the Insert mask is a run of set bits (which implies both are runs
455 // of set bits). Given that, Select the arguments and generate the rlwimi
458 if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
459 bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
460 bool Op0IsAND = Op0Opc == ISD::AND;
461 // Check for rotlwi / rotrwi here, a special case of bitfield insert
462 // where both bitfield halves are sourced from the same value.
463 if (IsRotate && fullMask &&
464 N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
466 Select(Tmp, N->getOperand(0).getOperand(0));
467 return CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Tmp,
468 getI32Imm(SH), getI32Imm(0), getI32Imm(31));
470 SDOperand Tmp1, Tmp2;
471 Select(Tmp1, ((Op0IsAND && fullMask) ? Op0.getOperand(0) : Op0));
472 Select(Tmp2, (IsAndWithShiftOp ? Op1.getOperand(0).getOperand(0)
473 : Op1.getOperand(0)));
474 return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
475 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
480 /// SelectAddrImm - Returns true if the address N can be represented by
481 /// a base register plus a signed 16-bit displacement [r+imm].
482 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp,
484 // If this can be more profitably realized as r+r, fail.
485 if (SelectAddrIdx(N, Disp, Base))
488 if (N.getOpcode() == ISD::ADD) {
490 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
491 Disp = getI32Imm(imm & 0xFFFF);
492 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
493 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
495 Base = N.getOperand(0);
497 return true; // [r+i]
498 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
499 // Match LOAD (ADD (X, Lo(G))).
500 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
501 && "Cannot handle constant offsets yet!");
502 Disp = N.getOperand(1).getOperand(0); // The global address.
503 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
504 Disp.getOpcode() == ISD::TargetConstantPool);
505 Base = N.getOperand(0);
506 return true; // [&g+r]
508 } else if (N.getOpcode() == ISD::OR) {
510 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
511 // If this is an or of disjoint bitfields, we can codegen this as an add
512 // (for better address arithmetic) if the LHS and RHS of the OR are
513 // provably disjoint.
514 uint64_t LHSKnownZero, LHSKnownOne;
515 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
516 LHSKnownZero, LHSKnownOne);
517 if ((LHSKnownZero|~imm) == ~0U) {
518 // If all of the bits are known zero on the LHS or RHS, the add won't
520 Base = N.getOperand(0);
521 Disp = getI32Imm(imm & 0xFFFF);
527 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
528 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
531 return true; // [r+0]
534 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
535 /// represented as an indexed [r+r] operation. Returns false if it can
536 /// be represented by [r+imm], which are preferred.
537 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base,
540 if (N.getOpcode() == ISD::ADD) {
541 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
543 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
546 Base = N.getOperand(0);
547 Index = N.getOperand(1);
549 } else if (N.getOpcode() == ISD::OR) {
550 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
551 return false; // r+i can fold it if we can.
553 // If this is an or of disjoint bitfields, we can codegen this as an add
554 // (for better address arithmetic) if the LHS and RHS of the OR are provably
556 uint64_t LHSKnownZero, LHSKnownOne;
557 uint64_t RHSKnownZero, RHSKnownOne;
558 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
559 LHSKnownZero, LHSKnownOne);
562 PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
563 RHSKnownZero, RHSKnownOne);
564 // If all of the bits are known zero on the LHS or RHS, the add won't
566 if ((LHSKnownZero | RHSKnownZero) == ~0U) {
567 Base = N.getOperand(0);
568 Index = N.getOperand(1);
577 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
578 /// represented as an indexed [r+r] operation.
579 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base,
581 // Check to see if we can easily represent this as an [r+r] address. This
582 // will fail if it thinks that the address is more profitably represented as
583 // reg+imm, e.g. where imm = 0.
584 if (!SelectAddrIdx(N, Base, Index)) {
585 // Nope, do it the hard way.
586 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
592 /// SelectCC - Select a comparison of the specified values with the specified
593 /// condition code, returning the CR# of the expression.
594 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
596 // Always select the LHS.
599 // Use U to determine whether the SETCC immediate range is signed or not.
600 if (MVT::isInteger(LHS.getValueType())) {
601 bool U = ISD::isUnsignedIntSetCC(CC);
603 if (isIntImmediate(RHS, Imm) &&
604 ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
605 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
606 MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
608 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
610 } else if (LHS.getValueType() == MVT::f32) {
612 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
615 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
619 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
621 static unsigned getBCCForSetCC(ISD::CondCode CC) {
623 default: assert(0 && "Unknown condition!"); abort();
624 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
625 case ISD::SETEQ: return PPC::BEQ;
626 case ISD::SETONE: // FIXME: This is incorrect see PR642.
627 case ISD::SETNE: return PPC::BNE;
628 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
630 case ISD::SETLT: return PPC::BLT;
631 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
633 case ISD::SETLE: return PPC::BLE;
634 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
636 case ISD::SETGT: return PPC::BGT;
637 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
639 case ISD::SETGE: return PPC::BGE;
641 case ISD::SETO: return PPC::BUN;
642 case ISD::SETUO: return PPC::BNU;
647 /// getCRIdxForSetCC - Return the index of the condition register field
648 /// associated with the SetCC condition, and whether or not the field is
649 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
650 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
652 default: assert(0 && "Unknown condition!"); abort();
653 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
655 case ISD::SETLT: Inv = false; return 0;
656 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
658 case ISD::SETGE: Inv = true; return 0;
659 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
661 case ISD::SETGT: Inv = false; return 1;
662 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
664 case ISD::SETLE: Inv = true; return 1;
665 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
666 case ISD::SETEQ: Inv = false; return 2;
667 case ISD::SETONE: // FIXME: This is incorrect see PR642.
668 case ISD::SETNE: Inv = true; return 2;
669 case ISD::SETO: Inv = true; return 3;
670 case ISD::SETUO: Inv = false; return 3;
675 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
678 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
679 if (isIntImmediate(N->getOperand(1), Imm)) {
680 // We can codegen setcc op, imm very efficiently compared to a brcond.
681 // Check for those cases here.
685 Select(Op, N->getOperand(0));
689 Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
690 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
691 getI32Imm(5), getI32Imm(31));
694 SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
695 Op, getI32Imm(~0U)), 0);
696 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
700 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
701 getI32Imm(31), getI32Imm(31));
704 SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
705 T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
706 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
707 getI32Imm(31), getI32Imm(31));
710 } else if (Imm == ~0U) { // setcc op, -1
712 Select(Op, N->getOperand(0));
716 Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
717 Op, getI32Imm(1)), 0);
718 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
719 SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
723 Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
724 SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
726 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0), Op,
730 SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
732 SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
734 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
735 getI32Imm(31), getI32Imm(31));
738 Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
739 getI32Imm(1), getI32Imm(31),
741 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
747 unsigned Idx = getCRIdxForSetCC(CC, Inv);
748 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
751 // Force the ccreg into CR7.
752 SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
754 SDOperand InFlag(0, 0); // Null incoming flag value.
755 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg,
758 if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
759 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
762 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
765 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
766 getI32Imm((32-(3-Idx)) & 31),
767 getI32Imm(31), getI32Imm(31));
770 SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
771 getI32Imm((32-(3-Idx)) & 31),
772 getI32Imm(31),getI32Imm(31)), 0);
773 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
777 /// isCallCompatibleAddress - Return true if the specified 32-bit value is
778 /// representable in the immediate field of a Bx instruction.
779 static bool isCallCompatibleAddress(ConstantSDNode *C) {
780 int Addr = C->getValue();
781 if (Addr & 3) return false; // Low 2 bits are implicitly zero.
782 return (Addr << 6 >> 6) == Addr; // Top 6 bits have to be sext of immediate.
785 SDOperand PPCDAGToDAGISel::SelectCALL(SDOperand Op) {
788 Select(Chain, N->getOperand(0));
791 std::vector<SDOperand> CallOperands;
793 if (GlobalAddressSDNode *GASD =
794 dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
795 CallOpcode = PPC::BL;
796 CallOperands.push_back(N->getOperand(1));
797 } else if (ExternalSymbolSDNode *ESSDN =
798 dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
799 CallOpcode = PPC::BL;
800 CallOperands.push_back(N->getOperand(1));
801 } else if (isa<ConstantSDNode>(N->getOperand(1)) &&
802 isCallCompatibleAddress(cast<ConstantSDNode>(N->getOperand(1)))) {
803 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
804 CallOpcode = PPC::BLA;
805 CallOperands.push_back(getI32Imm((int)C->getValue() >> 2));
807 // Copy the callee address into the CTR register.
809 Select(Callee, N->getOperand(1));
810 Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee,
813 // Copy the callee address into R12 on darwin.
814 SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
815 Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
817 CallOperands.push_back(R12);
818 CallOpcode = PPC::BCTRL;
821 unsigned GPR_idx = 0, FPR_idx = 0;
822 static const unsigned GPR[] = {
823 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
824 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
826 static const unsigned FPR[] = {
827 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
828 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
831 SDOperand InFlag; // Null incoming flag value.
833 for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
834 unsigned DestReg = 0;
835 MVT::ValueType RegTy = N->getOperand(i).getValueType();
836 if (RegTy == MVT::i32) {
837 assert(GPR_idx < 8 && "Too many int args");
838 DestReg = GPR[GPR_idx++];
840 assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
841 "Unpromoted integer arg?");
842 assert(FPR_idx < 13 && "Too many fp args");
843 DestReg = FPR[FPR_idx++];
846 if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
848 Select(Val, N->getOperand(i));
849 Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
850 InFlag = Chain.getValue(1);
851 CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
855 // Finally, once everything is in registers to pass to the call, emit the
858 CallOperands.push_back(InFlag); // Strong dep on register copies.
860 CallOperands.push_back(Chain); // Weak dep on whatever occurs before
861 Chain = SDOperand(CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
864 std::vector<SDOperand> CallResults;
866 // If the call has results, copy the values out of the ret val registers.
867 switch (N->getValueType(0)) {
868 default: assert(0 && "Unexpected ret value!");
869 case MVT::Other: break;
871 if (N->getValueType(1) == MVT::i32) {
872 Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32,
873 Chain.getValue(1)).getValue(1);
874 CallResults.push_back(Chain.getValue(0));
875 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
876 Chain.getValue(2)).getValue(1);
877 CallResults.push_back(Chain.getValue(0));
879 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
880 Chain.getValue(1)).getValue(1);
881 CallResults.push_back(Chain.getValue(0));
886 Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
887 Chain.getValue(1)).getValue(1);
888 CallResults.push_back(Chain.getValue(0));
892 CallResults.push_back(Chain);
893 for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
894 CodeGenMap[Op.getValue(i)] = CallResults[i];
895 return CallResults[Op.ResNo];
898 // Select - Convert the specified operand from a target-independent to a
899 // target-specific node if it hasn't already been changed.
900 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
902 if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
903 N->getOpcode() < PPCISD::FIRST_NUMBER) {
905 return; // Already selected.
908 // If this has already been converted, use it.
909 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
910 if (CGMI != CodeGenMap.end()) {
911 Result = CGMI->second;
915 switch (N->getOpcode()) {
918 Result = SelectSETCC(Op);
921 Result = SelectCALL(Op);
923 case PPCISD::GlobalBaseReg:
924 Result = getGlobalBaseReg();
927 case ISD::FrameIndex: {
928 int FI = cast<FrameIndexSDNode>(N)->getIndex();
929 if (N->hasOneUse()) {
930 Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
931 CurDAG->getTargetFrameIndex(FI, MVT::i32),
935 Result = CodeGenMap[Op] =
936 SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
937 CurDAG->getTargetFrameIndex(FI, MVT::i32),
942 // FIXME: since this depends on the setting of the carry flag from the srawi
943 // we should really be making notes about that for the scheduler.
944 // FIXME: It sure would be nice if we could cheaply recognize the
945 // srl/add/sra pattern the dag combiner will generate for this as
946 // sra/addze rather than having to handle sdiv ourselves. oh well.
948 if (isIntImmediate(N->getOperand(1), Imm)) {
950 Select(N0, N->getOperand(0));
951 if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
953 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
954 N0, getI32Imm(Log2_32(Imm)));
955 Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
956 SDOperand(Op, 0), SDOperand(Op, 1));
957 } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
959 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
960 N0, getI32Imm(Log2_32(-Imm)));
962 SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
963 SDOperand(Op, 0), SDOperand(Op, 1)),
965 Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
970 // Other cases are autogenerated.
975 // If this is an and of a value rotated between 0 and 31 bits and then and'd
976 // with a mask, emit rlwinm
977 if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
978 isShiftedMask_32(~Imm))) {
981 if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
982 Select(Val, N->getOperand(0).getOperand(0));
983 } else if (Imm == 0) {
984 // AND X, 0 -> 0, not "rlwinm 32".
985 Select(Result, N->getOperand(1));
988 Select(Val, N->getOperand(0));
989 isRunOfOnes(Imm, MB, ME);
992 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
993 getI32Imm(SH), getI32Imm(MB),
997 // ISD::OR doesn't get all the bitfield insertion fun.
998 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
999 if (isIntImmediate(N->getOperand(1), Imm) &&
1000 N->getOperand(0).getOpcode() == ISD::OR &&
1001 isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
1004 if (isRunOfOnes(Imm, MB, ME)) {
1005 SDOperand Tmp1, Tmp2;
1006 Select(Tmp1, N->getOperand(0).getOperand(0));
1007 Select(Tmp2, N->getOperand(0).getOperand(1));
1008 Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1010 getI32Imm(0), getI32Imm(MB),
1016 // Other cases are autogenerated.
1020 if (SDNode *I = SelectBitfieldInsert(N)) {
1021 Result = CodeGenMap[Op] = SDOperand(I, 0);
1025 // Other cases are autogenerated.
1028 unsigned Imm, SH, MB, ME;
1029 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1030 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1032 Select(Val, N->getOperand(0).getOperand(0));
1033 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1034 Val, getI32Imm(SH), getI32Imm(MB),
1039 // Other cases are autogenerated.
1043 unsigned Imm, SH, MB, ME;
1044 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1045 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1047 Select(Val, N->getOperand(0).getOperand(0));
1048 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1049 Val, getI32Imm(SH & 0x1F), getI32Imm(MB),
1054 // Other cases are autogenerated.
1057 case ISD::SELECT_CC: {
1058 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1060 // handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
1061 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1062 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1063 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1064 if (N1C->isNullValue() && N3C->isNullValue() &&
1065 N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1067 Select(LHS, N->getOperand(0));
1069 CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1070 LHS, getI32Imm(~0U));
1071 Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1072 SDOperand(Tmp, 0), LHS,
1077 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1078 unsigned BROpc = getBCCForSetCC(CC);
1080 bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1081 unsigned SelectCCOp;
1082 if (MVT::isInteger(N->getValueType(0)))
1083 SelectCCOp = PPC::SELECT_CC_Int;
1084 else if (N->getValueType(0) == MVT::f32)
1085 SelectCCOp = PPC::SELECT_CC_F4;
1087 SelectCCOp = PPC::SELECT_CC_F8;
1089 Select(N2, N->getOperand(2));
1090 Select(N3, N->getOperand(3));
1091 Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1092 N2, N3, getI32Imm(BROpc));
1096 case ISD::BRTWOWAY_CC: {
1098 Select(Chain, N->getOperand(0));
1099 MachineBasicBlock *Dest =
1100 cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1101 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1102 SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1104 // If this is a two way branch, then grab the fallthrough basic block
1105 // argument and build a PowerPC branch pseudo-op, suitable for long branch
1106 // conversion if necessary by the branch selection pass. Otherwise, emit a
1107 // standard conditional branch.
1108 if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1109 SDOperand CondTrueBlock = N->getOperand(4);
1110 SDOperand CondFalseBlock = N->getOperand(5);
1111 unsigned Opc = getBCCForSetCC(CC);
1113 SDOperand(CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1114 CondCode, getI32Imm(Opc),
1115 CondTrueBlock, CondFalseBlock,
1117 Result = CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, CondFalseBlock, CB);
1119 // Iterate to the next basic block
1120 ilist<MachineBasicBlock>::iterator It = BB;
1123 // If the fallthrough path is off the end of the function, which would be
1124 // undefined behavior, set it to be the same as the current block because
1125 // we have nothing better to set it to, and leaving it alone will cause
1126 // the PowerPC Branch Selection pass to crash.
1127 if (It == BB->getParent()->end()) It = Dest;
1128 Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, CondCode,
1129 getI32Imm(getBCCForSetCC(CC)),
1130 N->getOperand(4), CurDAG->getBasicBlock(It),
1137 SelectCode(Result, Op);
1141 /// createPPCISelDag - This pass converts a legalized DAG into a
1142 /// PowerPC-specific DAG, ready for instruction scheduling.
1144 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1145 return new PPCDAGToDAGISel(TM);