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;
44 PPCHazardRecognizer970 PPC970HR;
46 PPCDAGToDAGISel(TargetMachine &TM)
47 : SelectionDAGISel(PPCLowering), PPCLowering(TM) {}
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 /// GetTargetHazardRecognizer - Return the hazard recognizer to use for this
129 /// target when scheduling the DAG.
130 virtual HazardRecognizer &GetTargetHazardRecognizer() {
131 // Should use subtarget info to pick the right hazard recognizer. For
132 // now, always return a PPC970 recognizer.
136 // Include the pieces autogenerated from the target description.
137 #include "PPCGenDAGISel.inc"
140 SDOperand SelectSETCC(SDOperand Op);
141 SDOperand SelectCALL(SDOperand Op);
145 /// InstructionSelectBasicBlock - This callback is invoked by
146 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
147 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
150 // The selection process is inherently a bottom-up recursive process (users
151 // select their uses before themselves). Given infinite stack space, we
152 // could just start selecting on the root and traverse the whole graph. In
153 // practice however, this causes us to run out of stack space on large basic
154 // blocks. To avoid this problem, select the entry node, then all its uses,
155 // iteratively instead of recursively.
156 std::vector<SDOperand> Worklist;
157 Worklist.push_back(DAG.getEntryNode());
159 // Note that we can do this in the PPC target (scanning forward across token
160 // chain edges) because no nodes ever get folded across these edges. On a
161 // target like X86 which supports load/modify/store operations, this would
162 // have to be more careful.
163 while (!Worklist.empty()) {
164 SDOperand Node = Worklist.back();
167 // Chose from the least deep of the top two nodes.
168 if (!Worklist.empty() &&
169 Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
170 std::swap(Worklist.back(), Node);
172 if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
173 Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
174 CodeGenMap.count(Node)) continue;
176 for (SDNode::use_iterator UI = Node.Val->use_begin(),
177 E = Node.Val->use_end(); UI != E; ++UI) {
178 // Scan the values. If this use has a value that is a token chain, add it
181 for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
182 if (User->getValueType(i) == MVT::Other) {
183 Worklist.push_back(SDOperand(User, i));
188 // Finally, legalize this node.
193 // Select target instructions for the DAG.
194 DAG.setRoot(SelectRoot(DAG.getRoot()));
196 DAG.RemoveDeadNodes();
198 // Emit machine code to BB.
199 ScheduleAndEmitDAG(DAG);
202 /// getGlobalBaseReg - Output the instructions required to put the
203 /// base address to use for accessing globals into a register.
205 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
206 if (!GlobalBaseReg) {
207 // Insert the set of GlobalBaseReg into the first MBB of the function
208 MachineBasicBlock &FirstMBB = BB->getParent()->front();
209 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
210 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
211 // FIXME: when we get to LP64, we will need to create the appropriate
212 // type of register here.
213 GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
214 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
215 BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
217 return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
221 // isIntImmediate - This method tests to see if a constant operand.
222 // If so Imm will receive the 32 bit value.
223 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
224 if (N->getOpcode() == ISD::Constant) {
225 Imm = cast<ConstantSDNode>(N)->getValue();
231 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
232 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
233 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
234 // not, since all 1s are not contiguous.
235 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
236 if (isShiftedMask_32(Val)) {
237 // look for the first non-zero bit
238 MB = CountLeadingZeros_32(Val);
239 // look for the first zero bit after the run of ones
240 ME = CountLeadingZeros_32((Val - 1) ^ Val);
243 Val = ~Val; // invert mask
244 if (isShiftedMask_32(Val)) {
245 // effectively look for the first zero bit
246 ME = CountLeadingZeros_32(Val) - 1;
247 // effectively look for the first one bit after the run of zeros
248 MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
256 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
257 // and mask opcode and mask operation.
258 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
259 unsigned &SH, unsigned &MB, unsigned &ME) {
260 // Don't even go down this path for i64, since different logic will be
261 // necessary for rldicl/rldicr/rldimi.
262 if (N->getValueType(0) != MVT::i32)
266 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
267 unsigned Opcode = N->getOpcode();
268 if (N->getNumOperands() != 2 ||
269 !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
272 if (Opcode == ISD::SHL) {
273 // apply shift left to mask if it comes first
274 if (IsShiftMask) Mask = Mask << Shift;
275 // determine which bits are made indeterminant by shift
276 Indeterminant = ~(0xFFFFFFFFu << Shift);
277 } else if (Opcode == ISD::SRL) {
278 // apply shift right to mask if it comes first
279 if (IsShiftMask) Mask = Mask >> Shift;
280 // determine which bits are made indeterminant by shift
281 Indeterminant = ~(0xFFFFFFFFu >> Shift);
282 // adjust for the left rotate
288 // if the mask doesn't intersect any Indeterminant bits
289 if (Mask && !(Mask & Indeterminant)) {
291 // make sure the mask is still a mask (wrap arounds may not be)
292 return isRunOfOnes(Mask, MB, ME);
297 // isOpcWithIntImmediate - This method tests to see if the node is a specific
298 // opcode and that it has a immediate integer right operand.
299 // If so Imm will receive the 32 bit value.
300 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
301 return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
304 // isIntImmediate - This method tests to see if a constant operand.
305 // If so Imm will receive the 32 bit value.
306 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
307 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
308 Imm = (unsigned)CN->getSignExtended();
314 /// SelectBitfieldInsert - turn an or of two masked values into
315 /// the rotate left word immediate then mask insert (rlwimi) instruction.
316 /// Returns true on success, false if the caller still needs to select OR.
318 /// Patterns matched:
319 /// 1. or shl, and 5. or and, and
320 /// 2. or and, shl 6. or shl, shr
321 /// 3. or shr, and 7. or shr, shl
323 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
324 bool IsRotate = false;
325 unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
328 SDOperand Op0 = N->getOperand(0);
329 SDOperand Op1 = N->getOperand(1);
331 unsigned Op0Opc = Op0.getOpcode();
332 unsigned Op1Opc = Op1.getOpcode();
334 // Verify that we have the correct opcodes
335 if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
337 if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
340 // Generate Mask value for Target
341 if (isIntImmediate(Op0.getOperand(1), Value)) {
343 case ISD::SHL: TgtMask <<= Value; break;
344 case ISD::SRL: TgtMask >>= Value; break;
345 case ISD::AND: TgtMask &= Value; break;
351 // Generate Mask value for Insert
352 if (!isIntImmediate(Op1.getOperand(1), Value))
359 if (Op0Opc == ISD::SRL) IsRotate = true;
365 if (Op0Opc == ISD::SHL) IsRotate = true;
372 // If both of the inputs are ANDs and one of them has a logical shift by
373 // constant as its input, make that AND the inserted value so that we can
374 // combine the shift into the rotate part of the rlwimi instruction
375 bool IsAndWithShiftOp = false;
376 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
377 if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
378 Op1.getOperand(0).getOpcode() == ISD::SRL) {
379 if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
380 SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
381 IsAndWithShiftOp = true;
383 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
384 Op0.getOperand(0).getOpcode() == ISD::SRL) {
385 if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
387 std::swap(TgtMask, InsMask);
388 SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
389 IsAndWithShiftOp = true;
394 // Verify that the Target mask and Insert mask together form a full word mask
395 // and that the Insert mask is a run of set bits (which implies both are runs
396 // of set bits). Given that, Select the arguments and generate the rlwimi
399 if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
400 bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
401 bool Op0IsAND = Op0Opc == ISD::AND;
402 // Check for rotlwi / rotrwi here, a special case of bitfield insert
403 // where both bitfield halves are sourced from the same value.
404 if (IsRotate && fullMask &&
405 N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
407 Select(Tmp, N->getOperand(0).getOperand(0));
408 return CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Tmp,
409 getI32Imm(SH), getI32Imm(0), getI32Imm(31));
411 SDOperand Tmp1, Tmp2;
412 Select(Tmp1, ((Op0IsAND && fullMask) ? Op0.getOperand(0) : Op0));
413 Select(Tmp2, (IsAndWithShiftOp ? Op1.getOperand(0).getOperand(0)
414 : Op1.getOperand(0)));
415 return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
416 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
421 /// SelectAddrImm - Returns true if the address N can be represented by
422 /// a base register plus a signed 16-bit displacement [r+imm].
423 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp,
425 // If this can be more profitably realized as r+r, fail.
426 if (SelectAddrIdx(N, Disp, Base))
429 if (N.getOpcode() == ISD::ADD) {
431 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
432 Disp = getI32Imm(imm & 0xFFFF);
433 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
434 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
436 Base = N.getOperand(0);
438 return true; // [r+i]
439 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
440 // Match LOAD (ADD (X, Lo(G))).
441 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
442 && "Cannot handle constant offsets yet!");
443 Disp = N.getOperand(1).getOperand(0); // The global address.
444 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
445 Disp.getOpcode() == ISD::TargetConstantPool);
446 Base = N.getOperand(0);
447 return true; // [&g+r]
449 } else if (N.getOpcode() == ISD::OR) {
451 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
452 // If this is an or of disjoint bitfields, we can codegen this as an add
453 // (for better address arithmetic) if the LHS and RHS of the OR are
454 // provably disjoint.
455 uint64_t LHSKnownZero, LHSKnownOne;
456 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
457 LHSKnownZero, LHSKnownOne);
458 if ((LHSKnownZero|~imm) == ~0U) {
459 // If all of the bits are known zero on the LHS or RHS, the add won't
461 Base = N.getOperand(0);
462 Disp = getI32Imm(imm & 0xFFFF);
468 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
469 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
472 return true; // [r+0]
475 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
476 /// represented as an indexed [r+r] operation. Returns false if it can
477 /// be represented by [r+imm], which are preferred.
478 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base,
481 if (N.getOpcode() == ISD::ADD) {
482 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
484 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
487 Base = N.getOperand(0);
488 Index = N.getOperand(1);
490 } else if (N.getOpcode() == ISD::OR) {
491 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
492 return false; // r+i can fold it if we can.
494 // If this is an or of disjoint bitfields, we can codegen this as an add
495 // (for better address arithmetic) if the LHS and RHS of the OR are provably
497 uint64_t LHSKnownZero, LHSKnownOne;
498 uint64_t RHSKnownZero, RHSKnownOne;
499 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
500 LHSKnownZero, LHSKnownOne);
503 PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
504 RHSKnownZero, RHSKnownOne);
505 // If all of the bits are known zero on the LHS or RHS, the add won't
507 if ((LHSKnownZero | RHSKnownZero) == ~0U) {
508 Base = N.getOperand(0);
509 Index = N.getOperand(1);
518 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
519 /// represented as an indexed [r+r] operation.
520 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base,
522 // Check to see if we can easily represent this as an [r+r] address. This
523 // will fail if it thinks that the address is more profitably represented as
524 // reg+imm, e.g. where imm = 0.
525 if (!SelectAddrIdx(N, Base, Index)) {
526 // Nope, do it the hard way.
527 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
533 /// SelectCC - Select a comparison of the specified values with the specified
534 /// condition code, returning the CR# of the expression.
535 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
537 // Always select the LHS.
540 // Use U to determine whether the SETCC immediate range is signed or not.
541 if (MVT::isInteger(LHS.getValueType())) {
542 bool U = ISD::isUnsignedIntSetCC(CC);
544 if (isIntImmediate(RHS, Imm) &&
545 ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
546 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
547 MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
549 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
551 } else if (LHS.getValueType() == MVT::f32) {
553 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
556 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
560 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
562 static unsigned getBCCForSetCC(ISD::CondCode CC) {
564 default: assert(0 && "Unknown condition!"); abort();
565 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
566 case ISD::SETEQ: return PPC::BEQ;
567 case ISD::SETONE: // FIXME: This is incorrect see PR642.
568 case ISD::SETNE: return PPC::BNE;
569 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
571 case ISD::SETLT: return PPC::BLT;
572 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
574 case ISD::SETLE: return PPC::BLE;
575 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
577 case ISD::SETGT: return PPC::BGT;
578 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
580 case ISD::SETGE: return PPC::BGE;
582 case ISD::SETO: return PPC::BUN;
583 case ISD::SETUO: return PPC::BNU;
588 /// getCRIdxForSetCC - Return the index of the condition register field
589 /// associated with the SetCC condition, and whether or not the field is
590 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
591 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
593 default: assert(0 && "Unknown condition!"); abort();
594 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
596 case ISD::SETLT: Inv = false; return 0;
597 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
599 case ISD::SETGE: Inv = true; return 0;
600 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
602 case ISD::SETGT: Inv = false; return 1;
603 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
605 case ISD::SETLE: Inv = true; return 1;
606 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
607 case ISD::SETEQ: Inv = false; return 2;
608 case ISD::SETONE: // FIXME: This is incorrect see PR642.
609 case ISD::SETNE: Inv = true; return 2;
610 case ISD::SETO: Inv = true; return 3;
611 case ISD::SETUO: Inv = false; return 3;
616 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
619 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
620 if (isIntImmediate(N->getOperand(1), Imm)) {
621 // We can codegen setcc op, imm very efficiently compared to a brcond.
622 // Check for those cases here.
626 Select(Op, N->getOperand(0));
630 Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
631 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
632 getI32Imm(5), getI32Imm(31));
635 SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
636 Op, getI32Imm(~0U)), 0);
637 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
641 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
642 getI32Imm(31), getI32Imm(31));
645 SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
646 T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
647 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
648 getI32Imm(31), getI32Imm(31));
651 } else if (Imm == ~0U) { // setcc op, -1
653 Select(Op, N->getOperand(0));
657 Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
658 Op, getI32Imm(1)), 0);
659 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
660 SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
664 Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
665 SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
667 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0), Op,
671 SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
673 SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
675 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
676 getI32Imm(31), getI32Imm(31));
679 Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
680 getI32Imm(1), getI32Imm(31),
682 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
688 unsigned Idx = getCRIdxForSetCC(CC, Inv);
689 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
692 // Force the ccreg into CR7.
693 SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
695 SDOperand InFlag(0, 0); // Null incoming flag value.
696 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg,
699 if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
700 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
703 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
706 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
707 getI32Imm((32-(3-Idx)) & 31),
708 getI32Imm(31), getI32Imm(31));
711 SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
712 getI32Imm((32-(3-Idx)) & 31),
713 getI32Imm(31),getI32Imm(31)), 0);
714 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
718 /// isCallCompatibleAddress - Return true if the specified 32-bit value is
719 /// representable in the immediate field of a Bx instruction.
720 static bool isCallCompatibleAddress(ConstantSDNode *C) {
721 int Addr = C->getValue();
722 if (Addr & 3) return false; // Low 2 bits are implicitly zero.
723 return (Addr << 6 >> 6) == Addr; // Top 6 bits have to be sext of immediate.
726 SDOperand PPCDAGToDAGISel::SelectCALL(SDOperand Op) {
729 Select(Chain, N->getOperand(0));
732 std::vector<SDOperand> CallOperands;
734 if (GlobalAddressSDNode *GASD =
735 dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
736 CallOpcode = PPC::BL;
737 CallOperands.push_back(N->getOperand(1));
738 } else if (ExternalSymbolSDNode *ESSDN =
739 dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
740 CallOpcode = PPC::BL;
741 CallOperands.push_back(N->getOperand(1));
742 } else if (isa<ConstantSDNode>(N->getOperand(1)) &&
743 isCallCompatibleAddress(cast<ConstantSDNode>(N->getOperand(1)))) {
744 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
745 CallOpcode = PPC::BLA;
746 CallOperands.push_back(getI32Imm((int)C->getValue() >> 2));
748 // Copy the callee address into the CTR register.
750 Select(Callee, N->getOperand(1));
751 Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee,
754 // Copy the callee address into R12 on darwin.
755 SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
756 Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
758 CallOperands.push_back(R12);
759 CallOpcode = PPC::BCTRL;
762 unsigned GPR_idx = 0, FPR_idx = 0;
763 static const unsigned GPR[] = {
764 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
765 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
767 static const unsigned FPR[] = {
768 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
769 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
772 SDOperand InFlag; // Null incoming flag value.
774 for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
775 unsigned DestReg = 0;
776 MVT::ValueType RegTy = N->getOperand(i).getValueType();
777 if (RegTy == MVT::i32) {
778 assert(GPR_idx < 8 && "Too many int args");
779 DestReg = GPR[GPR_idx++];
781 assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
782 "Unpromoted integer arg?");
783 assert(FPR_idx < 13 && "Too many fp args");
784 DestReg = FPR[FPR_idx++];
787 if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
789 Select(Val, N->getOperand(i));
790 Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
791 InFlag = Chain.getValue(1);
792 CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
796 // Finally, once everything is in registers to pass to the call, emit the
799 CallOperands.push_back(InFlag); // Strong dep on register copies.
801 CallOperands.push_back(Chain); // Weak dep on whatever occurs before
802 Chain = SDOperand(CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
805 std::vector<SDOperand> CallResults;
807 // If the call has results, copy the values out of the ret val registers.
808 switch (N->getValueType(0)) {
809 default: assert(0 && "Unexpected ret value!");
810 case MVT::Other: break;
812 if (N->getValueType(1) == MVT::i32) {
813 Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32,
814 Chain.getValue(1)).getValue(1);
815 CallResults.push_back(Chain.getValue(0));
816 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
817 Chain.getValue(2)).getValue(1);
818 CallResults.push_back(Chain.getValue(0));
820 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
821 Chain.getValue(1)).getValue(1);
822 CallResults.push_back(Chain.getValue(0));
827 Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
828 Chain.getValue(1)).getValue(1);
829 CallResults.push_back(Chain.getValue(0));
833 CallResults.push_back(Chain);
834 for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
835 CodeGenMap[Op.getValue(i)] = CallResults[i];
836 return CallResults[Op.ResNo];
839 // Select - Convert the specified operand from a target-independent to a
840 // target-specific node if it hasn't already been changed.
841 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
843 if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
844 N->getOpcode() < PPCISD::FIRST_NUMBER) {
846 return; // Already selected.
849 // If this has already been converted, use it.
850 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
851 if (CGMI != CodeGenMap.end()) {
852 Result = CGMI->second;
856 switch (N->getOpcode()) {
859 Result = SelectSETCC(Op);
862 Result = SelectCALL(Op);
864 case PPCISD::GlobalBaseReg:
865 Result = getGlobalBaseReg();
868 case ISD::FrameIndex: {
869 int FI = cast<FrameIndexSDNode>(N)->getIndex();
870 if (N->hasOneUse()) {
871 Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
872 CurDAG->getTargetFrameIndex(FI, MVT::i32),
876 Result = CodeGenMap[Op] =
877 SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
878 CurDAG->getTargetFrameIndex(FI, MVT::i32),
883 // FIXME: since this depends on the setting of the carry flag from the srawi
884 // we should really be making notes about that for the scheduler.
885 // FIXME: It sure would be nice if we could cheaply recognize the
886 // srl/add/sra pattern the dag combiner will generate for this as
887 // sra/addze rather than having to handle sdiv ourselves. oh well.
889 if (isIntImmediate(N->getOperand(1), Imm)) {
891 Select(N0, N->getOperand(0));
892 if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
894 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
895 N0, getI32Imm(Log2_32(Imm)));
896 Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
897 SDOperand(Op, 0), SDOperand(Op, 1));
898 } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
900 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
901 N0, getI32Imm(Log2_32(-Imm)));
903 SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
904 SDOperand(Op, 0), SDOperand(Op, 1)),
906 Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
911 // Other cases are autogenerated.
916 // If this is an and of a value rotated between 0 and 31 bits and then and'd
917 // with a mask, emit rlwinm
918 if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
919 isShiftedMask_32(~Imm))) {
922 if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
923 Select(Val, N->getOperand(0).getOperand(0));
924 } else if (Imm == 0) {
925 // AND X, 0 -> 0, not "rlwinm 32".
926 Select(Result, N->getOperand(1));
929 Select(Val, N->getOperand(0));
930 isRunOfOnes(Imm, MB, ME);
933 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
934 getI32Imm(SH), getI32Imm(MB),
938 // ISD::OR doesn't get all the bitfield insertion fun.
939 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
940 if (isIntImmediate(N->getOperand(1), Imm) &&
941 N->getOperand(0).getOpcode() == ISD::OR &&
942 isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
945 if (isRunOfOnes(Imm, MB, ME)) {
946 SDOperand Tmp1, Tmp2;
947 Select(Tmp1, N->getOperand(0).getOperand(0));
948 Select(Tmp2, N->getOperand(0).getOperand(1));
949 Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
951 getI32Imm(0), getI32Imm(MB),
957 // Other cases are autogenerated.
961 if (SDNode *I = SelectBitfieldInsert(N)) {
962 Result = CodeGenMap[Op] = SDOperand(I, 0);
966 // Other cases are autogenerated.
969 unsigned Imm, SH, MB, ME;
970 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
971 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
973 Select(Val, N->getOperand(0).getOperand(0));
974 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
975 Val, getI32Imm(SH), getI32Imm(MB),
980 // Other cases are autogenerated.
984 unsigned Imm, SH, MB, ME;
985 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
986 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
988 Select(Val, N->getOperand(0).getOperand(0));
989 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
990 Val, getI32Imm(SH & 0x1F), getI32Imm(MB),
995 // Other cases are autogenerated.
998 case ISD::SELECT_CC: {
999 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1001 // handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
1002 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1003 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1004 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1005 if (N1C->isNullValue() && N3C->isNullValue() &&
1006 N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1008 Select(LHS, N->getOperand(0));
1010 CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1011 LHS, getI32Imm(~0U));
1012 Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1013 SDOperand(Tmp, 0), LHS,
1018 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1019 unsigned BROpc = getBCCForSetCC(CC);
1021 bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1022 unsigned SelectCCOp;
1023 if (MVT::isInteger(N->getValueType(0)))
1024 SelectCCOp = PPC::SELECT_CC_Int;
1025 else if (N->getValueType(0) == MVT::f32)
1026 SelectCCOp = PPC::SELECT_CC_F4;
1028 SelectCCOp = PPC::SELECT_CC_F8;
1030 Select(N2, N->getOperand(2));
1031 Select(N3, N->getOperand(3));
1032 Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1033 N2, N3, getI32Imm(BROpc));
1037 case ISD::BRTWOWAY_CC: {
1039 Select(Chain, N->getOperand(0));
1040 MachineBasicBlock *Dest =
1041 cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1042 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1043 SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1045 // If this is a two way branch, then grab the fallthrough basic block
1046 // argument and build a PowerPC branch pseudo-op, suitable for long branch
1047 // conversion if necessary by the branch selection pass. Otherwise, emit a
1048 // standard conditional branch.
1049 if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1050 SDOperand CondTrueBlock = N->getOperand(4);
1051 SDOperand CondFalseBlock = N->getOperand(5);
1052 unsigned Opc = getBCCForSetCC(CC);
1054 SDOperand(CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1055 CondCode, getI32Imm(Opc),
1056 CondTrueBlock, CondFalseBlock,
1058 Result = CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, CondFalseBlock, CB);
1060 // Iterate to the next basic block
1061 ilist<MachineBasicBlock>::iterator It = BB;
1064 // If the fallthrough path is off the end of the function, which would be
1065 // undefined behavior, set it to be the same as the current block because
1066 // we have nothing better to set it to, and leaving it alone will cause
1067 // the PowerPC Branch Selection pass to crash.
1068 if (It == BB->getParent()->end()) It = Dest;
1069 Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, CondCode,
1070 getI32Imm(getBCCForSetCC(CC)),
1071 N->getOperand(4), CurDAG->getBasicBlock(It),
1078 SelectCode(Result, Op);
1082 /// createPPCISelDag - This pass converts a legalized DAG into a
1083 /// PowerPC-specific DAG, ready for instruction scheduling.
1085 FunctionPass *llvm::createPPCISelDag(TargetMachine &TM) {
1086 return new PPCDAGToDAGISel(TM);