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"
41 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
42 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45 //===----------------------------------------------------------------------===//
46 // Pattern Matcher Implementation
47 //===----------------------------------------------------------------------===//
50 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
51 /// SDOperand's instead of register numbers for the leaves of the matched
53 struct X86ISelAddressMode {
59 struct { // This is really a union, discriminated by BaseType!
64 bool isRIPRel; // RIP relative?
72 unsigned Align; // CP alignment.
75 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
76 GV(0), CP(0), ES(0), JT(-1), Align(0) {
82 //===--------------------------------------------------------------------===//
83 /// ISel - X86 specific code to select X86 machine instructions for
84 /// SelectionDAG operations.
86 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
87 /// ContainsFPCode - Every instruction we select that uses or defines a FP
88 /// register should set this to true.
91 /// FastISel - Enable fast(er) instruction selection.
95 /// TM - Keep a reference to X86TargetMachine.
99 /// X86Lowering - This object fully describes how to lower LLVM code to an
100 /// X86-specific SelectionDAG.
101 X86TargetLowering X86Lowering;
103 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
104 /// make the right decision when generating code for different targets.
105 const X86Subtarget *Subtarget;
107 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
109 unsigned GlobalBaseReg;
112 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
113 : SelectionDAGISel(X86Lowering),
114 ContainsFPCode(false), FastISel(fast), TM(tm),
115 X86Lowering(*TM.getTargetLowering()),
116 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
118 virtual bool runOnFunction(Function &Fn) {
119 // Make sure we re-emit a set of the global base reg if necessary
121 return SelectionDAGISel::runOnFunction(Fn);
124 virtual const char *getPassName() const {
125 return "X86 DAG->DAG Instruction Selection";
128 /// InstructionSelectBasicBlock - This callback is invoked by
129 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
130 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
132 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
134 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root);
136 // Include the pieces autogenerated from the target description.
137 #include "X86GenDAGISel.inc"
140 SDNode *Select(SDOperand N);
142 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
143 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
144 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
145 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
146 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
147 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
148 SDOperand N, SDOperand &Base, SDOperand &Scale,
149 SDOperand &Index, SDOperand &Disp,
150 SDOperand &InChain, SDOperand &OutChain);
151 bool TryFoldLoad(SDOperand P, SDOperand N,
152 SDOperand &Base, SDOperand &Scale,
153 SDOperand &Index, SDOperand &Disp);
154 void InstructionSelectPreprocess(SelectionDAG &DAG);
156 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
157 /// inline asm expressions.
158 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
160 std::vector<SDOperand> &OutOps,
163 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
165 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
166 SDOperand &Scale, SDOperand &Index,
168 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
169 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
171 Scale = getI8Imm(AM.Scale);
173 // These are 32-bit even in 64-bit mode since RIP relative offset
176 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
178 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
180 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
181 else if (AM.JT != -1)
182 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
184 Disp = getI32Imm(AM.Disp);
187 /// getI8Imm - Return a target constant with the specified value, of type
189 inline SDOperand getI8Imm(unsigned Imm) {
190 return CurDAG->getTargetConstant(Imm, MVT::i8);
193 /// getI16Imm - Return a target constant with the specified value, of type
195 inline SDOperand getI16Imm(unsigned Imm) {
196 return CurDAG->getTargetConstant(Imm, MVT::i16);
199 /// getI32Imm - Return a target constant with the specified value, of type
201 inline SDOperand getI32Imm(unsigned Imm) {
202 return CurDAG->getTargetConstant(Imm, MVT::i32);
205 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
206 /// base register. Return the virtual register that holds this value.
207 SDNode *getGlobalBaseReg();
215 static SDNode *findFlagUse(SDNode *N) {
216 unsigned FlagResNo = N->getNumValues()-1;
217 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
219 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
220 SDOperand Op = User->getOperand(i);
221 if (Op.Val == N && Op.ResNo == FlagResNo)
228 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
229 SDNode *Root, SDNode *Skip, bool &found,
230 std::set<SDNode *> &Visited) {
232 Use->getNodeId() > Def->getNodeId() ||
233 !Visited.insert(Use).second)
236 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
237 SDNode *N = Use->getOperand(i).Val;
242 continue; // Immediate use is ok.
244 assert(Use->getOpcode() == ISD::STORE ||
245 Use->getOpcode() == X86ISD::CMP);
251 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
255 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
256 /// be reached. Return true if that's the case. However, ignore direct uses
257 /// by ImmedUse (which would be U in the example illustrated in
258 /// CanBeFoldedBy) and by Root (which can happen in the store case).
259 /// FIXME: to be really generic, we should allow direct use by any node
260 /// that is being folded. But realisticly since we only fold loads which
261 /// have one non-chain use, we only need to watch out for load/op/store
262 /// and load/op/cmp case where the root (store / cmp) may reach the load via
263 /// its chain operand.
264 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
265 SDNode *Skip = NULL) {
266 std::set<SDNode *> Visited;
268 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
273 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) {
274 if (FastISel) return false;
276 // If U use can somehow reach N through another path then U can't fold N or
277 // it will create a cycle. e.g. In the following diagram, U can reach N
278 // through X. If N is folded into into U, then X is both a predecessor and
289 if (isNonImmUse(Root, N, U))
292 // If U produces a flag, then it gets (even more) interesting. Since it
293 // would have been "glued" together with its flag use, we need to check if
306 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
307 // NU), then TF is a predecessor of FU and a successor of NU. But since
308 // NU and FU are flagged together, this effectively creates a cycle.
309 bool HasFlagUse = false;
310 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
311 while ((VT == MVT::Flag && !Root->use_empty())) {
312 SDNode *FU = findFlagUse(Root);
319 VT = Root->getValueType(Root->getNumValues()-1);
323 return !isNonImmUse(Root, N, Root, U);
327 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
328 /// and move load below the TokenFactor. Replace store's chain operand with
329 /// load's chain result.
330 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
331 SDOperand Store, SDOperand TF) {
332 std::vector<SDOperand> Ops;
333 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
334 if (Load.Val == TF.Val->getOperand(i).Val)
335 Ops.push_back(Load.Val->getOperand(0));
337 Ops.push_back(TF.Val->getOperand(i));
338 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
339 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
340 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
341 Store.getOperand(2), Store.getOperand(3));
344 /// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
345 /// selector to pick more load-modify-store instructions. This is a common
356 /// [TokenFactor] [Op]
363 /// The fact the store's chain operand != load's chain will prevent the
364 /// (store (op (load))) instruction from being selected. We can transform it to:
383 void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
384 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
385 E = DAG.allnodes_end(); I != E; ++I) {
386 if (!ISD::isNON_TRUNCStore(I))
388 SDOperand Chain = I->getOperand(0);
389 if (Chain.Val->getOpcode() != ISD::TokenFactor)
392 SDOperand N1 = I->getOperand(1);
393 SDOperand N2 = I->getOperand(2);
394 if (MVT::isFloatingPoint(N1.getValueType()) ||
395 MVT::isVector(N1.getValueType()) ||
401 unsigned Opcode = N1.Val->getOpcode();
410 SDOperand N10 = N1.getOperand(0);
411 SDOperand N11 = N1.getOperand(1);
412 if (ISD::isNON_EXTLoad(N10.Val))
414 else if (ISD::isNON_EXTLoad(N11.Val)) {
418 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
419 (N10.getOperand(1) == N2) &&
420 (N10.Val->getValueType(0) == N1.getValueType());
435 SDOperand N10 = N1.getOperand(0);
436 if (ISD::isNON_EXTLoad(N10.Val))
437 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
438 (N10.getOperand(1) == N2) &&
439 (N10.Val->getValueType(0) == N1.getValueType());
447 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
453 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
454 /// when it has created a SelectionDAG for us to codegen.
455 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
457 MachineFunction::iterator FirstMBB = BB;
460 InstructionSelectPreprocess(DAG);
462 // Codegen the basic block.
464 DOUT << "===== Instruction selection begins:\n";
467 DAG.setRoot(SelectRoot(DAG.getRoot()));
469 DOUT << "===== Instruction selection ends:\n";
472 DAG.RemoveDeadNodes();
474 // Emit machine code to BB.
475 ScheduleAndEmitDAG(DAG);
477 // If we are emitting FP stack code, scan the basic block to determine if this
478 // block defines any FP values. If so, put an FP_REG_KILL instruction before
479 // the terminator of the block.
480 if (!Subtarget->hasSSE2()) {
481 // Note that FP stack instructions *are* used in SSE code when returning
482 // values, but these are not live out of the basic block, so we don't need
483 // an FP_REG_KILL in this case either.
484 bool ContainsFPCode = false;
486 // Scan all of the machine instructions in these MBBs, checking for FP
488 MachineFunction::iterator MBBI = FirstMBB;
490 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
491 !ContainsFPCode && I != E; ++I) {
492 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
493 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
494 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
495 RegMap->getRegClass(I->getOperand(0).getReg()) ==
496 X86::RFPRegisterClass) {
497 ContainsFPCode = true;
502 } while (!ContainsFPCode && &*(MBBI++) != BB);
504 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
505 // a copy of the input value in this block.
506 if (!ContainsFPCode) {
507 // Final check, check LLVM BB's that are successors to the LLVM BB
508 // corresponding to BB for FP PHI nodes.
509 const BasicBlock *LLVMBB = BB->getBasicBlock();
511 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
512 !ContainsFPCode && SI != E; ++SI) {
513 for (BasicBlock::const_iterator II = SI->begin();
514 (PN = dyn_cast<PHINode>(II)); ++II) {
515 if (PN->getType()->isFloatingPoint()) {
516 ContainsFPCode = true;
523 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
524 if (ContainsFPCode) {
525 BuildMI(*BB, BB->getFirstTerminator(),
526 TM.getInstrInfo()->get(X86::FP_REG_KILL));
532 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
533 /// the main function.
534 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
535 MachineFrameInfo *MFI) {
536 const TargetInstrInfo *TII = TM.getInstrInfo();
537 if (Subtarget->isTargetCygMing())
538 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
540 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
541 int CWFrameIdx = MFI->CreateStackObject(2, 2);
542 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
544 // Set the high part to be 64-bit precision.
545 addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
546 CWFrameIdx, 1).addImm(2);
548 // Reload the modified control word now.
549 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
552 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
553 // If this is main, emit special code for main.
554 MachineBasicBlock *BB = MF.begin();
555 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
556 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
559 /// MatchAddress - Add the specified node to the specified addressing mode,
560 /// returning true if it cannot be done. This just pattern matches for the
562 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
564 // RIP relative addressing: %rip + 32-bit displacement!
566 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
567 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
568 if (isInt32(AM.Disp + Val)) {
576 int id = N.Val->getNodeId();
577 bool Available = isSelected(id);
579 switch (N.getOpcode()) {
581 case ISD::Constant: {
582 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
583 if (isInt32(AM.Disp + Val)) {
590 case X86ISD::Wrapper: {
591 bool is64Bit = Subtarget->is64Bit();
592 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
593 if (is64Bit && TM.getCodeModel() != CodeModel::Small)
595 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
597 // If value is available in a register both base and index components have
598 // been picked, we can't fit the result available in the register in the
599 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
600 if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
601 bool isStatic = TM.getRelocationModel() == Reloc::Static;
602 SDOperand N0 = N.getOperand(0);
603 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
604 GlobalValue *GV = G->getGlobal();
605 bool isAbs32 = !is64Bit || isStatic;
606 if (isAbs32 || isRoot) {
608 AM.Disp += G->getOffset();
609 AM.isRIPRel = !isAbs32;
612 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
613 if (!is64Bit || isStatic || isRoot) {
614 AM.CP = CP->getConstVal();
615 AM.Align = CP->getAlignment();
616 AM.Disp += CP->getOffset();
617 AM.isRIPRel = !isStatic;
620 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
621 if (isStatic || isRoot) {
622 AM.ES = S->getSymbol();
623 AM.isRIPRel = !isStatic;
626 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
627 if (isStatic || isRoot) {
628 AM.JT = J->getIndex();
629 AM.isRIPRel = !isStatic;
637 case ISD::FrameIndex:
638 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
639 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
640 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
646 if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
647 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
648 unsigned Val = CN->getValue();
649 if (Val == 1 || Val == 2 || Val == 3) {
651 SDOperand ShVal = N.Val->getOperand(0);
653 // Okay, we know that we have a scale by now. However, if the scaled
654 // value is an add of something and a constant, we can fold the
655 // constant into the disp field here.
656 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
657 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
658 AM.IndexReg = ShVal.Val->getOperand(0);
659 ConstantSDNode *AddVal =
660 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
661 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
675 // X*[3,5,9] -> X+X*[2,4,8]
677 AM.BaseType == X86ISelAddressMode::RegBase &&
678 AM.Base.Reg.Val == 0 &&
679 AM.IndexReg.Val == 0)
680 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
681 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
682 AM.Scale = unsigned(CN->getValue())-1;
684 SDOperand MulVal = N.Val->getOperand(0);
687 // Okay, we know that we have a scale by now. However, if the scaled
688 // value is an add of something and a constant, we can fold the
689 // constant into the disp field here.
690 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
691 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
692 Reg = MulVal.Val->getOperand(0);
693 ConstantSDNode *AddVal =
694 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
695 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
699 Reg = N.Val->getOperand(0);
701 Reg = N.Val->getOperand(0);
704 AM.IndexReg = AM.Base.Reg = Reg;
711 X86ISelAddressMode Backup = AM;
712 if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
713 !MatchAddress(N.Val->getOperand(1), AM, false))
716 if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
717 !MatchAddress(N.Val->getOperand(0), AM, false))
726 X86ISelAddressMode Backup = AM;
727 // Look for (x << c1) | c2 where (c2 < c1)
728 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(0));
729 if (CN && !MatchAddress(N.Val->getOperand(1), AM, false)) {
730 if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
731 AM.Disp = CN->getValue();
736 CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1));
737 if (CN && !MatchAddress(N.Val->getOperand(0), AM, false)) {
738 if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
739 AM.Disp = CN->getValue();
749 // Is the base register already occupied?
750 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
751 // If so, check to see if the scale index register is set.
752 if (AM.IndexReg.Val == 0) {
758 // Otherwise, we cannot select it.
762 // Default, generate it as a register.
763 AM.BaseType = X86ISelAddressMode::RegBase;
768 /// SelectAddr - returns true if it is able pattern match an addressing mode.
769 /// It returns the operands which make up the maximal addressing mode it can
770 /// match by reference.
771 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
772 SDOperand &Scale, SDOperand &Index,
774 X86ISelAddressMode AM;
775 if (MatchAddress(N, AM))
778 MVT::ValueType VT = N.getValueType();
779 if (AM.BaseType == X86ISelAddressMode::RegBase) {
780 if (!AM.Base.Reg.Val)
781 AM.Base.Reg = CurDAG->getRegister(0, VT);
784 if (!AM.IndexReg.Val)
785 AM.IndexReg = CurDAG->getRegister(0, VT);
787 getAddressOperands(AM, Base, Scale, Index, Disp);
791 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
793 static inline bool isZeroNode(SDOperand Elt) {
794 return ((isa<ConstantSDNode>(Elt) &&
795 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
796 (isa<ConstantFPSDNode>(Elt) &&
797 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
801 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
802 /// match a load whose top elements are either undef or zeros. The load flavor
803 /// is derived from the type of N, which is either v4f32 or v2f64.
804 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
805 SDOperand N, SDOperand &Base,
806 SDOperand &Scale, SDOperand &Index,
807 SDOperand &Disp, SDOperand &InChain,
808 SDOperand &OutChain) {
809 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
810 InChain = N.getOperand(0).getValue(1);
811 if (ISD::isNON_EXTLoad(InChain.Val) &&
812 InChain.getValue(0).hasOneUse() &&
814 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
815 LoadSDNode *LD = cast<LoadSDNode>(InChain);
816 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
818 OutChain = LD->getChain();
823 // Also handle the case where we explicitly require zeros in the top
824 // elements. This is a vector shuffle from the zero vector.
825 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
826 N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
827 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
828 N.getOperand(1).Val->hasOneUse() &&
829 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
830 N.getOperand(1).getOperand(0).hasOneUse()) {
831 // Check to see if the BUILD_VECTOR is building a zero vector.
832 SDOperand BV = N.getOperand(0);
833 for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
834 if (!isZeroNode(BV.getOperand(i)) &&
835 BV.getOperand(i).getOpcode() != ISD::UNDEF)
836 return false; // Not a zero/undef vector.
837 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
839 unsigned VecWidth = BV.getNumOperands();
840 SDOperand ShufMask = N.getOperand(2);
841 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
842 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
843 if (C->getValue() == VecWidth) {
844 for (unsigned i = 1; i != VecWidth; ++i) {
845 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
848 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
849 if (C->getValue() >= VecWidth) return false;
854 // Okay, this is a zero extending load. Fold it.
855 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
856 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
858 OutChain = LD->getChain();
859 InChain = SDOperand(LD, 1);
867 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
868 /// mode it matches can be cost effectively emitted as an LEA instruction.
869 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
870 SDOperand &Base, SDOperand &Scale,
871 SDOperand &Index, SDOperand &Disp) {
872 X86ISelAddressMode AM;
873 if (MatchAddress(N, AM))
876 MVT::ValueType VT = N.getValueType();
877 unsigned Complexity = 0;
878 if (AM.BaseType == X86ISelAddressMode::RegBase)
882 AM.Base.Reg = CurDAG->getRegister(0, VT);
883 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
889 AM.IndexReg = CurDAG->getRegister(0, VT);
893 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg
894 else if (AM.Scale > 1)
897 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
898 // to a LEA. This is determined with some expermentation but is by no means
899 // optimal (especially for code size consideration). LEA is nice because of
900 // its three-address nature. Tweak the cost function again when we can run
901 // convertToThreeAddress() at register allocation time.
902 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
903 // For X86-64, we should always use lea to materialize RIP relative
905 if (Subtarget->is64Bit())
911 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
914 if (Complexity > 2) {
915 getAddressOperands(AM, Base, Scale, Index, Disp);
921 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
922 SDOperand &Base, SDOperand &Scale,
923 SDOperand &Index, SDOperand &Disp) {
924 if (ISD::isNON_EXTLoad(N.Val) &&
926 CanBeFoldedBy(N.Val, P.Val, P.Val))
927 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
931 /// getGlobalBaseReg - Output the instructions required to put the
932 /// base address to use for accessing globals into a register.
934 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
935 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
936 if (!GlobalBaseReg) {
937 // Insert the set of GlobalBaseReg into the first MBB of the function
938 MachineBasicBlock &FirstMBB = BB->getParent()->front();
939 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
940 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
941 unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
943 const TargetInstrInfo *TII = TM.getInstrInfo();
944 BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
945 BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
947 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
948 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
949 if (Subtarget->isPICStyleGOT()) {
950 GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
951 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
953 addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
959 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
962 static SDNode *FindCallStartFromCall(SDNode *Node) {
963 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
964 assert(Node->getOperand(0).getValueType() == MVT::Other &&
965 "Node doesn't have a token chain argument!");
966 return FindCallStartFromCall(Node->getOperand(0).Val);
969 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
970 SDNode *Node = N.Val;
971 MVT::ValueType NVT = Node->getValueType(0);
973 unsigned Opcode = Node->getOpcode();
976 DOUT << std::string(Indent, ' ') << "Selecting: ";
977 DEBUG(Node->dump(CurDAG));
982 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
984 DOUT << std::string(Indent-2, ' ') << "== ";
985 DEBUG(Node->dump(CurDAG));
989 return NULL; // Already selected.
994 case X86ISD::GlobalBaseReg:
995 return getGlobalBaseReg();
998 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
999 // code and is matched first so to prevent it from being turned into
1001 // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1002 MVT::ValueType PtrVT = TLI.getPointerTy();
1003 SDOperand N0 = N.getOperand(0);
1004 SDOperand N1 = N.getOperand(1);
1005 if (N.Val->getValueType(0) == PtrVT &&
1006 N0.getOpcode() == X86ISD::Wrapper &&
1007 N1.getOpcode() == ISD::Constant) {
1008 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1010 // TODO: handle ExternalSymbolSDNode.
1011 if (GlobalAddressSDNode *G =
1012 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1013 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1014 G->getOffset() + Offset);
1015 } else if (ConstantPoolSDNode *CP =
1016 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1017 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1019 CP->getOffset()+Offset);
1023 if (Subtarget->is64Bit()) {
1024 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1025 CurDAG->getRegister(0, PtrVT), C };
1026 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1028 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1032 // Other cases are handled by auto-generated code.
1038 if (Opcode == ISD::MULHU)
1040 default: assert(0 && "Unsupported VT!");
1041 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1042 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1043 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1044 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1048 default: assert(0 && "Unsupported VT!");
1049 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1050 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1051 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1052 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1055 unsigned LoReg, HiReg;
1057 default: assert(0 && "Unsupported VT!");
1058 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1059 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1060 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1061 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1064 SDOperand N0 = Node->getOperand(0);
1065 SDOperand N1 = Node->getOperand(1);
1067 bool foldedLoad = false;
1068 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1069 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1070 // MULHU and MULHS are commmutative
1072 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1074 N0 = Node->getOperand(1);
1075 N1 = Node->getOperand(0);
1081 Chain = N1.getOperand(0);
1082 AddToISelQueue(Chain);
1084 Chain = CurDAG->getEntryNode();
1086 SDOperand InFlag(0, 0);
1088 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1090 InFlag = Chain.getValue(1);
1093 AddToISelQueue(Tmp0);
1094 AddToISelQueue(Tmp1);
1095 AddToISelQueue(Tmp2);
1096 AddToISelQueue(Tmp3);
1097 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1099 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1100 Chain = SDOperand(CNode, 0);
1101 InFlag = SDOperand(CNode, 1);
1105 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1108 SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1109 ReplaceUses(N.getValue(0), Result);
1111 ReplaceUses(N1.getValue(1), Result.getValue(1));
1114 DOUT << std::string(Indent-2, ' ') << "=> ";
1115 DEBUG(Result.Val->dump(CurDAG));
1126 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1127 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1130 default: assert(0 && "Unsupported VT!");
1131 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1132 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1133 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1134 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1138 default: assert(0 && "Unsupported VT!");
1139 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1140 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1141 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1142 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1145 unsigned LoReg, HiReg;
1146 unsigned ClrOpcode, SExtOpcode;
1148 default: assert(0 && "Unsupported VT!");
1150 LoReg = X86::AL; HiReg = X86::AH;
1152 SExtOpcode = X86::CBW;
1155 LoReg = X86::AX; HiReg = X86::DX;
1156 ClrOpcode = X86::MOV16r0;
1157 SExtOpcode = X86::CWD;
1160 LoReg = X86::EAX; HiReg = X86::EDX;
1161 ClrOpcode = X86::MOV32r0;
1162 SExtOpcode = X86::CDQ;
1165 LoReg = X86::RAX; HiReg = X86::RDX;
1166 ClrOpcode = X86::MOV64r0;
1167 SExtOpcode = X86::CQO;
1171 SDOperand N0 = Node->getOperand(0);
1172 SDOperand N1 = Node->getOperand(1);
1173 SDOperand InFlag(0, 0);
1174 if (NVT == MVT::i8 && !isSigned) {
1175 // Special case for div8, just use a move with zero extension to AX to
1176 // clear the upper 8 bits (AH).
1177 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1178 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1179 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1180 AddToISelQueue(N0.getOperand(0));
1181 AddToISelQueue(Tmp0);
1182 AddToISelQueue(Tmp1);
1183 AddToISelQueue(Tmp2);
1184 AddToISelQueue(Tmp3);
1186 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1188 Chain = Move.getValue(1);
1189 ReplaceUses(N0.getValue(1), Chain);
1193 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1194 Chain = CurDAG->getEntryNode();
1196 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1197 InFlag = Chain.getValue(1);
1201 CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1202 InFlag).getValue(1);
1204 // Sign extend the low part into the high part.
1206 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1208 // Zero out the high part, effectively zero extending the input.
1209 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1210 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1211 InFlag).getValue(1);
1215 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1216 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1218 AddToISelQueue(N1.getOperand(0));
1219 AddToISelQueue(Tmp0);
1220 AddToISelQueue(Tmp1);
1221 AddToISelQueue(Tmp2);
1222 AddToISelQueue(Tmp3);
1223 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1225 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1226 Chain = SDOperand(CNode, 0);
1227 InFlag = SDOperand(CNode, 1);
1230 Chain = CurDAG->getEntryNode();
1232 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1236 CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1237 ReplaceUses(N.getValue(0), Result);
1239 ReplaceUses(N1.getValue(1), Result.getValue(1));
1242 DOUT << std::string(Indent-2, ' ') << "=> ";
1243 DEBUG(Result.Val->dump(CurDAG));
1251 case ISD::TRUNCATE: {
1252 if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1255 switch (Node->getOperand(0).getValueType()) {
1256 default: assert(0 && "Unknown truncate!");
1258 Opc = X86::MOV16to16_;
1260 Opc2 = X86::TRUNC_16_to8;
1263 Opc = X86::MOV32to32_;
1265 Opc2 = X86::TRUNC_32_to8;
1269 AddToISelQueue(Node->getOperand(0));
1271 SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1272 SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1275 DOUT << std::string(Indent-2, ' ') << "=> ";
1276 DEBUG(ResNode->dump(CurDAG));
1287 SDNode *ResNode = SelectCode(N);
1290 DOUT << std::string(Indent-2, ' ') << "=> ";
1291 if (ResNode == NULL || ResNode == N.Val)
1292 DEBUG(N.Val->dump(CurDAG));
1294 DEBUG(ResNode->dump(CurDAG));
1302 bool X86DAGToDAGISel::
1303 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1304 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1305 SDOperand Op0, Op1, Op2, Op3;
1306 switch (ConstraintCode) {
1307 case 'o': // offsetable ??
1308 case 'v': // not offsetable ??
1309 default: return true;
1311 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1316 OutOps.push_back(Op0);
1317 OutOps.push_back(Op1);
1318 OutOps.push_back(Op2);
1319 OutOps.push_back(Op3);
1320 AddToISelQueue(Op0);
1321 AddToISelQueue(Op1);
1322 AddToISelQueue(Op2);
1323 AddToISelQueue(Op3);
1327 /// createX86ISelDag - This pass converts a legalized DAG into a
1328 /// X86-specific DAG, ready for instruction scheduling.
1330 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1331 return new X86DAGToDAGISel(TM, Fast);