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/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/ADT/Statistic.h"
42 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
43 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46 //===----------------------------------------------------------------------===//
47 // Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
51 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52 /// SDOperand's instead of register numbers for the leaves of the matched
54 struct X86ISelAddressMode {
60 struct { // This is really a union, discriminated by BaseType!
65 bool isRIPRel; // RIP relative?
73 unsigned Align; // CP alignment.
76 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
77 GV(0), CP(0), ES(0), JT(-1), Align(0) {
83 //===--------------------------------------------------------------------===//
84 /// ISel - X86 specific code to select X86 machine instructions for
85 /// SelectionDAG operations.
87 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
88 /// ContainsFPCode - Every instruction we select that uses or defines a FP
89 /// register should set this to true.
92 /// FastISel - Enable fast(er) instruction selection.
96 /// TM - Keep a reference to X86TargetMachine.
100 /// X86Lowering - This object fully describes how to lower LLVM code to an
101 /// X86-specific SelectionDAG.
102 X86TargetLowering X86Lowering;
104 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
105 /// make the right decision when generating code for different targets.
106 const X86Subtarget *Subtarget;
108 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
110 unsigned GlobalBaseReg;
113 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
114 : SelectionDAGISel(X86Lowering),
115 ContainsFPCode(false), FastISel(fast), TM(tm),
116 X86Lowering(*TM.getTargetLowering()),
117 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
119 virtual bool runOnFunction(Function &Fn) {
120 // Make sure we re-emit a set of the global base reg if necessary
122 return SelectionDAGISel::runOnFunction(Fn);
125 virtual const char *getPassName() const {
126 return "X86 DAG->DAG Instruction Selection";
129 /// InstructionSelectBasicBlock - This callback is invoked by
130 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
131 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
133 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
135 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root);
137 // Include the pieces autogenerated from the target description.
138 #include "X86GenDAGISel.inc"
141 SDNode *Select(SDOperand N);
143 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
144 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
145 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
146 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
147 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
148 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
149 SDOperand N, SDOperand &Base, SDOperand &Scale,
150 SDOperand &Index, SDOperand &Disp,
151 SDOperand &InChain, SDOperand &OutChain);
152 bool TryFoldLoad(SDOperand P, SDOperand N,
153 SDOperand &Base, SDOperand &Scale,
154 SDOperand &Index, SDOperand &Disp);
155 void InstructionSelectPreprocess(SelectionDAG &DAG);
157 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
158 /// inline asm expressions.
159 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
161 std::vector<SDOperand> &OutOps,
164 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
166 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
167 SDOperand &Scale, SDOperand &Index,
169 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
170 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
172 Scale = getI8Imm(AM.Scale);
174 // These are 32-bit even in 64-bit mode since RIP relative offset
177 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
179 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
181 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
182 else if (AM.JT != -1)
183 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
185 Disp = getI32Imm(AM.Disp);
188 /// getI8Imm - Return a target constant with the specified value, of type
190 inline SDOperand getI8Imm(unsigned Imm) {
191 return CurDAG->getTargetConstant(Imm, MVT::i8);
194 /// getI16Imm - Return a target constant with the specified value, of type
196 inline SDOperand getI16Imm(unsigned Imm) {
197 return CurDAG->getTargetConstant(Imm, MVT::i16);
200 /// getI32Imm - Return a target constant with the specified value, of type
202 inline SDOperand getI32Imm(unsigned Imm) {
203 return CurDAG->getTargetConstant(Imm, MVT::i32);
206 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
207 /// base register. Return the virtual register that holds this value.
208 SDNode *getGlobalBaseReg();
216 static SDNode *findFlagUse(SDNode *N) {
217 unsigned FlagResNo = N->getNumValues()-1;
218 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
220 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
221 SDOperand Op = User->getOperand(i);
222 if (Op.Val == N && Op.ResNo == FlagResNo)
229 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
230 SDNode *Root, SDNode *Skip, bool &found,
231 std::set<SDNode *> &Visited) {
233 Use->getNodeId() > Def->getNodeId() ||
234 !Visited.insert(Use).second)
237 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
238 SDNode *N = Use->getOperand(i).Val;
243 continue; // Immediate use is ok.
245 assert(Use->getOpcode() == ISD::STORE ||
246 Use->getOpcode() == X86ISD::CMP);
252 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
256 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
257 /// be reached. Return true if that's the case. However, ignore direct uses
258 /// by ImmedUse (which would be U in the example illustrated in
259 /// CanBeFoldedBy) and by Root (which can happen in the store case).
260 /// FIXME: to be really generic, we should allow direct use by any node
261 /// that is being folded. But realisticly since we only fold loads which
262 /// have one non-chain use, we only need to watch out for load/op/store
263 /// and load/op/cmp case where the root (store / cmp) may reach the load via
264 /// its chain operand.
265 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
266 SDNode *Skip = NULL) {
267 std::set<SDNode *> Visited;
269 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
274 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) {
275 if (FastISel) return false;
277 // If U use can somehow reach N through another path then U can't fold N or
278 // it will create a cycle. e.g. In the following diagram, U can reach N
279 // through X. If N is folded into into U, then X is both a predecessor and
290 if (isNonImmUse(Root, N, U))
293 // If U produces a flag, then it gets (even more) interesting. Since it
294 // would have been "glued" together with its flag use, we need to check if
307 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
308 // NU), then TF is a predecessor of FU and a successor of NU. But since
309 // NU and FU are flagged together, this effectively creates a cycle.
310 bool HasFlagUse = false;
311 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
312 while ((VT == MVT::Flag && !Root->use_empty())) {
313 SDNode *FU = findFlagUse(Root);
320 VT = Root->getValueType(Root->getNumValues()-1);
324 return !isNonImmUse(Root, N, Root, U);
328 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
329 /// and move load below the TokenFactor. Replace store's chain operand with
330 /// load's chain result.
331 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
332 SDOperand Store, SDOperand TF) {
333 std::vector<SDOperand> Ops;
334 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
335 if (Load.Val == TF.Val->getOperand(i).Val)
336 Ops.push_back(Load.Val->getOperand(0));
338 Ops.push_back(TF.Val->getOperand(i));
339 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
340 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
341 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
342 Store.getOperand(2), Store.getOperand(3));
345 /// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
346 /// selector to pick more load-modify-store instructions. This is a common
357 /// [TokenFactor] [Op]
364 /// The fact the store's chain operand != load's chain will prevent the
365 /// (store (op (load))) instruction from being selected. We can transform it to:
384 void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
385 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
386 E = DAG.allnodes_end(); I != E; ++I) {
387 if (!ISD::isNON_TRUNCStore(I))
389 SDOperand Chain = I->getOperand(0);
390 if (Chain.Val->getOpcode() != ISD::TokenFactor)
393 SDOperand N1 = I->getOperand(1);
394 SDOperand N2 = I->getOperand(2);
395 if (MVT::isFloatingPoint(N1.getValueType()) ||
396 MVT::isVector(N1.getValueType()) ||
402 unsigned Opcode = N1.Val->getOpcode();
411 SDOperand N10 = N1.getOperand(0);
412 SDOperand N11 = N1.getOperand(1);
413 if (ISD::isNON_EXTLoad(N10.Val))
415 else if (ISD::isNON_EXTLoad(N11.Val)) {
419 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
420 (N10.getOperand(1) == N2) &&
421 (N10.Val->getValueType(0) == N1.getValueType());
436 SDOperand N10 = N1.getOperand(0);
437 if (ISD::isNON_EXTLoad(N10.Val))
438 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
439 (N10.getOperand(1) == N2) &&
440 (N10.Val->getValueType(0) == N1.getValueType());
448 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
454 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
455 /// when it has created a SelectionDAG for us to codegen.
456 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
458 MachineFunction::iterator FirstMBB = BB;
461 InstructionSelectPreprocess(DAG);
463 // Codegen the basic block.
465 DOUT << "===== Instruction selection begins:\n";
468 DAG.setRoot(SelectRoot(DAG.getRoot()));
470 DOUT << "===== Instruction selection ends:\n";
473 DAG.RemoveDeadNodes();
475 // Emit machine code to BB.
476 ScheduleAndEmitDAG(DAG);
478 // If we are emitting FP stack code, scan the basic block to determine if this
479 // block defines any FP values. If so, put an FP_REG_KILL instruction before
480 // the terminator of the block.
481 if (!Subtarget->hasSSE2()) {
482 // Note that FP stack instructions *are* used in SSE code when returning
483 // values, but these are not live out of the basic block, so we don't need
484 // an FP_REG_KILL in this case either.
485 bool ContainsFPCode = false;
487 // Scan all of the machine instructions in these MBBs, checking for FP
489 MachineFunction::iterator MBBI = FirstMBB;
491 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
492 !ContainsFPCode && I != E; ++I) {
493 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
494 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
495 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
496 RegMap->getRegClass(I->getOperand(0).getReg()) ==
497 X86::RFPRegisterClass) {
498 ContainsFPCode = true;
503 } while (!ContainsFPCode && &*(MBBI++) != BB);
505 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
506 // a copy of the input value in this block.
507 if (!ContainsFPCode) {
508 // Final check, check LLVM BB's that are successors to the LLVM BB
509 // corresponding to BB for FP PHI nodes.
510 const BasicBlock *LLVMBB = BB->getBasicBlock();
512 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
513 !ContainsFPCode && SI != E; ++SI) {
514 for (BasicBlock::const_iterator II = SI->begin();
515 (PN = dyn_cast<PHINode>(II)); ++II) {
516 if (PN->getType()->isFloatingPoint()) {
517 ContainsFPCode = true;
524 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
525 if (ContainsFPCode) {
526 BuildMI(*BB, BB->getFirstTerminator(),
527 TM.getInstrInfo()->get(X86::FP_REG_KILL));
533 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
534 /// the main function.
535 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
536 MachineFrameInfo *MFI) {
537 const TargetInstrInfo *TII = TM.getInstrInfo();
538 if (Subtarget->isTargetCygMing())
539 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
541 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
542 int CWFrameIdx = MFI->CreateStackObject(2, 2);
543 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
545 // Set the high part to be 64-bit precision.
546 addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
547 CWFrameIdx, 1).addImm(2);
549 // Reload the modified control word now.
550 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
553 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
554 // If this is main, emit special code for main.
555 MachineBasicBlock *BB = MF.begin();
556 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
557 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
560 /// MatchAddress - Add the specified node to the specified addressing mode,
561 /// returning true if it cannot be done. This just pattern matches for the
563 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
565 // RIP relative addressing: %rip + 32-bit displacement!
567 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
568 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
569 if (isInt32(AM.Disp + Val)) {
577 int id = N.Val->getNodeId();
578 bool Available = isSelected(id);
580 switch (N.getOpcode()) {
582 case ISD::Constant: {
583 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
584 if (isInt32(AM.Disp + Val)) {
591 case X86ISD::Wrapper: {
592 bool is64Bit = Subtarget->is64Bit();
593 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
594 if (is64Bit && TM.getCodeModel() != CodeModel::Small)
596 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
598 // If value is available in a register both base and index components have
599 // been picked, we can't fit the result available in the register in the
600 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
601 if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
602 bool isStatic = TM.getRelocationModel() == Reloc::Static;
603 SDOperand N0 = N.getOperand(0);
604 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
605 GlobalValue *GV = G->getGlobal();
606 bool isAbs32 = !is64Bit || isStatic;
607 if (isAbs32 || isRoot) {
609 AM.Disp += G->getOffset();
610 AM.isRIPRel = !isAbs32;
613 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
614 if (!is64Bit || isStatic || isRoot) {
615 AM.CP = CP->getConstVal();
616 AM.Align = CP->getAlignment();
617 AM.Disp += CP->getOffset();
618 AM.isRIPRel = !isStatic;
621 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
622 if (isStatic || isRoot) {
623 AM.ES = S->getSymbol();
624 AM.isRIPRel = !isStatic;
627 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
628 if (isStatic || isRoot) {
629 AM.JT = J->getIndex();
630 AM.isRIPRel = !isStatic;
638 case ISD::FrameIndex:
639 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
640 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
641 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
647 if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
648 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
649 unsigned Val = CN->getValue();
650 if (Val == 1 || Val == 2 || Val == 3) {
652 SDOperand ShVal = N.Val->getOperand(0);
654 // Okay, we know that we have a scale by now. However, if the scaled
655 // value is an add of something and a constant, we can fold the
656 // constant into the disp field here.
657 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
658 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
659 AM.IndexReg = ShVal.Val->getOperand(0);
660 ConstantSDNode *AddVal =
661 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
662 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
676 // X*[3,5,9] -> X+X*[2,4,8]
678 AM.BaseType == X86ISelAddressMode::RegBase &&
679 AM.Base.Reg.Val == 0 &&
680 AM.IndexReg.Val == 0) {
681 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
682 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
683 AM.Scale = unsigned(CN->getValue())-1;
685 SDOperand MulVal = N.Val->getOperand(0);
688 // Okay, we know that we have a scale by now. However, if the scaled
689 // value is an add of something and a constant, we can fold the
690 // constant into the disp field here.
691 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
692 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
693 Reg = MulVal.Val->getOperand(0);
694 ConstantSDNode *AddVal =
695 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
696 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
700 Reg = N.Val->getOperand(0);
702 Reg = N.Val->getOperand(0);
705 AM.IndexReg = AM.Base.Reg = Reg;
713 X86ISelAddressMode Backup = AM;
714 if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
715 !MatchAddress(N.Val->getOperand(1), AM, false))
718 if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
719 !MatchAddress(N.Val->getOperand(0), AM, false))
726 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
728 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
729 X86ISelAddressMode Backup = AM;
730 // Start with the LHS as an addr mode.
731 if (!MatchAddress(N.getOperand(0), AM, false) &&
732 // Address could not have picked a GV address for the displacement.
734 // On x86-64, the resultant disp must fit in 32-bits.
735 isInt32(AM.Disp + CN->getSignExtended()) &&
736 // Check to see if the LHS & C is zero.
737 TLI.MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
738 AM.Disp += CN->getValue();
747 // Is the base register already occupied?
748 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
749 // If so, check to see if the scale index register is set.
750 if (AM.IndexReg.Val == 0) {
756 // Otherwise, we cannot select it.
760 // Default, generate it as a register.
761 AM.BaseType = X86ISelAddressMode::RegBase;
766 /// SelectAddr - returns true if it is able pattern match an addressing mode.
767 /// It returns the operands which make up the maximal addressing mode it can
768 /// match by reference.
769 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
770 SDOperand &Scale, SDOperand &Index,
772 X86ISelAddressMode AM;
773 if (MatchAddress(N, AM))
776 MVT::ValueType VT = N.getValueType();
777 if (AM.BaseType == X86ISelAddressMode::RegBase) {
778 if (!AM.Base.Reg.Val)
779 AM.Base.Reg = CurDAG->getRegister(0, VT);
782 if (!AM.IndexReg.Val)
783 AM.IndexReg = CurDAG->getRegister(0, VT);
785 getAddressOperands(AM, Base, Scale, Index, Disp);
789 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
791 static inline bool isZeroNode(SDOperand Elt) {
792 return ((isa<ConstantSDNode>(Elt) &&
793 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
794 (isa<ConstantFPSDNode>(Elt) &&
795 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
799 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
800 /// match a load whose top elements are either undef or zeros. The load flavor
801 /// is derived from the type of N, which is either v4f32 or v2f64.
802 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
803 SDOperand N, SDOperand &Base,
804 SDOperand &Scale, SDOperand &Index,
805 SDOperand &Disp, SDOperand &InChain,
806 SDOperand &OutChain) {
807 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
808 InChain = N.getOperand(0).getValue(1);
809 if (ISD::isNON_EXTLoad(InChain.Val) &&
810 InChain.getValue(0).hasOneUse() &&
812 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
813 LoadSDNode *LD = cast<LoadSDNode>(InChain);
814 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
816 OutChain = LD->getChain();
821 // Also handle the case where we explicitly require zeros in the top
822 // elements. This is a vector shuffle from the zero vector.
823 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
824 N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
825 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
826 N.getOperand(1).Val->hasOneUse() &&
827 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
828 N.getOperand(1).getOperand(0).hasOneUse()) {
829 // Check to see if the BUILD_VECTOR is building a zero vector.
830 SDOperand BV = N.getOperand(0);
831 for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
832 if (!isZeroNode(BV.getOperand(i)) &&
833 BV.getOperand(i).getOpcode() != ISD::UNDEF)
834 return false; // Not a zero/undef vector.
835 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
837 unsigned VecWidth = BV.getNumOperands();
838 SDOperand ShufMask = N.getOperand(2);
839 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
840 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
841 if (C->getValue() == VecWidth) {
842 for (unsigned i = 1; i != VecWidth; ++i) {
843 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
846 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
847 if (C->getValue() >= VecWidth) return false;
852 // Okay, this is a zero extending load. Fold it.
853 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
854 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
856 OutChain = LD->getChain();
857 InChain = SDOperand(LD, 1);
865 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
866 /// mode it matches can be cost effectively emitted as an LEA instruction.
867 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
868 SDOperand &Base, SDOperand &Scale,
869 SDOperand &Index, SDOperand &Disp) {
870 X86ISelAddressMode AM;
871 if (MatchAddress(N, AM))
874 MVT::ValueType VT = N.getValueType();
875 unsigned Complexity = 0;
876 if (AM.BaseType == X86ISelAddressMode::RegBase)
880 AM.Base.Reg = CurDAG->getRegister(0, VT);
881 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
887 AM.IndexReg = CurDAG->getRegister(0, VT);
889 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
894 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
895 // to a LEA. This is determined with some expermentation but is by no means
896 // optimal (especially for code size consideration). LEA is nice because of
897 // its three-address nature. Tweak the cost function again when we can run
898 // convertToThreeAddress() at register allocation time.
899 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
900 // For X86-64, we should always use lea to materialize RIP relative
902 if (Subtarget->is64Bit())
908 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
911 if (Complexity > 2) {
912 getAddressOperands(AM, Base, Scale, Index, Disp);
918 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
919 SDOperand &Base, SDOperand &Scale,
920 SDOperand &Index, SDOperand &Disp) {
921 if (ISD::isNON_EXTLoad(N.Val) &&
923 CanBeFoldedBy(N.Val, P.Val, P.Val))
924 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
928 /// getGlobalBaseReg - Output the instructions required to put the
929 /// base address to use for accessing globals into a register.
931 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
932 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
933 if (!GlobalBaseReg) {
934 // Insert the set of GlobalBaseReg into the first MBB of the function
935 MachineBasicBlock &FirstMBB = BB->getParent()->front();
936 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
937 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
938 unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
940 const TargetInstrInfo *TII = TM.getInstrInfo();
941 BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
942 BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
944 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
945 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
946 if (TM.getRelocationModel() == Reloc::PIC_ &&
947 Subtarget->isPICStyleGOT()) {
948 GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
949 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
951 addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
957 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
960 static SDNode *FindCallStartFromCall(SDNode *Node) {
961 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
962 assert(Node->getOperand(0).getValueType() == MVT::Other &&
963 "Node doesn't have a token chain argument!");
964 return FindCallStartFromCall(Node->getOperand(0).Val);
967 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
968 SDNode *Node = N.Val;
969 MVT::ValueType NVT = Node->getValueType(0);
971 unsigned Opcode = Node->getOpcode();
974 DOUT << std::string(Indent, ' ') << "Selecting: ";
975 DEBUG(Node->dump(CurDAG));
980 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
982 DOUT << std::string(Indent-2, ' ') << "== ";
983 DEBUG(Node->dump(CurDAG));
987 return NULL; // Already selected.
992 case X86ISD::GlobalBaseReg:
993 return getGlobalBaseReg();
996 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
997 // code and is matched first so to prevent it from being turned into
999 // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1000 MVT::ValueType PtrVT = TLI.getPointerTy();
1001 SDOperand N0 = N.getOperand(0);
1002 SDOperand N1 = N.getOperand(1);
1003 if (N.Val->getValueType(0) == PtrVT &&
1004 N0.getOpcode() == X86ISD::Wrapper &&
1005 N1.getOpcode() == ISD::Constant) {
1006 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1008 // TODO: handle ExternalSymbolSDNode.
1009 if (GlobalAddressSDNode *G =
1010 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1011 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1012 G->getOffset() + Offset);
1013 } else if (ConstantPoolSDNode *CP =
1014 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1015 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1017 CP->getOffset()+Offset);
1021 if (Subtarget->is64Bit()) {
1022 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1023 CurDAG->getRegister(0, PtrVT), C };
1024 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1026 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1030 // Other cases are handled by auto-generated code.
1036 if (Opcode == ISD::MULHU)
1038 default: assert(0 && "Unsupported VT!");
1039 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1040 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1041 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1042 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1046 default: assert(0 && "Unsupported VT!");
1047 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1048 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1049 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1050 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1053 unsigned LoReg, HiReg;
1055 default: assert(0 && "Unsupported VT!");
1056 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1057 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1058 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1059 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1062 SDOperand N0 = Node->getOperand(0);
1063 SDOperand N1 = Node->getOperand(1);
1065 bool foldedLoad = false;
1066 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1067 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1068 // MULHU and MULHS are commmutative
1070 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1072 N0 = Node->getOperand(1);
1073 N1 = Node->getOperand(0);
1079 Chain = N1.getOperand(0);
1080 AddToISelQueue(Chain);
1082 Chain = CurDAG->getEntryNode();
1084 SDOperand InFlag(0, 0);
1086 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1088 InFlag = Chain.getValue(1);
1091 AddToISelQueue(Tmp0);
1092 AddToISelQueue(Tmp1);
1093 AddToISelQueue(Tmp2);
1094 AddToISelQueue(Tmp3);
1095 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1097 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1098 Chain = SDOperand(CNode, 0);
1099 InFlag = SDOperand(CNode, 1);
1103 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1106 SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1107 ReplaceUses(N.getValue(0), Result);
1109 ReplaceUses(N1.getValue(1), Result.getValue(1));
1112 DOUT << std::string(Indent-2, ' ') << "=> ";
1113 DEBUG(Result.Val->dump(CurDAG));
1124 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1125 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1128 default: assert(0 && "Unsupported VT!");
1129 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1130 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1131 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1132 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1136 default: assert(0 && "Unsupported VT!");
1137 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1138 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1139 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1140 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1143 unsigned LoReg, HiReg;
1144 unsigned ClrOpcode, SExtOpcode;
1146 default: assert(0 && "Unsupported VT!");
1148 LoReg = X86::AL; HiReg = X86::AH;
1150 SExtOpcode = X86::CBW;
1153 LoReg = X86::AX; HiReg = X86::DX;
1154 ClrOpcode = X86::MOV16r0;
1155 SExtOpcode = X86::CWD;
1158 LoReg = X86::EAX; HiReg = X86::EDX;
1159 ClrOpcode = X86::MOV32r0;
1160 SExtOpcode = X86::CDQ;
1163 LoReg = X86::RAX; HiReg = X86::RDX;
1164 ClrOpcode = X86::MOV64r0;
1165 SExtOpcode = X86::CQO;
1169 SDOperand N0 = Node->getOperand(0);
1170 SDOperand N1 = Node->getOperand(1);
1171 SDOperand InFlag(0, 0);
1172 if (NVT == MVT::i8 && !isSigned) {
1173 // Special case for div8, just use a move with zero extension to AX to
1174 // clear the upper 8 bits (AH).
1175 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1176 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1177 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1178 AddToISelQueue(N0.getOperand(0));
1179 AddToISelQueue(Tmp0);
1180 AddToISelQueue(Tmp1);
1181 AddToISelQueue(Tmp2);
1182 AddToISelQueue(Tmp3);
1184 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1186 Chain = Move.getValue(1);
1187 ReplaceUses(N0.getValue(1), Chain);
1191 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1192 Chain = CurDAG->getEntryNode();
1194 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1195 InFlag = Chain.getValue(1);
1199 CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1200 InFlag).getValue(1);
1202 // Sign extend the low part into the high part.
1204 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1206 // Zero out the high part, effectively zero extending the input.
1207 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1208 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1209 InFlag).getValue(1);
1213 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1214 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1216 AddToISelQueue(N1.getOperand(0));
1217 AddToISelQueue(Tmp0);
1218 AddToISelQueue(Tmp1);
1219 AddToISelQueue(Tmp2);
1220 AddToISelQueue(Tmp3);
1221 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1223 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1224 Chain = SDOperand(CNode, 0);
1225 InFlag = SDOperand(CNode, 1);
1228 Chain = CurDAG->getEntryNode();
1230 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1234 CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1235 ReplaceUses(N.getValue(0), Result);
1237 ReplaceUses(N1.getValue(1), Result.getValue(1));
1240 DOUT << std::string(Indent-2, ' ') << "=> ";
1241 DEBUG(Result.Val->dump(CurDAG));
1249 case ISD::TRUNCATE: {
1250 if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1253 switch (Node->getOperand(0).getValueType()) {
1254 default: assert(0 && "Unknown truncate!");
1256 Opc = X86::MOV16to16_;
1258 Opc2 = X86::TRUNC_16_to8;
1261 Opc = X86::MOV32to32_;
1263 Opc2 = X86::TRUNC_32_to8;
1267 AddToISelQueue(Node->getOperand(0));
1269 SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1270 SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1273 DOUT << std::string(Indent-2, ' ') << "=> ";
1274 DEBUG(ResNode->dump(CurDAG));
1285 SDNode *ResNode = SelectCode(N);
1288 DOUT << std::string(Indent-2, ' ') << "=> ";
1289 if (ResNode == NULL || ResNode == N.Val)
1290 DEBUG(N.Val->dump(CurDAG));
1292 DEBUG(ResNode->dump(CurDAG));
1300 bool X86DAGToDAGISel::
1301 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1302 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1303 SDOperand Op0, Op1, Op2, Op3;
1304 switch (ConstraintCode) {
1305 case 'o': // offsetable ??
1306 case 'v': // not offsetable ??
1307 default: return true;
1309 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1314 OutOps.push_back(Op0);
1315 OutOps.push_back(Op1);
1316 OutOps.push_back(Op2);
1317 OutOps.push_back(Op3);
1318 AddToISelQueue(Op0);
1319 AddToISelQueue(Op1);
1320 AddToISelQueue(Op2);
1321 AddToISelQueue(Op3);
1325 /// createX86ISelDag - This pass converts a legalized DAG into a
1326 /// X86-specific DAG, ready for instruction scheduling.
1328 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1329 return new X86DAGToDAGISel(TM, Fast);