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);
538 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
539 // Loading from a constant address.
540 int Addr = (int)CN->getValue();
542 // If this address fits entirely in a 16-bit sext immediate field, codegen
544 if (Addr == (short)Addr) {
545 Disp = getI32Imm(Addr);
546 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
550 // Otherwise, break this down into an LIS + disp.
551 Disp = getI32Imm((short)Addr);
552 Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
557 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
558 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
561 return true; // [r+0]
564 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
565 /// represented as an indexed [r+r] operation. Returns false if it can
566 /// be represented by [r+imm], which are preferred.
567 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base,
570 if (N.getOpcode() == ISD::ADD) {
571 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
573 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
576 Base = N.getOperand(0);
577 Index = N.getOperand(1);
579 } else if (N.getOpcode() == ISD::OR) {
580 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
581 return false; // r+i can fold it if we can.
583 // If this is an or of disjoint bitfields, we can codegen this as an add
584 // (for better address arithmetic) if the LHS and RHS of the OR are provably
586 uint64_t LHSKnownZero, LHSKnownOne;
587 uint64_t RHSKnownZero, RHSKnownOne;
588 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
589 LHSKnownZero, LHSKnownOne);
592 PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
593 RHSKnownZero, RHSKnownOne);
594 // If all of the bits are known zero on the LHS or RHS, the add won't
596 if ((LHSKnownZero | RHSKnownZero) == ~0U) {
597 Base = N.getOperand(0);
598 Index = N.getOperand(1);
607 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
608 /// represented as an indexed [r+r] operation.
609 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base,
611 // Check to see if we can easily represent this as an [r+r] address. This
612 // will fail if it thinks that the address is more profitably represented as
613 // reg+imm, e.g. where imm = 0.
614 if (!SelectAddrIdx(N, Base, Index)) {
615 // Nope, do it the hard way.
616 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
622 /// SelectCC - Select a comparison of the specified values with the specified
623 /// condition code, returning the CR# of the expression.
624 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
626 // Always select the LHS.
629 // Use U to determine whether the SETCC immediate range is signed or not.
630 if (MVT::isInteger(LHS.getValueType())) {
631 bool U = ISD::isUnsignedIntSetCC(CC);
633 if (isIntImmediate(RHS, Imm) &&
634 ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
635 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
636 MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
638 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
640 } else if (LHS.getValueType() == MVT::f32) {
642 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
645 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
649 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
651 static unsigned getBCCForSetCC(ISD::CondCode CC) {
653 default: assert(0 && "Unknown condition!"); abort();
654 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
655 case ISD::SETEQ: return PPC::BEQ;
656 case ISD::SETONE: // FIXME: This is incorrect see PR642.
657 case ISD::SETNE: return PPC::BNE;
658 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
660 case ISD::SETLT: return PPC::BLT;
661 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
663 case ISD::SETLE: return PPC::BLE;
664 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
666 case ISD::SETGT: return PPC::BGT;
667 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
669 case ISD::SETGE: return PPC::BGE;
671 case ISD::SETO: return PPC::BUN;
672 case ISD::SETUO: return PPC::BNU;
677 /// getCRIdxForSetCC - Return the index of the condition register field
678 /// associated with the SetCC condition, and whether or not the field is
679 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
680 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
682 default: assert(0 && "Unknown condition!"); abort();
683 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
685 case ISD::SETLT: Inv = false; return 0;
686 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
688 case ISD::SETGE: Inv = true; return 0;
689 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
691 case ISD::SETGT: Inv = false; return 1;
692 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
694 case ISD::SETLE: Inv = true; return 1;
695 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
696 case ISD::SETEQ: Inv = false; return 2;
697 case ISD::SETONE: // FIXME: This is incorrect see PR642.
698 case ISD::SETNE: Inv = true; return 2;
699 case ISD::SETO: Inv = true; return 3;
700 case ISD::SETUO: Inv = false; return 3;
705 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
708 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
709 if (isIntImmediate(N->getOperand(1), Imm)) {
710 // We can codegen setcc op, imm very efficiently compared to a brcond.
711 // Check for those cases here.
715 Select(Op, N->getOperand(0));
719 Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
720 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
721 getI32Imm(5), getI32Imm(31));
724 SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
725 Op, getI32Imm(~0U)), 0);
726 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
730 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
731 getI32Imm(31), getI32Imm(31));
734 SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
735 T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
736 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
737 getI32Imm(31), getI32Imm(31));
740 } else if (Imm == ~0U) { // setcc op, -1
742 Select(Op, N->getOperand(0));
746 Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
747 Op, getI32Imm(1)), 0);
748 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
749 SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
753 Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
754 SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
756 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0), Op,
760 SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
762 SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
764 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
765 getI32Imm(31), getI32Imm(31));
768 Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
769 getI32Imm(1), getI32Imm(31),
771 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
777 unsigned Idx = getCRIdxForSetCC(CC, Inv);
778 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
781 // Force the ccreg into CR7.
782 SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
784 SDOperand InFlag(0, 0); // Null incoming flag value.
785 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg,
788 if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
789 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
792 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
795 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
796 getI32Imm((32-(3-Idx)) & 31),
797 getI32Imm(31), getI32Imm(31));
800 SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
801 getI32Imm((32-(3-Idx)) & 31),
802 getI32Imm(31),getI32Imm(31)), 0);
803 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
807 /// isCallCompatibleAddress - Return true if the specified 32-bit value is
808 /// representable in the immediate field of a Bx instruction.
809 static bool isCallCompatibleAddress(ConstantSDNode *C) {
810 int Addr = C->getValue();
811 if (Addr & 3) return false; // Low 2 bits are implicitly zero.
812 return (Addr << 6 >> 6) == Addr; // Top 6 bits have to be sext of immediate.
815 SDOperand PPCDAGToDAGISel::SelectCALL(SDOperand Op) {
818 Select(Chain, N->getOperand(0));
821 std::vector<SDOperand> CallOperands;
823 if (GlobalAddressSDNode *GASD =
824 dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
825 CallOpcode = PPC::BL;
826 CallOperands.push_back(N->getOperand(1));
827 } else if (ExternalSymbolSDNode *ESSDN =
828 dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
829 CallOpcode = PPC::BL;
830 CallOperands.push_back(N->getOperand(1));
831 } else if (isa<ConstantSDNode>(N->getOperand(1)) &&
832 isCallCompatibleAddress(cast<ConstantSDNode>(N->getOperand(1)))) {
833 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
834 CallOpcode = PPC::BLA;
835 CallOperands.push_back(getI32Imm((int)C->getValue() >> 2));
837 // Copy the callee address into the CTR register.
839 Select(Callee, N->getOperand(1));
840 Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee,
843 // Copy the callee address into R12 on darwin.
844 SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
845 Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
847 CallOperands.push_back(R12);
848 CallOpcode = PPC::BCTRL;
851 unsigned GPR_idx = 0, FPR_idx = 0;
852 static const unsigned GPR[] = {
853 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
854 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
856 static const unsigned FPR[] = {
857 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
858 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
861 SDOperand InFlag; // Null incoming flag value.
863 for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
864 unsigned DestReg = 0;
865 MVT::ValueType RegTy = N->getOperand(i).getValueType();
866 if (RegTy == MVT::i32) {
867 assert(GPR_idx < 8 && "Too many int args");
868 DestReg = GPR[GPR_idx++];
870 assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
871 "Unpromoted integer arg?");
872 assert(FPR_idx < 13 && "Too many fp args");
873 DestReg = FPR[FPR_idx++];
876 if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
878 Select(Val, N->getOperand(i));
879 Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
880 InFlag = Chain.getValue(1);
881 CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
885 // Finally, once everything is in registers to pass to the call, emit the
888 CallOperands.push_back(InFlag); // Strong dep on register copies.
890 CallOperands.push_back(Chain); // Weak dep on whatever occurs before
891 Chain = SDOperand(CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
894 std::vector<SDOperand> CallResults;
896 // If the call has results, copy the values out of the ret val registers.
897 switch (N->getValueType(0)) {
898 default: assert(0 && "Unexpected ret value!");
899 case MVT::Other: break;
901 if (N->getValueType(1) == MVT::i32) {
902 Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32,
903 Chain.getValue(1)).getValue(1);
904 CallResults.push_back(Chain.getValue(0));
905 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
906 Chain.getValue(2)).getValue(1);
907 CallResults.push_back(Chain.getValue(0));
909 Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
910 Chain.getValue(1)).getValue(1);
911 CallResults.push_back(Chain.getValue(0));
916 Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
917 Chain.getValue(1)).getValue(1);
918 CallResults.push_back(Chain.getValue(0));
922 CallResults.push_back(Chain);
923 for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
924 CodeGenMap[Op.getValue(i)] = CallResults[i];
925 return CallResults[Op.ResNo];
928 // Select - Convert the specified operand from a target-independent to a
929 // target-specific node if it hasn't already been changed.
930 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
932 if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
933 N->getOpcode() < PPCISD::FIRST_NUMBER) {
935 return; // Already selected.
938 // If this has already been converted, use it.
939 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
940 if (CGMI != CodeGenMap.end()) {
941 Result = CGMI->second;
945 switch (N->getOpcode()) {
948 Result = SelectSETCC(Op);
951 Result = SelectCALL(Op);
953 case PPCISD::GlobalBaseReg:
954 Result = getGlobalBaseReg();
957 case ISD::FrameIndex: {
958 int FI = cast<FrameIndexSDNode>(N)->getIndex();
959 if (N->hasOneUse()) {
960 Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
961 CurDAG->getTargetFrameIndex(FI, MVT::i32),
965 Result = CodeGenMap[Op] =
966 SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
967 CurDAG->getTargetFrameIndex(FI, MVT::i32),
972 // FIXME: since this depends on the setting of the carry flag from the srawi
973 // we should really be making notes about that for the scheduler.
974 // FIXME: It sure would be nice if we could cheaply recognize the
975 // srl/add/sra pattern the dag combiner will generate for this as
976 // sra/addze rather than having to handle sdiv ourselves. oh well.
978 if (isIntImmediate(N->getOperand(1), Imm)) {
980 Select(N0, N->getOperand(0));
981 if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
983 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
984 N0, getI32Imm(Log2_32(Imm)));
985 Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
986 SDOperand(Op, 0), SDOperand(Op, 1));
987 } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
989 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
990 N0, getI32Imm(Log2_32(-Imm)));
992 SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
993 SDOperand(Op, 0), SDOperand(Op, 1)),
995 Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
1000 // Other cases are autogenerated.
1005 // If this is an and of a value rotated between 0 and 31 bits and then and'd
1006 // with a mask, emit rlwinm
1007 if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
1008 isShiftedMask_32(~Imm))) {
1010 unsigned SH, MB, ME;
1011 if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
1012 Select(Val, N->getOperand(0).getOperand(0));
1013 } else if (Imm == 0) {
1014 // AND X, 0 -> 0, not "rlwinm 32".
1015 Select(Result, N->getOperand(1));
1018 Select(Val, N->getOperand(0));
1019 isRunOfOnes(Imm, MB, ME);
1022 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
1023 getI32Imm(SH), getI32Imm(MB),
1027 // ISD::OR doesn't get all the bitfield insertion fun.
1028 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1029 if (isIntImmediate(N->getOperand(1), Imm) &&
1030 N->getOperand(0).getOpcode() == ISD::OR &&
1031 isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
1034 if (isRunOfOnes(Imm, MB, ME)) {
1035 SDOperand Tmp1, Tmp2;
1036 Select(Tmp1, N->getOperand(0).getOperand(0));
1037 Select(Tmp2, N->getOperand(0).getOperand(1));
1038 Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1040 getI32Imm(0), getI32Imm(MB),
1046 // Other cases are autogenerated.
1050 if (SDNode *I = SelectBitfieldInsert(N)) {
1051 Result = CodeGenMap[Op] = SDOperand(I, 0);
1055 // Other cases are autogenerated.
1058 unsigned Imm, SH, MB, ME;
1059 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1060 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1062 Select(Val, N->getOperand(0).getOperand(0));
1063 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1064 Val, getI32Imm(SH), getI32Imm(MB),
1069 // Other cases are autogenerated.
1073 unsigned Imm, SH, MB, ME;
1074 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1075 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1077 Select(Val, N->getOperand(0).getOperand(0));
1078 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1079 Val, getI32Imm(SH & 0x1F), getI32Imm(MB),
1084 // Other cases are autogenerated.
1087 case ISD::SELECT_CC: {
1088 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1090 // handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
1091 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1092 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1093 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1094 if (N1C->isNullValue() && N3C->isNullValue() &&
1095 N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1097 Select(LHS, N->getOperand(0));
1099 CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1100 LHS, getI32Imm(~0U));
1101 Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1102 SDOperand(Tmp, 0), LHS,
1107 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1108 unsigned BROpc = getBCCForSetCC(CC);
1110 bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1111 unsigned SelectCCOp;
1112 if (MVT::isInteger(N->getValueType(0)))
1113 SelectCCOp = PPC::SELECT_CC_Int;
1114 else if (N->getValueType(0) == MVT::f32)
1115 SelectCCOp = PPC::SELECT_CC_F4;
1117 SelectCCOp = PPC::SELECT_CC_F8;
1119 Select(N2, N->getOperand(2));
1120 Select(N3, N->getOperand(3));
1121 Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1122 N2, N3, getI32Imm(BROpc));
1127 Select(Chain, N->getOperand(0));
1128 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1129 SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1130 Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other,
1131 CondCode, getI32Imm(getBCCForSetCC(CC)),
1132 N->getOperand(4), Chain);
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);