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) const;
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,
144 bool isRoot = true, unsigned Depth = 0);
145 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
146 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
147 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
148 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
149 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
150 SDOperand N, SDOperand &Base, SDOperand &Scale,
151 SDOperand &Index, SDOperand &Disp,
152 SDOperand &InChain, SDOperand &OutChain);
153 bool TryFoldLoad(SDOperand P, SDOperand N,
154 SDOperand &Base, SDOperand &Scale,
155 SDOperand &Index, SDOperand &Disp);
156 void InstructionSelectPreprocess(SelectionDAG &DAG);
158 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
159 /// inline asm expressions.
160 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
162 std::vector<SDOperand> &OutOps,
165 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
167 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
168 SDOperand &Scale, SDOperand &Index,
170 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
171 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
173 Scale = getI8Imm(AM.Scale);
175 // These are 32-bit even in 64-bit mode since RIP relative offset
178 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
180 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
182 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
183 else if (AM.JT != -1)
184 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
186 Disp = getI32Imm(AM.Disp);
189 /// getI8Imm - Return a target constant with the specified value, of type
191 inline SDOperand getI8Imm(unsigned Imm) {
192 return CurDAG->getTargetConstant(Imm, MVT::i8);
195 /// getI16Imm - Return a target constant with the specified value, of type
197 inline SDOperand getI16Imm(unsigned Imm) {
198 return CurDAG->getTargetConstant(Imm, MVT::i16);
201 /// getI32Imm - Return a target constant with the specified value, of type
203 inline SDOperand getI32Imm(unsigned Imm) {
204 return CurDAG->getTargetConstant(Imm, MVT::i32);
207 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
208 /// base register. Return the virtual register that holds this value.
209 SDNode *getGlobalBaseReg();
217 static SDNode *findFlagUse(SDNode *N) {
218 unsigned FlagResNo = N->getNumValues()-1;
219 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
221 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
222 SDOperand Op = User->getOperand(i);
223 if (Op.Val == N && Op.ResNo == FlagResNo)
230 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
231 SDNode *Root, SDNode *Skip, bool &found,
232 std::set<SDNode *> &Visited) {
234 Use->getNodeId() > Def->getNodeId() ||
235 !Visited.insert(Use).second)
238 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
239 SDNode *N = Use->getOperand(i).Val;
244 continue; // Immediate use is ok.
246 assert(Use->getOpcode() == ISD::STORE ||
247 Use->getOpcode() == X86ISD::CMP);
253 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
257 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
258 /// be reached. Return true if that's the case. However, ignore direct uses
259 /// by ImmedUse (which would be U in the example illustrated in
260 /// CanBeFoldedBy) and by Root (which can happen in the store case).
261 /// FIXME: to be really generic, we should allow direct use by any node
262 /// that is being folded. But realisticly since we only fold loads which
263 /// have one non-chain use, we only need to watch out for load/op/store
264 /// and load/op/cmp case where the root (store / cmp) may reach the load via
265 /// its chain operand.
266 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
267 SDNode *Skip = NULL) {
268 std::set<SDNode *> Visited;
270 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
275 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
276 if (FastISel) return false;
278 // If U use can somehow reach N through another path then U can't fold N or
279 // it will create a cycle. e.g. In the following diagram, U can reach N
280 // through X. If N is folded into into U, then X is both a predecessor and
291 if (isNonImmUse(Root, N, U))
294 // If U produces a flag, then it gets (even more) interesting. Since it
295 // would have been "glued" together with its flag use, we need to check if
308 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
309 // NU), then TF is a predecessor of FU and a successor of NU. But since
310 // NU and FU are flagged together, this effectively creates a cycle.
311 bool HasFlagUse = false;
312 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
313 while ((VT == MVT::Flag && !Root->use_empty())) {
314 SDNode *FU = findFlagUse(Root);
321 VT = Root->getValueType(Root->getNumValues()-1);
325 return !isNonImmUse(Root, N, Root, U);
329 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
330 /// and move load below the TokenFactor. Replace store's chain operand with
331 /// load's chain result.
332 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
333 SDOperand Store, SDOperand TF) {
334 std::vector<SDOperand> Ops;
335 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
336 if (Load.Val == TF.Val->getOperand(i).Val)
337 Ops.push_back(Load.Val->getOperand(0));
339 Ops.push_back(TF.Val->getOperand(i));
340 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
341 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
342 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
343 Store.getOperand(2), Store.getOperand(3));
346 /// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
347 /// selector to pick more load-modify-store instructions. This is a common
358 /// [TokenFactor] [Op]
365 /// The fact the store's chain operand != load's chain will prevent the
366 /// (store (op (load))) instruction from being selected. We can transform it to:
385 void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
386 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
387 E = DAG.allnodes_end(); I != E; ++I) {
388 if (!ISD::isNON_TRUNCStore(I))
390 SDOperand Chain = I->getOperand(0);
391 if (Chain.Val->getOpcode() != ISD::TokenFactor)
394 SDOperand N1 = I->getOperand(1);
395 SDOperand N2 = I->getOperand(2);
396 if (MVT::isFloatingPoint(N1.getValueType()) ||
397 MVT::isVector(N1.getValueType()) ||
403 unsigned Opcode = N1.Val->getOpcode();
412 SDOperand N10 = N1.getOperand(0);
413 SDOperand N11 = N1.getOperand(1);
414 if (ISD::isNON_EXTLoad(N10.Val))
416 else if (ISD::isNON_EXTLoad(N11.Val)) {
420 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
421 (N10.getOperand(1) == N2) &&
422 (N10.Val->getValueType(0) == N1.getValueType());
437 SDOperand N10 = N1.getOperand(0);
438 if (ISD::isNON_EXTLoad(N10.Val))
439 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
440 (N10.getOperand(1) == N2) &&
441 (N10.Val->getValueType(0) == N1.getValueType());
449 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
455 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
456 /// when it has created a SelectionDAG for us to codegen.
457 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
459 MachineFunction::iterator FirstMBB = BB;
462 InstructionSelectPreprocess(DAG);
464 // Codegen the basic block.
466 DOUT << "===== Instruction selection begins:\n";
469 DAG.setRoot(SelectRoot(DAG.getRoot()));
471 DOUT << "===== Instruction selection ends:\n";
474 DAG.RemoveDeadNodes();
476 // Emit machine code to BB.
477 ScheduleAndEmitDAG(DAG);
479 // If we are emitting FP stack code, scan the basic block to determine if this
480 // block defines any FP values. If so, put an FP_REG_KILL instruction before
481 // the terminator of the block.
482 if (!Subtarget->hasSSE2()) {
483 // Note that FP stack instructions *are* used in SSE code when returning
484 // values, but these are not live out of the basic block, so we don't need
485 // an FP_REG_KILL in this case either.
486 bool ContainsFPCode = false;
488 // Scan all of the machine instructions in these MBBs, checking for FP
490 MachineFunction::iterator MBBI = FirstMBB;
492 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
493 !ContainsFPCode && I != E; ++I) {
494 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
495 const TargetRegisterClass *clas;
496 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
497 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
498 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
499 ((clas = RegMap->getRegClass(I->getOperand(0).getReg())) ==
500 X86::RFP32RegisterClass ||
501 clas == X86::RFP64RegisterClass)) {
502 ContainsFPCode = true;
508 } while (!ContainsFPCode && &*(MBBI++) != BB);
510 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
511 // a copy of the input value in this block.
512 if (!ContainsFPCode) {
513 // Final check, check LLVM BB's that are successors to the LLVM BB
514 // corresponding to BB for FP PHI nodes.
515 const BasicBlock *LLVMBB = BB->getBasicBlock();
517 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
518 !ContainsFPCode && SI != E; ++SI) {
519 for (BasicBlock::const_iterator II = SI->begin();
520 (PN = dyn_cast<PHINode>(II)); ++II) {
521 if (PN->getType()->isFloatingPoint()) {
522 ContainsFPCode = true;
529 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
530 if (ContainsFPCode) {
531 BuildMI(*BB, BB->getFirstTerminator(),
532 TM.getInstrInfo()->get(X86::FP_REG_KILL));
538 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
539 /// the main function.
540 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
541 MachineFrameInfo *MFI) {
542 const TargetInstrInfo *TII = TM.getInstrInfo();
543 if (Subtarget->isTargetCygMing())
544 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
546 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
547 int CWFrameIdx = MFI->CreateStackObject(2, 2);
548 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
550 // Set the high part to be 64-bit precision.
551 addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
552 CWFrameIdx, 1).addImm(2);
554 // Reload the modified control word now.
555 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
558 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
559 // If this is main, emit special code for main.
560 MachineBasicBlock *BB = MF.begin();
561 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
562 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
565 /// MatchAddress - Add the specified node to the specified addressing mode,
566 /// returning true if it cannot be done. This just pattern matches for the
568 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
569 bool isRoot, unsigned Depth) {
571 // Default, generate it as a register.
572 AM.BaseType = X86ISelAddressMode::RegBase;
577 // RIP relative addressing: %rip + 32-bit displacement!
579 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
580 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
581 if (isInt32(AM.Disp + Val)) {
589 int id = N.Val->getNodeId();
590 bool Available = isSelected(id);
592 switch (N.getOpcode()) {
594 case ISD::Constant: {
595 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
596 if (isInt32(AM.Disp + Val)) {
603 case X86ISD::Wrapper: {
604 bool is64Bit = Subtarget->is64Bit();
605 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
606 if (is64Bit && TM.getCodeModel() != CodeModel::Small)
608 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
610 // If value is available in a register both base and index components have
611 // been picked, we can't fit the result available in the register in the
612 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
613 if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
614 bool isStatic = TM.getRelocationModel() == Reloc::Static;
615 SDOperand N0 = N.getOperand(0);
616 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
617 GlobalValue *GV = G->getGlobal();
618 // Mac OS X X86-64 lower 4G address is not available.
619 bool isAbs32 = !is64Bit || (isStatic && !Subtarget->isTargetDarwin());
620 if (isAbs32 || isRoot) {
622 AM.Disp += G->getOffset();
623 AM.isRIPRel = !isAbs32;
626 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
627 if (!is64Bit || isStatic || isRoot) {
628 AM.CP = CP->getConstVal();
629 AM.Align = CP->getAlignment();
630 AM.Disp += CP->getOffset();
631 AM.isRIPRel = !isStatic;
634 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
635 if (isStatic || isRoot) {
636 AM.ES = S->getSymbol();
637 AM.isRIPRel = !isStatic;
640 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
641 if (isStatic || isRoot) {
642 AM.JT = J->getIndex();
643 AM.isRIPRel = !isStatic;
651 case ISD::FrameIndex:
652 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
653 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
654 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
660 if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
661 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
662 unsigned Val = CN->getValue();
663 if (Val == 1 || Val == 2 || Val == 3) {
665 SDOperand ShVal = N.Val->getOperand(0);
667 // Okay, we know that we have a scale by now. However, if the scaled
668 // value is an add of something and a constant, we can fold the
669 // constant into the disp field here.
670 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
671 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
672 AM.IndexReg = ShVal.Val->getOperand(0);
673 ConstantSDNode *AddVal =
674 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
675 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
689 // X*[3,5,9] -> X+X*[2,4,8]
691 AM.BaseType == X86ISelAddressMode::RegBase &&
692 AM.Base.Reg.Val == 0 &&
693 AM.IndexReg.Val == 0) {
694 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
695 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
696 AM.Scale = unsigned(CN->getValue())-1;
698 SDOperand MulVal = N.Val->getOperand(0);
701 // Okay, we know that we have a scale by now. However, if the scaled
702 // value is an add of something and a constant, we can fold the
703 // constant into the disp field here.
704 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
705 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
706 Reg = MulVal.Val->getOperand(0);
707 ConstantSDNode *AddVal =
708 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
709 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
713 Reg = N.Val->getOperand(0);
715 Reg = N.Val->getOperand(0);
718 AM.IndexReg = AM.Base.Reg = Reg;
726 X86ISelAddressMode Backup = AM;
727 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
728 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
731 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
732 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
739 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
741 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
742 X86ISelAddressMode Backup = AM;
743 // Start with the LHS as an addr mode.
744 if (!MatchAddress(N.getOperand(0), AM, false) &&
745 // Address could not have picked a GV address for the displacement.
747 // On x86-64, the resultant disp must fit in 32-bits.
748 isInt32(AM.Disp + CN->getSignExtended()) &&
749 // Check to see if the LHS & C is zero.
750 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
751 AM.Disp += CN->getValue();
760 // Is the base register already occupied?
761 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
762 // If so, check to see if the scale index register is set.
763 if (AM.IndexReg.Val == 0) {
769 // Otherwise, we cannot select it.
773 // Default, generate it as a register.
774 AM.BaseType = X86ISelAddressMode::RegBase;
779 /// SelectAddr - returns true if it is able pattern match an addressing mode.
780 /// It returns the operands which make up the maximal addressing mode it can
781 /// match by reference.
782 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
783 SDOperand &Scale, SDOperand &Index,
785 X86ISelAddressMode AM;
786 if (MatchAddress(N, AM))
789 MVT::ValueType VT = N.getValueType();
790 if (AM.BaseType == X86ISelAddressMode::RegBase) {
791 if (!AM.Base.Reg.Val)
792 AM.Base.Reg = CurDAG->getRegister(0, VT);
795 if (!AM.IndexReg.Val)
796 AM.IndexReg = CurDAG->getRegister(0, VT);
798 getAddressOperands(AM, Base, Scale, Index, Disp);
802 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
804 static inline bool isZeroNode(SDOperand Elt) {
805 return ((isa<ConstantSDNode>(Elt) &&
806 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
807 (isa<ConstantFPSDNode>(Elt) &&
808 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
812 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
813 /// match a load whose top elements are either undef or zeros. The load flavor
814 /// is derived from the type of N, which is either v4f32 or v2f64.
815 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
816 SDOperand N, SDOperand &Base,
817 SDOperand &Scale, SDOperand &Index,
818 SDOperand &Disp, SDOperand &InChain,
819 SDOperand &OutChain) {
820 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
821 InChain = N.getOperand(0).getValue(1);
822 if (ISD::isNON_EXTLoad(InChain.Val) &&
823 InChain.getValue(0).hasOneUse() &&
825 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
826 LoadSDNode *LD = cast<LoadSDNode>(InChain);
827 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
829 OutChain = LD->getChain();
834 // Also handle the case where we explicitly require zeros in the top
835 // elements. This is a vector shuffle from the zero vector.
836 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
837 N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
838 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
839 N.getOperand(1).Val->hasOneUse() &&
840 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
841 N.getOperand(1).getOperand(0).hasOneUse()) {
842 // Check to see if the BUILD_VECTOR is building a zero vector.
843 SDOperand BV = N.getOperand(0);
844 for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
845 if (!isZeroNode(BV.getOperand(i)) &&
846 BV.getOperand(i).getOpcode() != ISD::UNDEF)
847 return false; // Not a zero/undef vector.
848 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
850 unsigned VecWidth = BV.getNumOperands();
851 SDOperand ShufMask = N.getOperand(2);
852 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
854 if (C->getValue() == VecWidth) {
855 for (unsigned i = 1; i != VecWidth; ++i) {
856 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
859 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
860 if (C->getValue() >= VecWidth) return false;
865 // Okay, this is a zero extending load. Fold it.
866 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
867 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
869 OutChain = LD->getChain();
870 InChain = SDOperand(LD, 1);
878 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
879 /// mode it matches can be cost effectively emitted as an LEA instruction.
880 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
881 SDOperand &Base, SDOperand &Scale,
882 SDOperand &Index, SDOperand &Disp) {
883 X86ISelAddressMode AM;
884 if (MatchAddress(N, AM))
887 MVT::ValueType VT = N.getValueType();
888 unsigned Complexity = 0;
889 if (AM.BaseType == X86ISelAddressMode::RegBase)
893 AM.Base.Reg = CurDAG->getRegister(0, VT);
894 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
900 AM.IndexReg = CurDAG->getRegister(0, VT);
902 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
907 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
908 // to a LEA. This is determined with some expermentation but is by no means
909 // optimal (especially for code size consideration). LEA is nice because of
910 // its three-address nature. Tweak the cost function again when we can run
911 // convertToThreeAddress() at register allocation time.
912 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
913 // For X86-64, we should always use lea to materialize RIP relative
915 if (Subtarget->is64Bit())
921 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
924 if (Complexity > 2) {
925 getAddressOperands(AM, Base, Scale, Index, Disp);
931 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
932 SDOperand &Base, SDOperand &Scale,
933 SDOperand &Index, SDOperand &Disp) {
934 if (ISD::isNON_EXTLoad(N.Val) &&
936 CanBeFoldedBy(N.Val, P.Val, P.Val))
937 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
941 /// getGlobalBaseReg - Output the instructions required to put the
942 /// base address to use for accessing globals into a register.
944 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
945 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
946 if (!GlobalBaseReg) {
947 // Insert the set of GlobalBaseReg into the first MBB of the function
948 MachineBasicBlock &FirstMBB = BB->getParent()->front();
949 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
950 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
951 unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
953 const TargetInstrInfo *TII = TM.getInstrInfo();
954 BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
955 BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
957 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
958 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
959 if (TM.getRelocationModel() == Reloc::PIC_ &&
960 Subtarget->isPICStyleGOT()) {
961 GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
962 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
964 addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
970 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
973 static SDNode *FindCallStartFromCall(SDNode *Node) {
974 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
975 assert(Node->getOperand(0).getValueType() == MVT::Other &&
976 "Node doesn't have a token chain argument!");
977 return FindCallStartFromCall(Node->getOperand(0).Val);
980 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
981 SDNode *Node = N.Val;
982 MVT::ValueType NVT = Node->getValueType(0);
984 unsigned Opcode = Node->getOpcode();
987 DOUT << std::string(Indent, ' ') << "Selecting: ";
988 DEBUG(Node->dump(CurDAG));
993 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
995 DOUT << std::string(Indent-2, ' ') << "== ";
996 DEBUG(Node->dump(CurDAG));
1000 return NULL; // Already selected.
1005 case X86ISD::GlobalBaseReg:
1006 return getGlobalBaseReg();
1009 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1010 // code and is matched first so to prevent it from being turned into
1012 // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1013 MVT::ValueType PtrVT = TLI.getPointerTy();
1014 SDOperand N0 = N.getOperand(0);
1015 SDOperand N1 = N.getOperand(1);
1016 if (N.Val->getValueType(0) == PtrVT &&
1017 N0.getOpcode() == X86ISD::Wrapper &&
1018 N1.getOpcode() == ISD::Constant) {
1019 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1021 // TODO: handle ExternalSymbolSDNode.
1022 if (GlobalAddressSDNode *G =
1023 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1024 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1025 G->getOffset() + Offset);
1026 } else if (ConstantPoolSDNode *CP =
1027 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1028 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1030 CP->getOffset()+Offset);
1034 if (Subtarget->is64Bit()) {
1035 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1036 CurDAG->getRegister(0, PtrVT), C };
1037 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1039 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1043 // Other cases are handled by auto-generated code.
1049 if (Opcode == ISD::MULHU)
1051 default: assert(0 && "Unsupported VT!");
1052 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1053 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1054 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1055 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1059 default: assert(0 && "Unsupported VT!");
1060 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1061 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1062 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1063 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1066 unsigned LoReg, HiReg;
1068 default: assert(0 && "Unsupported VT!");
1069 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1070 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1071 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1072 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1075 SDOperand N0 = Node->getOperand(0);
1076 SDOperand N1 = Node->getOperand(1);
1078 bool foldedLoad = false;
1079 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1080 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1081 // MULHU and MULHS are commmutative
1083 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1085 N0 = Node->getOperand(1);
1086 N1 = Node->getOperand(0);
1092 Chain = N1.getOperand(0);
1093 AddToISelQueue(Chain);
1095 Chain = CurDAG->getEntryNode();
1097 SDOperand InFlag(0, 0);
1099 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1101 InFlag = Chain.getValue(1);
1104 AddToISelQueue(Tmp0);
1105 AddToISelQueue(Tmp1);
1106 AddToISelQueue(Tmp2);
1107 AddToISelQueue(Tmp3);
1108 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1110 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1111 Chain = SDOperand(CNode, 0);
1112 InFlag = SDOperand(CNode, 1);
1116 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1119 SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1120 ReplaceUses(N.getValue(0), Result);
1122 ReplaceUses(N1.getValue(1), Result.getValue(1));
1125 DOUT << std::string(Indent-2, ' ') << "=> ";
1126 DEBUG(Result.Val->dump(CurDAG));
1137 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1138 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1141 default: assert(0 && "Unsupported VT!");
1142 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1143 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1144 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1145 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1149 default: assert(0 && "Unsupported VT!");
1150 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1151 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1152 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1153 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1156 unsigned LoReg, HiReg;
1157 unsigned ClrOpcode, SExtOpcode;
1159 default: assert(0 && "Unsupported VT!");
1161 LoReg = X86::AL; HiReg = X86::AH;
1163 SExtOpcode = X86::CBW;
1166 LoReg = X86::AX; HiReg = X86::DX;
1167 ClrOpcode = X86::MOV16r0;
1168 SExtOpcode = X86::CWD;
1171 LoReg = X86::EAX; HiReg = X86::EDX;
1172 ClrOpcode = X86::MOV32r0;
1173 SExtOpcode = X86::CDQ;
1176 LoReg = X86::RAX; HiReg = X86::RDX;
1177 ClrOpcode = X86::MOV64r0;
1178 SExtOpcode = X86::CQO;
1182 SDOperand N0 = Node->getOperand(0);
1183 SDOperand N1 = Node->getOperand(1);
1184 SDOperand InFlag(0, 0);
1185 if (NVT == MVT::i8 && !isSigned) {
1186 // Special case for div8, just use a move with zero extension to AX to
1187 // clear the upper 8 bits (AH).
1188 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1189 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1190 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1191 AddToISelQueue(N0.getOperand(0));
1192 AddToISelQueue(Tmp0);
1193 AddToISelQueue(Tmp1);
1194 AddToISelQueue(Tmp2);
1195 AddToISelQueue(Tmp3);
1197 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1199 Chain = Move.getValue(1);
1200 ReplaceUses(N0.getValue(1), Chain);
1204 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1205 Chain = CurDAG->getEntryNode();
1207 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1208 InFlag = Chain.getValue(1);
1212 CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1213 InFlag).getValue(1);
1215 // Sign extend the low part into the high part.
1217 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1219 // Zero out the high part, effectively zero extending the input.
1220 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1221 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1222 InFlag).getValue(1);
1226 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1227 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1229 AddToISelQueue(N1.getOperand(0));
1230 AddToISelQueue(Tmp0);
1231 AddToISelQueue(Tmp1);
1232 AddToISelQueue(Tmp2);
1233 AddToISelQueue(Tmp3);
1234 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1236 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1237 Chain = SDOperand(CNode, 0);
1238 InFlag = SDOperand(CNode, 1);
1241 Chain = CurDAG->getEntryNode();
1243 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1247 CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1248 ReplaceUses(N.getValue(0), Result);
1250 ReplaceUses(N1.getValue(1), Result.getValue(1));
1253 DOUT << std::string(Indent-2, ' ') << "=> ";
1254 DEBUG(Result.Val->dump(CurDAG));
1262 case ISD::TRUNCATE: {
1263 if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1266 switch (Node->getOperand(0).getValueType()) {
1267 default: assert(0 && "Unknown truncate!");
1269 Opc = X86::MOV16to16_;
1271 Opc2 = X86::TRUNC_16_to8;
1274 Opc = X86::MOV32to32_;
1276 Opc2 = X86::TRUNC_32_to8;
1280 AddToISelQueue(Node->getOperand(0));
1282 SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1283 SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1286 DOUT << std::string(Indent-2, ' ') << "=> ";
1287 DEBUG(ResNode->dump(CurDAG));
1298 SDNode *ResNode = SelectCode(N);
1301 DOUT << std::string(Indent-2, ' ') << "=> ";
1302 if (ResNode == NULL || ResNode == N.Val)
1303 DEBUG(N.Val->dump(CurDAG));
1305 DEBUG(ResNode->dump(CurDAG));
1313 bool X86DAGToDAGISel::
1314 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1315 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1316 SDOperand Op0, Op1, Op2, Op3;
1317 switch (ConstraintCode) {
1318 case 'o': // offsetable ??
1319 case 'v': // not offsetable ??
1320 default: return true;
1322 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1327 OutOps.push_back(Op0);
1328 OutOps.push_back(Op1);
1329 OutOps.push_back(Op2);
1330 OutOps.push_back(Op3);
1331 AddToISelQueue(Op0);
1332 AddToISelQueue(Op1);
1333 AddToISelQueue(Op2);
1334 AddToISelQueue(Op3);
1338 /// createX86ISelDag - This pass converts a legalized DAG into a
1339 /// X86-specific DAG, ready for instruction scheduling.
1341 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1342 return new X86DAGToDAGISel(TM, Fast);