1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "X86MachineFunctionInfo.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Type.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Streams.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
45 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
46 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
48 //===----------------------------------------------------------------------===//
49 // Pattern Matcher Implementation
50 //===----------------------------------------------------------------------===//
53 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
54 /// SDValue's instead of register numbers for the leaves of the matched
56 struct X86ISelAddressMode {
62 struct { // This is really a union, discriminated by BaseType!
67 bool isRIPRel; // RIP as base?
75 unsigned Align; // CP alignment.
78 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
79 GV(0), CP(0), ES(0), JT(-1), Align(0) {
82 cerr << "X86ISelAddressMode " << this << "\n";
83 cerr << "Base.Reg "; if (Base.Reg.Val!=0) Base.Reg.Val->dump();
85 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
86 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
87 cerr << "IndexReg "; if (IndexReg.Val!=0) IndexReg.Val->dump();
89 cerr << " Disp " << Disp << "\n";
90 cerr << "GV "; if (GV) GV->dump();
92 cerr << " CP "; if (CP) CP->dump();
95 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
96 cerr << " JT" << JT << " Align" << Align << "\n";
102 //===--------------------------------------------------------------------===//
103 /// ISel - X86 specific code to select X86 machine instructions for
104 /// SelectionDAG operations.
106 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
107 /// ContainsFPCode - Every instruction we select that uses or defines a FP
108 /// register should set this to true.
111 /// TM - Keep a reference to X86TargetMachine.
113 X86TargetMachine &TM;
115 /// X86Lowering - This object fully describes how to lower LLVM code to an
116 /// X86-specific SelectionDAG.
117 X86TargetLowering X86Lowering;
119 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
120 /// make the right decision when generating code for different targets.
121 const X86Subtarget *Subtarget;
123 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
125 unsigned GlobalBaseReg;
127 /// CurBB - Current BB being isel'd.
129 MachineBasicBlock *CurBB;
132 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
133 : SelectionDAGISel(X86Lowering, fast),
134 ContainsFPCode(false), TM(tm),
135 X86Lowering(*TM.getTargetLowering()),
136 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
138 virtual bool runOnFunction(Function &Fn) {
139 // Make sure we re-emit a set of the global base reg if necessary
141 return SelectionDAGISel::runOnFunction(Fn);
144 virtual const char *getPassName() const {
145 return "X86 DAG->DAG Instruction Selection";
148 /// InstructionSelect - This callback is invoked by
149 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
150 virtual void InstructionSelect(SelectionDAG &DAG);
152 /// InstructionSelectPostProcessing - Post processing of selected and
153 /// scheduled basic blocks.
154 virtual void InstructionSelectPostProcessing();
156 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
158 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
160 // Include the pieces autogenerated from the target description.
161 #include "X86GenDAGISel.inc"
164 SDNode *Select(SDValue N);
166 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
167 bool isRoot = true, unsigned Depth = 0);
168 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
169 bool isRoot, unsigned Depth);
170 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
171 SDValue &Scale, SDValue &Index, SDValue &Disp);
172 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
173 SDValue &Scale, SDValue &Index, SDValue &Disp);
174 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
175 SDValue N, SDValue &Base, SDValue &Scale,
176 SDValue &Index, SDValue &Disp,
177 SDValue &InChain, SDValue &OutChain);
178 bool TryFoldLoad(SDValue P, SDValue N,
179 SDValue &Base, SDValue &Scale,
180 SDValue &Index, SDValue &Disp);
181 void PreprocessForRMW(SelectionDAG &DAG);
182 void PreprocessForFPConvert(SelectionDAG &DAG);
184 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
185 /// inline asm expressions.
186 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
188 std::vector<SDValue> &OutOps,
191 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
193 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
194 SDValue &Scale, SDValue &Index,
196 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
197 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
199 Scale = getI8Imm(AM.Scale);
201 // These are 32-bit even in 64-bit mode since RIP relative offset
204 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
206 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
208 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
209 else if (AM.JT != -1)
210 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
212 Disp = getI32Imm(AM.Disp);
215 /// getI8Imm - Return a target constant with the specified value, of type
217 inline SDValue getI8Imm(unsigned Imm) {
218 return CurDAG->getTargetConstant(Imm, MVT::i8);
221 /// getI16Imm - Return a target constant with the specified value, of type
223 inline SDValue getI16Imm(unsigned Imm) {
224 return CurDAG->getTargetConstant(Imm, MVT::i16);
227 /// getI32Imm - Return a target constant with the specified value, of type
229 inline SDValue getI32Imm(unsigned Imm) {
230 return CurDAG->getTargetConstant(Imm, MVT::i32);
233 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
234 /// base register. Return the virtual register that holds this value.
235 SDNode *getGlobalBaseReg();
237 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
238 /// truncate of the specified operand to i8. This can be done with tablegen,
239 /// except that this code uses MVT::Flag in a tricky way that happens to
240 /// improve scheduling in some cases.
241 SDNode *getTruncateTo8Bit(SDValue N0);
249 /// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
251 static SDNode *findFlagUse(SDNode *N) {
252 unsigned FlagResNo = N->getNumValues()-1;
253 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
255 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
256 SDValue Op = User->getOperand(i);
257 if (Op.Val == N && Op.ResNo == FlagResNo)
264 /// findNonImmUse - Return true by reference in "found" if "Use" is an
265 /// non-immediate use of "Def". This function recursively traversing
266 /// up the operand chain ignoring certain nodes.
267 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
268 SDNode *Root, SDNode *Skip, bool &found,
269 SmallPtrSet<SDNode*, 16> &Visited) {
271 Use->getNodeId() > Def->getNodeId() ||
272 !Visited.insert(Use))
275 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
276 SDNode *N = Use->getOperand(i).Val;
281 continue; // We are not looking for immediate use.
283 // Must be a chain reading node where it is possible to reach its own
284 // chain operand through a path started from another operand.
285 assert(Use->getOpcode() == ISD::STORE ||
286 Use->getOpcode() == X86ISD::CMP ||
287 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
288 Use->getOpcode() == ISD::INTRINSIC_VOID);
295 // Traverse up the operand chain.
296 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
300 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
301 /// be reached. Return true if that's the case. However, ignore direct uses
302 /// by ImmedUse (which would be U in the example illustrated in
303 /// CanBeFoldedBy) and by Root (which can happen in the store case).
304 /// FIXME: to be really generic, we should allow direct use by any node
305 /// that is being folded. But realisticly since we only fold loads which
306 /// have one non-chain use, we only need to watch out for load/op/store
307 /// and load/op/cmp case where the root (store / cmp) may reach the load via
308 /// its chain operand.
309 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
310 SDNode *Skip = NULL) {
311 SmallPtrSet<SDNode*, 16> Visited;
313 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
318 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
319 if (Fast) return false;
321 // If U use can somehow reach N through another path then U can't fold N or
322 // it will create a cycle. e.g. In the following diagram, U can reach N
323 // through X. If N is folded into into U, then X is both a predecessor and
334 if (isNonImmUse(Root, N, U))
337 // If U produces a flag, then it gets (even more) interesting. Since it
338 // would have been "glued" together with its flag use, we need to check if
351 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
352 // NU), then TF is a predecessor of FU and a successor of NU. But since
353 // NU and FU are flagged together, this effectively creates a cycle.
354 bool HasFlagUse = false;
355 MVT VT = Root->getValueType(Root->getNumValues()-1);
356 while ((VT == MVT::Flag && !Root->use_empty())) {
357 SDNode *FU = findFlagUse(Root);
364 VT = Root->getValueType(Root->getNumValues()-1);
368 return !isNonImmUse(Root, N, Root, U);
372 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
373 /// and move load below the TokenFactor. Replace store's chain operand with
374 /// load's chain result.
375 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDValue Load,
376 SDValue Store, SDValue TF) {
377 std::vector<SDValue> Ops;
378 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
379 if (Load.Val == TF.Val->getOperand(i).Val)
380 Ops.push_back(Load.Val->getOperand(0));
382 Ops.push_back(TF.Val->getOperand(i));
383 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
384 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
385 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
386 Store.getOperand(2), Store.getOperand(3));
389 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
391 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
393 if (N.getOpcode() == ISD::BIT_CONVERT)
396 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
397 if (!LD || LD->isVolatile())
399 if (LD->getAddressingMode() != ISD::UNINDEXED)
402 ISD::LoadExtType ExtType = LD->getExtensionType();
403 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
407 N.getOperand(1) == Address &&
408 N.Val->isOperandOf(Chain.Val)) {
415 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
416 /// This is only run if not in -fast mode (aka -O0).
417 /// This allows the instruction selector to pick more read-modify-write
418 /// instructions. This is a common case:
428 /// [TokenFactor] [Op]
435 /// The fact the store's chain operand != load's chain will prevent the
436 /// (store (op (load))) instruction from being selected. We can transform it to:
455 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
456 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
457 E = DAG.allnodes_end(); I != E; ++I) {
458 if (!ISD::isNON_TRUNCStore(I))
460 SDValue Chain = I->getOperand(0);
461 if (Chain.Val->getOpcode() != ISD::TokenFactor)
464 SDValue N1 = I->getOperand(1);
465 SDValue N2 = I->getOperand(2);
466 if ((N1.getValueType().isFloatingPoint() &&
467 !N1.getValueType().isVector()) ||
473 unsigned Opcode = N1.Val->getOpcode();
482 case ISD::VECTOR_SHUFFLE: {
483 SDValue N10 = N1.getOperand(0);
484 SDValue N11 = N1.getOperand(1);
485 RModW = isRMWLoad(N10, Chain, N2, Load);
487 RModW = isRMWLoad(N11, Chain, N2, Load);
500 SDValue N10 = N1.getOperand(0);
501 RModW = isRMWLoad(N10, Chain, N2, Load);
507 MoveBelowTokenFactor(DAG, Load, SDValue(I, 0), Chain);
514 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
515 /// nodes that target the FP stack to be store and load to the stack. This is a
516 /// gross hack. We would like to simply mark these as being illegal, but when
517 /// we do that, legalize produces these when it expands calls, then expands
518 /// these in the same legalize pass. We would like dag combine to be able to
519 /// hack on these between the call expansion and the node legalization. As such
520 /// this pass basically does "really late" legalization of these inline with the
522 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
523 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
524 E = DAG.allnodes_end(); I != E; ) {
525 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
526 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
529 // If the source and destination are SSE registers, then this is a legal
530 // conversion that should not be lowered.
531 MVT SrcVT = N->getOperand(0).getValueType();
532 MVT DstVT = N->getValueType(0);
533 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
534 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
535 if (SrcIsSSE && DstIsSSE)
538 if (!SrcIsSSE && !DstIsSSE) {
539 // If this is an FPStack extension, it is a noop.
540 if (N->getOpcode() == ISD::FP_EXTEND)
542 // If this is a value-preserving FPStack truncation, it is a noop.
543 if (N->getConstantOperandVal(1))
547 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
548 // FPStack has extload and truncstore. SSE can fold direct loads into other
549 // operations. Based on this, decide what we want to do.
551 if (N->getOpcode() == ISD::FP_ROUND)
552 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
554 MemVT = SrcIsSSE ? SrcVT : DstVT;
556 SDValue MemTmp = DAG.CreateStackTemporary(MemVT);
558 // FIXME: optimize the case where the src/dest is a load or store?
559 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
560 MemTmp, NULL, 0, MemVT);
561 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
564 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
565 // extload we created. This will cause general havok on the dag because
566 // anything below the conversion could be folded into other existing nodes.
567 // To avoid invalidating 'I', back it up to the convert node.
569 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
571 // Now that we did that, the node is dead. Increment the iterator to the
572 // next node to process, then delete N.
578 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
579 /// when it has created a SelectionDAG for us to codegen.
580 void X86DAGToDAGISel::InstructionSelect(SelectionDAG &DAG) {
581 CurBB = BB; // BB can change as result of isel.
585 PreprocessForRMW(DAG);
587 // FIXME: This should only happen when not -fast.
588 PreprocessForFPConvert(DAG);
590 // Codegen the basic block.
592 DOUT << "===== Instruction selection begins:\n";
595 DAG.setRoot(SelectRoot(DAG.getRoot()));
597 DOUT << "===== Instruction selection ends:\n";
600 DAG.RemoveDeadNodes();
603 void X86DAGToDAGISel::InstructionSelectPostProcessing() {
604 // If we are emitting FP stack code, scan the basic block to determine if this
605 // block defines any FP values. If so, put an FP_REG_KILL instruction before
606 // the terminator of the block.
608 // Note that FP stack instructions are used in all modes for long double,
609 // so we always need to do this check.
610 // Also note that it's possible for an FP stack register to be live across
611 // an instruction that produces multiple basic blocks (SSE CMOV) so we
612 // must check all the generated basic blocks.
614 // Scan all of the machine instructions in these MBBs, checking for FP
615 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
616 MachineFunction::iterator MBBI = CurBB;
617 MachineFunction::iterator EndMBB = BB; ++EndMBB;
618 for (; MBBI != EndMBB; ++MBBI) {
619 MachineBasicBlock *MBB = MBBI;
621 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
622 // before the return.
624 MachineBasicBlock::iterator EndI = MBB->end();
626 if (EndI->getDesc().isReturn())
630 bool ContainsFPCode = false;
631 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
632 !ContainsFPCode && I != E; ++I) {
633 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
634 const TargetRegisterClass *clas;
635 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
636 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
637 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
638 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
639 X86::RFP32RegisterClass ||
640 clas == X86::RFP64RegisterClass ||
641 clas == X86::RFP80RegisterClass)) {
642 ContainsFPCode = true;
648 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
649 // a copy of the input value in this block. In SSE mode, we only care about
651 if (!ContainsFPCode) {
652 // Final check, check LLVM BB's that are successors to the LLVM BB
653 // corresponding to BB for FP PHI nodes.
654 const BasicBlock *LLVMBB = BB->getBasicBlock();
656 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
657 !ContainsFPCode && SI != E; ++SI) {
658 for (BasicBlock::const_iterator II = SI->begin();
659 (PN = dyn_cast<PHINode>(II)); ++II) {
660 if (PN->getType()==Type::X86_FP80Ty ||
661 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
662 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
663 ContainsFPCode = true;
669 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
670 if (ContainsFPCode) {
671 BuildMI(*MBB, MBBI->getFirstTerminator(),
672 TM.getInstrInfo()->get(X86::FP_REG_KILL));
678 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
679 /// the main function.
680 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
681 MachineFrameInfo *MFI) {
682 const TargetInstrInfo *TII = TM.getInstrInfo();
683 if (Subtarget->isTargetCygMing())
684 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
687 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
688 // If this is main, emit special code for main.
689 MachineBasicBlock *BB = MF.begin();
690 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
691 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
694 /// MatchAddress - Add the specified node to the specified addressing mode,
695 /// returning true if it cannot be done. This just pattern matches for the
697 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
698 bool isRoot, unsigned Depth) {
699 DOUT << "MatchAddress: "; DEBUG(AM.dump());
702 return MatchAddressBase(N, AM, isRoot, Depth);
704 // RIP relative addressing: %rip + 32-bit displacement!
706 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
707 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
708 if (isInt32(AM.Disp + Val)) {
716 int id = N.Val->getNodeId();
717 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
719 switch (N.getOpcode()) {
721 case ISD::Constant: {
722 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
723 if (isInt32(AM.Disp + Val)) {
730 case X86ISD::Wrapper: {
731 DOUT << "Wrapper: 64bit " << Subtarget->is64Bit();
732 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
733 DOUT << "AlreadySelected " << AlreadySelected << "\n";
734 bool is64Bit = Subtarget->is64Bit();
735 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
736 // Also, base and index reg must be 0 in order to use rip as base.
737 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
738 AM.Base.Reg.Val || AM.IndexReg.Val))
740 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
742 // If value is available in a register both base and index components have
743 // been picked, we can't fit the result available in the register in the
744 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
745 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
746 SDValue N0 = N.getOperand(0);
747 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
748 GlobalValue *GV = G->getGlobal();
750 AM.Disp += G->getOffset();
751 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
752 Subtarget->isPICStyleRIPRel();
754 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
755 AM.CP = CP->getConstVal();
756 AM.Align = CP->getAlignment();
757 AM.Disp += CP->getOffset();
758 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
759 Subtarget->isPICStyleRIPRel();
761 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
762 AM.ES = S->getSymbol();
763 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
764 Subtarget->isPICStyleRIPRel();
766 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
767 AM.JT = J->getIndex();
768 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
769 Subtarget->isPICStyleRIPRel();
776 case ISD::FrameIndex:
777 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
778 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
779 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
785 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
788 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
789 unsigned Val = CN->getValue();
790 if (Val == 1 || Val == 2 || Val == 3) {
792 SDValue ShVal = N.Val->getOperand(0);
794 // Okay, we know that we have a scale by now. However, if the scaled
795 // value is an add of something and a constant, we can fold the
796 // constant into the disp field here.
797 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
798 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
799 AM.IndexReg = ShVal.Val->getOperand(0);
800 ConstantSDNode *AddVal =
801 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
802 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
817 // A mul_lohi where we need the low part can be folded as a plain multiply.
818 if (N.ResNo != 0) break;
821 // X*[3,5,9] -> X+X*[2,4,8]
822 if (!AlreadySelected &&
823 AM.BaseType == X86ISelAddressMode::RegBase &&
824 AM.Base.Reg.Val == 0 &&
825 AM.IndexReg.Val == 0 &&
827 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
828 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
829 AM.Scale = unsigned(CN->getValue())-1;
831 SDValue MulVal = N.Val->getOperand(0);
834 // Okay, we know that we have a scale by now. However, if the scaled
835 // value is an add of something and a constant, we can fold the
836 // constant into the disp field here.
837 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
838 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
839 Reg = MulVal.Val->getOperand(0);
840 ConstantSDNode *AddVal =
841 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
842 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
846 Reg = N.Val->getOperand(0);
848 Reg = N.Val->getOperand(0);
851 AM.IndexReg = AM.Base.Reg = Reg;
858 if (!AlreadySelected) {
859 X86ISelAddressMode Backup = AM;
860 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
861 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
864 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
865 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
872 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
873 if (AlreadySelected) break;
875 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
876 X86ISelAddressMode Backup = AM;
877 // Start with the LHS as an addr mode.
878 if (!MatchAddress(N.getOperand(0), AM, false) &&
879 // Address could not have picked a GV address for the displacement.
881 // On x86-64, the resultant disp must fit in 32-bits.
882 isInt32(AM.Disp + CN->getSignExtended()) &&
883 // Check to see if the LHS & C is zero.
884 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
885 AM.Disp += CN->getValue();
893 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
894 // allows us to fold the shift into this addressing mode.
895 if (AlreadySelected) break;
896 SDValue Shift = N.getOperand(0);
897 if (Shift.getOpcode() != ISD::SHL) break;
899 // Scale must not be used already.
900 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
902 // Not when RIP is used as the base.
903 if (AM.isRIPRel) break;
905 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
906 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
907 if (!C1 || !C2) break;
909 // Not likely to be profitable if either the AND or SHIFT node has more
910 // than one use (unless all uses are for address computation). Besides,
911 // isel mechanism requires their node ids to be reused.
912 if (!N.hasOneUse() || !Shift.hasOneUse())
915 // Verify that the shift amount is something we can fold.
916 unsigned ShiftCst = C1->getValue();
917 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
920 // Get the new AND mask, this folds to a constant.
921 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
922 SDValue(C2, 0), SDValue(C1, 0));
923 SDValue NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
924 Shift.getOperand(0), NewANDMask);
925 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
926 NewAND.Val->setNodeId(N.Val->getNodeId());
928 AM.Scale = 1 << ShiftCst;
929 AM.IndexReg = NewAND;
934 return MatchAddressBase(N, AM, isRoot, Depth);
937 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
938 /// specified addressing mode without any further recursion.
939 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
940 bool isRoot, unsigned Depth) {
941 // Is the base register already occupied?
942 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
943 // If so, check to see if the scale index register is set.
944 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
950 // Otherwise, we cannot select it.
954 // Default, generate it as a register.
955 AM.BaseType = X86ISelAddressMode::RegBase;
960 /// SelectAddr - returns true if it is able pattern match an addressing mode.
961 /// It returns the operands which make up the maximal addressing mode it can
962 /// match by reference.
963 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
964 SDValue &Scale, SDValue &Index,
966 X86ISelAddressMode AM;
967 if (MatchAddress(N, AM))
970 MVT VT = N.getValueType();
971 if (AM.BaseType == X86ISelAddressMode::RegBase) {
972 if (!AM.Base.Reg.Val)
973 AM.Base.Reg = CurDAG->getRegister(0, VT);
976 if (!AM.IndexReg.Val)
977 AM.IndexReg = CurDAG->getRegister(0, VT);
979 getAddressOperands(AM, Base, Scale, Index, Disp);
983 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
985 static inline bool isZeroNode(SDValue Elt) {
986 return ((isa<ConstantSDNode>(Elt) &&
987 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
988 (isa<ConstantFPSDNode>(Elt) &&
989 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
993 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
994 /// match a load whose top elements are either undef or zeros. The load flavor
995 /// is derived from the type of N, which is either v4f32 or v2f64.
996 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
997 SDValue N, SDValue &Base,
998 SDValue &Scale, SDValue &Index,
999 SDValue &Disp, SDValue &InChain,
1000 SDValue &OutChain) {
1001 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1002 InChain = N.getOperand(0).getValue(1);
1003 if (ISD::isNON_EXTLoad(InChain.Val) &&
1004 InChain.getValue(0).hasOneUse() &&
1006 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
1007 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1008 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1010 OutChain = LD->getChain();
1015 // Also handle the case where we explicitly require zeros in the top
1016 // elements. This is a vector shuffle from the zero vector.
1017 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
1018 // Check to see if the top elements are all zeros (or bitcast of zeros).
1019 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1020 N.getOperand(0).Val->hasOneUse() &&
1021 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
1022 N.getOperand(0).getOperand(0).hasOneUse()) {
1023 // Okay, this is a zero extending load. Fold it.
1024 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1025 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1027 OutChain = LD->getChain();
1028 InChain = SDValue(LD, 1);
1035 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1036 /// mode it matches can be cost effectively emitted as an LEA instruction.
1037 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1038 SDValue &Base, SDValue &Scale,
1039 SDValue &Index, SDValue &Disp) {
1040 X86ISelAddressMode AM;
1041 if (MatchAddress(N, AM))
1044 MVT VT = N.getValueType();
1045 unsigned Complexity = 0;
1046 if (AM.BaseType == X86ISelAddressMode::RegBase)
1047 if (AM.Base.Reg.Val)
1050 AM.Base.Reg = CurDAG->getRegister(0, VT);
1051 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1054 if (AM.IndexReg.Val)
1057 AM.IndexReg = CurDAG->getRegister(0, VT);
1059 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1064 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1065 // to a LEA. This is determined with some expermentation but is by no means
1066 // optimal (especially for code size consideration). LEA is nice because of
1067 // its three-address nature. Tweak the cost function again when we can run
1068 // convertToThreeAddress() at register allocation time.
1069 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1070 // For X86-64, we should always use lea to materialize RIP relative
1072 if (Subtarget->is64Bit())
1078 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1081 if (Complexity > 2) {
1082 getAddressOperands(AM, Base, Scale, Index, Disp);
1088 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1089 SDValue &Base, SDValue &Scale,
1090 SDValue &Index, SDValue &Disp) {
1091 if (ISD::isNON_EXTLoad(N.Val) &&
1093 CanBeFoldedBy(N.Val, P.Val, P.Val))
1094 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1098 /// getGlobalBaseReg - Output the instructions required to put the
1099 /// base address to use for accessing globals into a register.
1101 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1102 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1103 if (!GlobalBaseReg) {
1104 // Insert the set of GlobalBaseReg into the first MBB of the function
1105 MachineFunction *MF = BB->getParent();
1106 MachineBasicBlock &FirstMBB = MF->front();
1107 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1108 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1109 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1111 const TargetInstrInfo *TII = TM.getInstrInfo();
1112 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1113 // only used in JIT code emission as displacement to pc.
1114 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1116 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1117 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1118 if (TM.getRelocationModel() == Reloc::PIC_ &&
1119 Subtarget->isPICStyleGOT()) {
1120 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1121 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1122 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1128 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1131 static SDNode *FindCallStartFromCall(SDNode *Node) {
1132 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1133 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1134 "Node doesn't have a token chain argument!");
1135 return FindCallStartFromCall(Node->getOperand(0).Val);
1138 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1139 /// truncate of the specified operand to i8. This can be done with tablegen,
1140 /// except that this code uses MVT::Flag in a tricky way that happens to
1141 /// improve scheduling in some cases.
1142 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1143 assert(!Subtarget->is64Bit() &&
1144 "getTruncateTo8Bit is only needed on x86-32!");
1145 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1147 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1149 MVT N0VT = N0.getValueType();
1150 switch (N0VT.getSimpleVT()) {
1151 default: assert(0 && "Unknown truncate!");
1153 Opc = X86::MOV16to16_;
1156 Opc = X86::MOV32to32_;
1160 // The use of MVT::Flag here is not strictly accurate, but it helps
1161 // scheduling in some cases.
1162 N0 = SDValue(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
1163 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1164 MVT::i8, N0, SRIdx, N0.getValue(1));
1168 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1169 SDNode *Node = N.Val;
1170 MVT NVT = Node->getValueType(0);
1172 unsigned Opcode = Node->getOpcode();
1175 DOUT << std::string(Indent, ' ') << "Selecting: ";
1176 DEBUG(Node->dump(CurDAG));
1181 if (Node->isMachineOpcode()) {
1183 DOUT << std::string(Indent-2, ' ') << "== ";
1184 DEBUG(Node->dump(CurDAG));
1188 return NULL; // Already selected.
1193 case X86ISD::GlobalBaseReg:
1194 return getGlobalBaseReg();
1197 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1198 // code and is matched first so to prevent it from being turned into
1200 // In 64-bit small code size mode, use LEA to take advantage of
1201 // RIP-relative addressing.
1202 if (TM.getCodeModel() != CodeModel::Small)
1204 MVT PtrVT = TLI.getPointerTy();
1205 SDValue N0 = N.getOperand(0);
1206 SDValue N1 = N.getOperand(1);
1207 if (N.Val->getValueType(0) == PtrVT &&
1208 N0.getOpcode() == X86ISD::Wrapper &&
1209 N1.getOpcode() == ISD::Constant) {
1210 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1212 // TODO: handle ExternalSymbolSDNode.
1213 if (GlobalAddressSDNode *G =
1214 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1215 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1216 G->getOffset() + Offset);
1217 } else if (ConstantPoolSDNode *CP =
1218 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1219 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1221 CP->getOffset()+Offset);
1225 if (Subtarget->is64Bit()) {
1226 SDValue Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1227 CurDAG->getRegister(0, PtrVT), C };
1228 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1230 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1234 // Other cases are handled by auto-generated code.
1238 case ISD::SMUL_LOHI:
1239 case ISD::UMUL_LOHI: {
1240 SDValue N0 = Node->getOperand(0);
1241 SDValue N1 = Node->getOperand(1);
1243 bool isSigned = Opcode == ISD::SMUL_LOHI;
1245 switch (NVT.getSimpleVT()) {
1246 default: assert(0 && "Unsupported VT!");
1247 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1248 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1249 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1250 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1253 switch (NVT.getSimpleVT()) {
1254 default: assert(0 && "Unsupported VT!");
1255 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1256 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1257 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1258 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1261 unsigned LoReg, HiReg;
1262 switch (NVT.getSimpleVT()) {
1263 default: assert(0 && "Unsupported VT!");
1264 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1265 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1266 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1267 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1270 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1271 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1272 // multiplty is commmutative
1274 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1280 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1281 N0, SDValue()).getValue(1);
1284 AddToISelQueue(N1.getOperand(0));
1285 AddToISelQueue(Tmp0);
1286 AddToISelQueue(Tmp1);
1287 AddToISelQueue(Tmp2);
1288 AddToISelQueue(Tmp3);
1289 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1291 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1292 InFlag = SDValue(CNode, 1);
1293 // Update the chain.
1294 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1298 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1301 // Copy the low half of the result, if it is needed.
1302 if (!N.getValue(0).use_empty()) {
1303 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1304 LoReg, NVT, InFlag);
1305 InFlag = Result.getValue(2);
1306 ReplaceUses(N.getValue(0), Result);
1308 DOUT << std::string(Indent-2, ' ') << "=> ";
1309 DEBUG(Result.Val->dump(CurDAG));
1313 // Copy the high half of the result, if it is needed.
1314 if (!N.getValue(1).use_empty()) {
1316 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1317 // Prevent use of AH in a REX instruction by referencing AX instead.
1318 // Shift it down 8 bits.
1319 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1320 X86::AX, MVT::i16, InFlag);
1321 InFlag = Result.getValue(2);
1322 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1323 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1324 // Then truncate it down to i8.
1325 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1326 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1327 MVT::i8, Result, SRIdx), 0);
1329 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1330 HiReg, NVT, InFlag);
1331 InFlag = Result.getValue(2);
1333 ReplaceUses(N.getValue(1), Result);
1335 DOUT << std::string(Indent-2, ' ') << "=> ";
1336 DEBUG(Result.Val->dump(CurDAG));
1349 case ISD::UDIVREM: {
1350 SDValue N0 = Node->getOperand(0);
1351 SDValue N1 = Node->getOperand(1);
1353 bool isSigned = Opcode == ISD::SDIVREM;
1355 switch (NVT.getSimpleVT()) {
1356 default: assert(0 && "Unsupported VT!");
1357 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1358 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1359 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1360 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1363 switch (NVT.getSimpleVT()) {
1364 default: assert(0 && "Unsupported VT!");
1365 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1366 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1367 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1368 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1371 unsigned LoReg, HiReg;
1372 unsigned ClrOpcode, SExtOpcode;
1373 switch (NVT.getSimpleVT()) {
1374 default: assert(0 && "Unsupported VT!");
1376 LoReg = X86::AL; HiReg = X86::AH;
1378 SExtOpcode = X86::CBW;
1381 LoReg = X86::AX; HiReg = X86::DX;
1382 ClrOpcode = X86::MOV16r0;
1383 SExtOpcode = X86::CWD;
1386 LoReg = X86::EAX; HiReg = X86::EDX;
1387 ClrOpcode = X86::MOV32r0;
1388 SExtOpcode = X86::CDQ;
1391 LoReg = X86::RAX; HiReg = X86::RDX;
1392 ClrOpcode = X86::MOV64r0;
1393 SExtOpcode = X86::CQO;
1397 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1398 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1401 if (NVT == MVT::i8 && !isSigned) {
1402 // Special case for div8, just use a move with zero extension to AX to
1403 // clear the upper 8 bits (AH).
1404 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1405 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1406 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1407 AddToISelQueue(N0.getOperand(0));
1408 AddToISelQueue(Tmp0);
1409 AddToISelQueue(Tmp1);
1410 AddToISelQueue(Tmp2);
1411 AddToISelQueue(Tmp3);
1413 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1415 Chain = Move.getValue(1);
1416 ReplaceUses(N0.getValue(1), Chain);
1420 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1421 Chain = CurDAG->getEntryNode();
1423 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDValue());
1424 InFlag = Chain.getValue(1);
1428 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1429 LoReg, N0, SDValue()).getValue(1);
1431 // Sign extend the low part into the high part.
1433 SDValue(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1435 // Zero out the high part, effectively zero extending the input.
1436 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1437 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1438 ClrNode, InFlag).getValue(1);
1443 AddToISelQueue(N1.getOperand(0));
1444 AddToISelQueue(Tmp0);
1445 AddToISelQueue(Tmp1);
1446 AddToISelQueue(Tmp2);
1447 AddToISelQueue(Tmp3);
1448 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1450 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1451 InFlag = SDValue(CNode, 1);
1452 // Update the chain.
1453 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1457 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1460 // Copy the division (low) result, if it is needed.
1461 if (!N.getValue(0).use_empty()) {
1462 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1463 LoReg, NVT, InFlag);
1464 InFlag = Result.getValue(2);
1465 ReplaceUses(N.getValue(0), Result);
1467 DOUT << std::string(Indent-2, ' ') << "=> ";
1468 DEBUG(Result.Val->dump(CurDAG));
1472 // Copy the remainder (high) result, if it is needed.
1473 if (!N.getValue(1).use_empty()) {
1475 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1476 // Prevent use of AH in a REX instruction by referencing AX instead.
1477 // Shift it down 8 bits.
1478 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1479 X86::AX, MVT::i16, InFlag);
1480 InFlag = Result.getValue(2);
1481 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1482 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1483 // Then truncate it down to i8.
1484 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1485 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1486 MVT::i8, Result, SRIdx), 0);
1488 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1489 HiReg, NVT, InFlag);
1490 InFlag = Result.getValue(2);
1492 ReplaceUses(N.getValue(1), Result);
1494 DOUT << std::string(Indent-2, ' ') << "=> ";
1495 DEBUG(Result.Val->dump(CurDAG));
1507 case ISD::SIGN_EXTEND_INREG: {
1508 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1509 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1510 SDValue N0 = Node->getOperand(0);
1513 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1515 switch (NVT.getSimpleVT()) {
1516 default: assert(0 && "Unknown sign_extend_inreg!");
1518 Opc = X86::MOVSX16rr8;
1521 Opc = X86::MOVSX32rr8;
1525 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1528 DOUT << std::string(Indent-2, ' ') << "=> ";
1529 DEBUG(TruncOp.Val->dump(CurDAG));
1531 DOUT << std::string(Indent-2, ' ') << "=> ";
1532 DEBUG(ResNode->dump(CurDAG));
1541 case ISD::TRUNCATE: {
1542 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1543 SDValue Input = Node->getOperand(0);
1544 AddToISelQueue(Node->getOperand(0));
1545 SDNode *ResNode = getTruncateTo8Bit(Input);
1548 DOUT << std::string(Indent-2, ' ') << "=> ";
1549 DEBUG(ResNode->dump(CurDAG));
1558 case ISD::DECLARE: {
1559 // Handle DECLARE nodes here because the second operand may have been
1560 // wrapped in X86ISD::Wrapper.
1561 SDValue Chain = Node->getOperand(0);
1562 SDValue N1 = Node->getOperand(1);
1563 SDValue N2 = Node->getOperand(2);
1564 if (!isa<FrameIndexSDNode>(N1))
1566 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1567 if (N2.getOpcode() == ISD::ADD &&
1568 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1569 N2 = N2.getOperand(1);
1570 if (N2.getOpcode() == X86ISD::Wrapper &&
1571 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
1573 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1574 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1575 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1576 AddToISelQueue(Chain);
1577 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1578 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1579 MVT::Other, Ops, 3);
1585 SDNode *ResNode = SelectCode(N);
1588 DOUT << std::string(Indent-2, ' ') << "=> ";
1589 if (ResNode == NULL || ResNode == N.Val)
1590 DEBUG(N.Val->dump(CurDAG));
1592 DEBUG(ResNode->dump(CurDAG));
1600 bool X86DAGToDAGISel::
1601 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1602 std::vector<SDValue> &OutOps, SelectionDAG &DAG){
1603 SDValue Op0, Op1, Op2, Op3;
1604 switch (ConstraintCode) {
1605 case 'o': // offsetable ??
1606 case 'v': // not offsetable ??
1607 default: return true;
1609 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1614 OutOps.push_back(Op0);
1615 OutOps.push_back(Op1);
1616 OutOps.push_back(Op2);
1617 OutOps.push_back(Op3);
1618 AddToISelQueue(Op0);
1619 AddToISelQueue(Op1);
1620 AddToISelQueue(Op2);
1621 AddToISelQueue(Op3);
1625 /// createX86ISelDag - This pass converts a legalized DAG into a
1626 /// X86-specific DAG, ready for instruction scheduling.
1628 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1629 return new X86DAGToDAGISel(TM, Fast);