1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SSARegMap.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/ADT/Statistic.h"
42 //===----------------------------------------------------------------------===//
43 // Pattern Matcher Implementation
44 //===----------------------------------------------------------------------===//
47 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
48 /// SDOperand's instead of register numbers for the leaves of the matched
50 struct X86ISelAddressMode {
56 struct { // This is really a union, discriminated by BaseType!
61 bool isRIPRel; // RIP relative?
69 unsigned Align; // CP alignment.
72 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
73 GV(0), CP(0), ES(0), JT(-1), Align(0) {
80 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
83 NumLoadMoved("x86-codegen", "Number of loads moved below TokenFactor");
85 //===--------------------------------------------------------------------===//
86 /// ISel - X86 specific code to select X86 machine instructions for
87 /// SelectionDAG operations.
89 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
90 /// ContainsFPCode - Every instruction we select that uses or defines a FP
91 /// register should set this to true.
94 /// FastISel - Enable fast(er) instruction selection.
98 /// TM - Keep a reference to X86TargetMachine.
100 X86TargetMachine &TM;
102 /// X86Lowering - This object fully describes how to lower LLVM code to an
103 /// X86-specific SelectionDAG.
104 X86TargetLowering X86Lowering;
106 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
107 /// make the right decision when generating code for different targets.
108 const X86Subtarget *Subtarget;
110 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
112 unsigned GlobalBaseReg;
115 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
116 : SelectionDAGISel(X86Lowering),
117 ContainsFPCode(false), FastISel(fast), TM(tm),
118 X86Lowering(*TM.getTargetLowering()),
119 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
121 virtual bool runOnFunction(Function &Fn) {
122 // Make sure we re-emit a set of the global base reg if necessary
124 return SelectionDAGISel::runOnFunction(Fn);
127 virtual const char *getPassName() const {
128 return "X86 DAG->DAG Instruction Selection";
131 /// InstructionSelectBasicBlock - This callback is invoked by
132 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
133 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
135 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
137 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U);
139 // Include the pieces autogenerated from the target description.
140 #include "X86GenDAGISel.inc"
143 SDNode *Select(SDOperand N);
145 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
146 bool SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
147 SDOperand &Index, SDOperand &Disp);
148 bool SelectLEAAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
149 SDOperand &Index, SDOperand &Disp);
150 bool TryFoldLoad(SDOperand P, SDOperand N,
151 SDOperand &Base, SDOperand &Scale,
152 SDOperand &Index, SDOperand &Disp);
153 void InstructionSelectPreprocess(SelectionDAG &DAG);
155 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
156 /// inline asm expressions.
157 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
159 std::vector<SDOperand> &OutOps,
162 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
164 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
165 SDOperand &Scale, SDOperand &Index,
167 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
168 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
170 Scale = getI8Imm(AM.Scale);
172 // These are 32-bit even in 64-bit mode since RIP relative offset
175 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
177 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
179 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
180 else if (AM.JT != -1)
181 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
183 Disp = getI32Imm(AM.Disp);
186 /// getI8Imm - Return a target constant with the specified value, of type
188 inline SDOperand getI8Imm(unsigned Imm) {
189 return CurDAG->getTargetConstant(Imm, MVT::i8);
192 /// getI16Imm - Return a target constant with the specified value, of type
194 inline SDOperand getI16Imm(unsigned Imm) {
195 return CurDAG->getTargetConstant(Imm, MVT::i16);
198 /// getI32Imm - Return a target constant with the specified value, of type
200 inline SDOperand getI32Imm(unsigned Imm) {
201 return CurDAG->getTargetConstant(Imm, MVT::i32);
204 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
205 /// base register. Return the virtual register that holds this value.
206 SDNode *getGlobalBaseReg();
214 static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found,
215 std::set<SDNode *> &Visited) {
217 Use->getNodeId() > Def->getNodeId() ||
218 !Visited.insert(Use).second)
221 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
222 SDNode *N = Use->getOperand(i).Val;
224 findNonImmUse(N, Def, found, Visited);
232 static inline bool isNonImmUse(SDNode* Use, SDNode* Def) {
233 std::set<SDNode *> Visited;
235 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
236 SDNode *N = Use->getOperand(i).Val;
238 findNonImmUse(N, Def, found, Visited);
246 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U) {
247 // If U use can somehow reach N through another path then U can't fold N or
248 // it will create a cycle. e.g. In the following diagram, U can reach N
249 // through X. If N is folded into into U, then X is both a predecessor and
259 return !FastISel && !isNonImmUse(U, N);
262 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
263 /// and move load below the TokenFactor. Replace store's chain operand with
264 /// load's chain result.
265 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
266 SDOperand Store, SDOperand TF) {
267 std::vector<SDOperand> Ops;
268 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
269 if (Load.Val == TF.Val->getOperand(i).Val)
270 Ops.push_back(Load.Val->getOperand(0));
272 Ops.push_back(TF.Val->getOperand(i));
273 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
274 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
275 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
276 Store.getOperand(2), Store.getOperand(3));
279 /// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
280 /// selector to pick more load-modify-store instructions. This is a common
291 /// [TokenFactor] [Op]
298 /// The fact the store's chain operand != load's chain will prevent the
299 /// (store (op (load))) instruction from being selected. We can transform it to:
318 void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
319 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
320 E = DAG.allnodes_end(); I != E; ++I) {
321 if (I->getOpcode() != ISD::STORE)
323 SDOperand Chain = I->getOperand(0);
324 if (Chain.Val->getOpcode() != ISD::TokenFactor)
327 SDOperand N1 = I->getOperand(1);
328 SDOperand N2 = I->getOperand(2);
329 if (MVT::isFloatingPoint(N1.getValueType()) ||
330 MVT::isVector(N1.getValueType()) ||
336 unsigned Opcode = N1.Val->getOpcode();
345 SDOperand N10 = N1.getOperand(0);
346 SDOperand N11 = N1.getOperand(1);
347 if (N10.Val->getOpcode() == ISD::LOAD)
349 else if (N11.Val->getOpcode() == ISD::LOAD) {
353 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
354 (N10.getOperand(1) == N2) &&
355 (N10.Val->getValueType(0) == N1.getValueType());
370 SDOperand N10 = N1.getOperand(0);
371 if (N10.Val->getOpcode() == ISD::LOAD)
372 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
373 (N10.getOperand(1) == N2) &&
374 (N10.Val->getValueType(0) == N1.getValueType());
382 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
388 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
389 /// when it has created a SelectionDAG for us to codegen.
390 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
392 MachineFunction::iterator FirstMBB = BB;
395 InstructionSelectPreprocess(DAG);
397 // Codegen the basic block.
399 DEBUG(std::cerr << "===== Instruction selection begins:\n");
402 DAG.setRoot(SelectRoot(DAG.getRoot()));
404 DEBUG(std::cerr << "===== Instruction selection ends:\n");
407 DAG.RemoveDeadNodes();
409 // Emit machine code to BB.
410 ScheduleAndEmitDAG(DAG);
412 // If we are emitting FP stack code, scan the basic block to determine if this
413 // block defines any FP values. If so, put an FP_REG_KILL instruction before
414 // the terminator of the block.
415 if (!Subtarget->hasSSE2()) {
416 // Note that FP stack instructions *are* used in SSE code when returning
417 // values, but these are not live out of the basic block, so we don't need
418 // an FP_REG_KILL in this case either.
419 bool ContainsFPCode = false;
421 // Scan all of the machine instructions in these MBBs, checking for FP
423 MachineFunction::iterator MBBI = FirstMBB;
425 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
426 !ContainsFPCode && I != E; ++I) {
427 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
428 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
429 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
430 RegMap->getRegClass(I->getOperand(0).getReg()) ==
431 X86::RFPRegisterClass) {
432 ContainsFPCode = true;
437 } while (!ContainsFPCode && &*(MBBI++) != BB);
439 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
440 // a copy of the input value in this block.
441 if (!ContainsFPCode) {
442 // Final check, check LLVM BB's that are successors to the LLVM BB
443 // corresponding to BB for FP PHI nodes.
444 const BasicBlock *LLVMBB = BB->getBasicBlock();
446 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
447 !ContainsFPCode && SI != E; ++SI) {
448 for (BasicBlock::const_iterator II = SI->begin();
449 (PN = dyn_cast<PHINode>(II)); ++II) {
450 if (PN->getType()->isFloatingPoint()) {
451 ContainsFPCode = true;
458 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
459 if (ContainsFPCode) {
460 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
466 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
467 /// the main function.
468 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
469 MachineFrameInfo *MFI) {
470 if (Subtarget->isTargetCygwin())
471 BuildMI(BB, X86::CALLpcrel32, 1).addExternalSymbol("__main");
473 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
474 int CWFrameIdx = MFI->CreateStackObject(2, 2);
475 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
477 // Set the high part to be 64-bit precision.
478 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
479 CWFrameIdx, 1).addImm(2);
481 // Reload the modified control word now.
482 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
485 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
486 // If this is main, emit special code for main.
487 MachineBasicBlock *BB = MF.begin();
488 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
489 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
492 /// MatchAddress - Add the specified node to the specified addressing mode,
493 /// returning true if it cannot be done. This just pattern matches for the
495 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
497 // RIP relative addressing: %rip + 32-bit displacement!
499 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
500 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
501 if (isInt32(AM.Disp + Val)) {
509 int id = N.Val->getNodeId();
510 bool Available = isSelected(id);
512 switch (N.getOpcode()) {
514 case ISD::Constant: {
515 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
516 if (isInt32(AM.Disp + Val)) {
523 case X86ISD::Wrapper:
524 // If value is available in a register both base and index components have
525 // been picked, we can't fit the result available in the register in the
526 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
528 // Can't fit GV or CP in addressing mode for X86-64 medium or large code
529 // model since the displacement field is 32-bit. Ok for small code model.
531 // For X86-64 PIC code, only allow GV / CP + displacement so we can use RIP
532 // relative addressing mode.
533 if ((!Subtarget->is64Bit() || TM.getCodeModel() == CodeModel::Small) &&
534 (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val))) {
535 bool isRIP = Subtarget->is64Bit();
536 if (isRIP && (AM.Base.Reg.Val || AM.Scale > 1 || AM.IndexReg.Val ||
537 AM.BaseType == X86ISelAddressMode::FrameIndexBase))
539 if (ConstantPoolSDNode *CP =
540 dyn_cast<ConstantPoolSDNode>(N.getOperand(0))) {
542 AM.CP = CP->getConstVal();
543 AM.Align = CP->getAlignment();
544 AM.Disp += CP->getOffset();
549 } else if (GlobalAddressSDNode *G =
550 dyn_cast<GlobalAddressSDNode>(N.getOperand(0))) {
552 AM.GV = G->getGlobal();
553 AM.Disp += G->getOffset();
558 } else if (isRoot && isRIP) {
559 if (ExternalSymbolSDNode *S =
560 dyn_cast<ExternalSymbolSDNode>(N.getOperand(0))) {
561 AM.ES = S->getSymbol();
564 } else if (JumpTableSDNode *J =
565 dyn_cast<JumpTableSDNode>(N.getOperand(0))) {
566 AM.JT = J->getIndex();
574 case ISD::FrameIndex:
575 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
576 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
577 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
583 if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
584 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
585 unsigned Val = CN->getValue();
586 if (Val == 1 || Val == 2 || Val == 3) {
588 SDOperand ShVal = N.Val->getOperand(0);
590 // Okay, we know that we have a scale by now. However, if the scaled
591 // value is an add of something and a constant, we can fold the
592 // constant into the disp field here.
593 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
594 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
595 AM.IndexReg = ShVal.Val->getOperand(0);
596 ConstantSDNode *AddVal =
597 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
598 uint64_t Disp = AM.Disp + AddVal->getValue() << Val;
612 // X*[3,5,9] -> X+X*[2,4,8]
614 AM.BaseType == X86ISelAddressMode::RegBase &&
615 AM.Base.Reg.Val == 0 &&
616 AM.IndexReg.Val == 0)
617 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
618 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
619 AM.Scale = unsigned(CN->getValue())-1;
621 SDOperand MulVal = N.Val->getOperand(0);
624 // Okay, we know that we have a scale by now. However, if the scaled
625 // value is an add of something and a constant, we can fold the
626 // constant into the disp field here.
627 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
628 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
629 Reg = MulVal.Val->getOperand(0);
630 ConstantSDNode *AddVal =
631 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
632 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
636 Reg = N.Val->getOperand(0);
638 Reg = N.Val->getOperand(0);
641 AM.IndexReg = AM.Base.Reg = Reg;
648 X86ISelAddressMode Backup = AM;
649 if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
650 !MatchAddress(N.Val->getOperand(1), AM, false))
653 if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
654 !MatchAddress(N.Val->getOperand(0), AM, false))
663 X86ISelAddressMode Backup = AM;
664 // Look for (x << c1) | c2 where (c2 < c1)
665 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(0));
666 if (CN && !MatchAddress(N.Val->getOperand(1), AM, false)) {
667 if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
668 AM.Disp = CN->getValue();
673 CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1));
674 if (CN && !MatchAddress(N.Val->getOperand(0), AM, false)) {
675 if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
676 AM.Disp = CN->getValue();
686 // Is the base register already occupied?
687 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
688 // If so, check to see if the scale index register is set.
689 if (AM.IndexReg.Val == 0) {
695 // Otherwise, we cannot select it.
699 // Default, generate it as a register.
700 AM.BaseType = X86ISelAddressMode::RegBase;
705 /// SelectAddr - returns true if it is able pattern match an addressing mode.
706 /// It returns the operands which make up the maximal addressing mode it can
707 /// match by reference.
708 bool X86DAGToDAGISel::SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
709 SDOperand &Index, SDOperand &Disp) {
710 X86ISelAddressMode AM;
711 if (MatchAddress(N, AM))
714 MVT::ValueType VT = N.getValueType();
715 if (AM.BaseType == X86ISelAddressMode::RegBase) {
716 if (!AM.Base.Reg.Val)
717 AM.Base.Reg = CurDAG->getRegister(0, VT);
720 if (!AM.IndexReg.Val)
721 AM.IndexReg = CurDAG->getRegister(0, VT);
723 getAddressOperands(AM, Base, Scale, Index, Disp);
727 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
728 /// mode it matches can be cost effectively emitted as an LEA instruction.
729 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand N, SDOperand &Base,
731 SDOperand &Index, SDOperand &Disp) {
732 X86ISelAddressMode AM;
733 if (MatchAddress(N, AM))
736 MVT::ValueType VT = N.getValueType();
737 unsigned Complexity = 0;
738 if (AM.BaseType == X86ISelAddressMode::RegBase)
742 AM.Base.Reg = CurDAG->getRegister(0, VT);
743 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
749 AM.IndexReg = CurDAG->getRegister(0, VT);
753 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg
754 else if (AM.Scale > 1)
757 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
758 // to a LEA. This is determined with some expermentation but is by no means
759 // optimal (especially for code size consideration). LEA is nice because of
760 // its three-address nature. Tweak the cost function again when we can run
761 // convertToThreeAddress() at register allocation time.
762 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
763 // For X86-64, we should always use lea to materialize RIP relative
765 if (Subtarget->is64Bit())
771 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
774 if (Complexity > 2) {
775 getAddressOperands(AM, Base, Scale, Index, Disp);
781 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
782 SDOperand &Base, SDOperand &Scale,
783 SDOperand &Index, SDOperand &Disp) {
784 if (N.getOpcode() == ISD::LOAD &&
786 CanBeFoldedBy(N.Val, P.Val))
787 return SelectAddr(N.getOperand(1), Base, Scale, Index, Disp);
791 static bool isRegister0(SDOperand Op) {
792 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op))
793 return (R->getReg() == 0);
797 /// getGlobalBaseReg - Output the instructions required to put the
798 /// base address to use for accessing globals into a register.
800 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
801 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
802 if (!GlobalBaseReg) {
803 // Insert the set of GlobalBaseReg into the first MBB of the function
804 MachineBasicBlock &FirstMBB = BB->getParent()->front();
805 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
806 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
807 // FIXME: when we get to LP64, we will need to create the appropriate
808 // type of register here.
809 GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
810 BuildMI(FirstMBB, MBBI, X86::MovePCtoStack, 0);
811 BuildMI(FirstMBB, MBBI, X86::POP32r, 1, GlobalBaseReg);
813 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
816 static SDNode *FindCallStartFromCall(SDNode *Node) {
817 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
818 assert(Node->getOperand(0).getValueType() == MVT::Other &&
819 "Node doesn't have a token chain argument!");
820 return FindCallStartFromCall(Node->getOperand(0).Val);
823 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
824 SDNode *Node = N.Val;
825 MVT::ValueType NVT = Node->getValueType(0);
827 unsigned Opcode = Node->getOpcode();
830 DEBUG(std::cerr << std::string(Indent, ' '));
831 DEBUG(std::cerr << "Selecting: ");
832 DEBUG(Node->dump(CurDAG));
833 DEBUG(std::cerr << "\n");
837 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
839 DEBUG(std::cerr << std::string(Indent-2, ' '));
840 DEBUG(std::cerr << "== ");
841 DEBUG(Node->dump(CurDAG));
842 DEBUG(std::cerr << "\n");
845 return NULL; // Already selected.
850 case X86ISD::GlobalBaseReg:
851 return getGlobalBaseReg();
854 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
855 // code and is matched first so to prevent it from being turned into
857 // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
858 MVT::ValueType PtrVT = TLI.getPointerTy();
859 SDOperand N0 = N.getOperand(0);
860 SDOperand N1 = N.getOperand(1);
861 if (N.Val->getValueType(0) == PtrVT &&
862 N0.getOpcode() == X86ISD::Wrapper &&
863 N1.getOpcode() == ISD::Constant) {
864 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
866 // TODO: handle ExternalSymbolSDNode.
867 if (GlobalAddressSDNode *G =
868 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
869 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
870 G->getOffset() + Offset);
871 } else if (ConstantPoolSDNode *CP =
872 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
873 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
875 CP->getOffset()+Offset);
879 if (Subtarget->is64Bit()) {
880 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
881 CurDAG->getRegister(0, PtrVT), C };
882 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
884 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
888 // Other cases are handled by auto-generated code.
894 if (Opcode == ISD::MULHU)
896 default: assert(0 && "Unsupported VT!");
897 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
898 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
899 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
900 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
904 default: assert(0 && "Unsupported VT!");
905 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
906 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
907 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
908 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
911 unsigned LoReg, HiReg;
913 default: assert(0 && "Unsupported VT!");
914 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
915 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
916 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
917 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
920 SDOperand N0 = Node->getOperand(0);
921 SDOperand N1 = Node->getOperand(1);
923 bool foldedLoad = false;
924 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
925 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
926 // MULHU and MULHS are commmutative
928 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
930 N0 = Node->getOperand(1);
931 N1 = Node->getOperand(0);
937 Chain = N1.getOperand(0);
938 AddToISelQueue(Chain);
940 Chain = CurDAG->getEntryNode();
942 SDOperand InFlag(0, 0);
944 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
946 InFlag = Chain.getValue(1);
949 AddToISelQueue(Tmp0);
950 AddToISelQueue(Tmp1);
951 AddToISelQueue(Tmp2);
952 AddToISelQueue(Tmp3);
953 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
955 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
956 Chain = SDOperand(CNode, 0);
957 InFlag = SDOperand(CNode, 1);
961 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
964 SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
965 ReplaceUses(N.getValue(0), Result);
967 ReplaceUses(N1.getValue(1), Result.getValue(1));
970 DEBUG(std::cerr << std::string(Indent-2, ' '));
971 DEBUG(std::cerr << "=> ");
972 DEBUG(Result.Val->dump(CurDAG));
973 DEBUG(std::cerr << "\n");
983 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
984 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
987 default: assert(0 && "Unsupported VT!");
988 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
989 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
990 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
991 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
995 default: assert(0 && "Unsupported VT!");
996 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
997 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
998 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
999 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1002 unsigned LoReg, HiReg;
1003 unsigned ClrOpcode, SExtOpcode;
1005 default: assert(0 && "Unsupported VT!");
1007 LoReg = X86::AL; HiReg = X86::AH;
1008 ClrOpcode = X86::MOV8r0;
1009 SExtOpcode = X86::CBW;
1012 LoReg = X86::AX; HiReg = X86::DX;
1013 ClrOpcode = X86::MOV16r0;
1014 SExtOpcode = X86::CWD;
1017 LoReg = X86::EAX; HiReg = X86::EDX;
1018 ClrOpcode = X86::MOV32r0;
1019 SExtOpcode = X86::CDQ;
1022 LoReg = X86::RAX; HiReg = X86::RDX;
1023 ClrOpcode = X86::MOV64r0;
1024 SExtOpcode = X86::CQO;
1028 SDOperand N0 = Node->getOperand(0);
1029 SDOperand N1 = Node->getOperand(1);
1031 bool foldedLoad = false;
1032 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1033 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1036 Chain = N1.getOperand(0);
1037 AddToISelQueue(Chain);
1039 Chain = CurDAG->getEntryNode();
1041 SDOperand InFlag(0, 0);
1043 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1045 InFlag = Chain.getValue(1);
1048 // Sign extend the low part into the high part.
1050 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1052 // Zero out the high part, effectively zero extending the input.
1053 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1054 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(HiReg, NVT),
1056 InFlag = Chain.getValue(1);
1060 AddToISelQueue(Tmp0);
1061 AddToISelQueue(Tmp1);
1062 AddToISelQueue(Tmp2);
1063 AddToISelQueue(Tmp3);
1064 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1066 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1067 Chain = SDOperand(CNode, 0);
1068 InFlag = SDOperand(CNode, 1);
1072 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1075 SDOperand Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg,
1077 ReplaceUses(N.getValue(0), Result);
1079 ReplaceUses(N1.getValue(1), Result.getValue(1));
1082 DEBUG(std::cerr << std::string(Indent-2, ' '));
1083 DEBUG(std::cerr << "=> ");
1084 DEBUG(Result.Val->dump(CurDAG));
1085 DEBUG(std::cerr << "\n");
1092 case ISD::TRUNCATE: {
1093 if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1096 switch (Node->getOperand(0).getValueType()) {
1097 default: assert(0 && "Unknown truncate!");
1099 Opc = X86::MOV16to16_;
1101 Opc2 = X86::TRUNC_16_to8;
1104 Opc = X86::MOV32to32_;
1106 Opc2 = X86::TRUNC_32_to8;
1110 AddToISelQueue(Node->getOperand(0));
1112 SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1113 SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1116 DEBUG(std::cerr << std::string(Indent-2, ' '));
1117 DEBUG(std::cerr << "=> ");
1118 DEBUG(ResNode->dump(CurDAG));
1119 DEBUG(std::cerr << "\n");
1129 SDNode *ResNode = SelectCode(N);
1132 DEBUG(std::cerr << std::string(Indent-2, ' '));
1133 DEBUG(std::cerr << "=> ");
1134 if (ResNode == NULL || ResNode == N.Val)
1135 DEBUG(N.Val->dump(CurDAG));
1137 DEBUG(ResNode->dump(CurDAG));
1138 DEBUG(std::cerr << "\n");
1145 bool X86DAGToDAGISel::
1146 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1147 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1148 SDOperand Op0, Op1, Op2, Op3;
1149 switch (ConstraintCode) {
1150 case 'o': // offsetable ??
1151 case 'v': // not offsetable ??
1152 default: return true;
1154 if (!SelectAddr(Op, Op0, Op1, Op2, Op3))
1159 OutOps.push_back(Op0);
1160 OutOps.push_back(Op1);
1161 OutOps.push_back(Op2);
1162 OutOps.push_back(Op3);
1163 AddToISelQueue(Op0);
1164 AddToISelQueue(Op1);
1165 AddToISelQueue(Op2);
1166 AddToISelQueue(Op3);
1170 /// createX86ISelDag - This pass converts a legalized DAG into a
1171 /// X86-specific DAG, ready for instruction scheduling.
1173 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1174 return new X86DAGToDAGISel(TM, Fast);