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/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
44 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
45 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
47 //===----------------------------------------------------------------------===//
48 // Pattern Matcher Implementation
49 //===----------------------------------------------------------------------===//
52 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
53 /// SDOperand's instead of register numbers for the leaves of the matched
55 struct X86ISelAddressMode {
61 struct { // This is really a union, discriminated by BaseType!
66 bool isRIPRel; // RIP as base?
74 unsigned Align; // CP alignment.
77 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
78 GV(0), CP(0), ES(0), JT(-1), Align(0) {
84 //===--------------------------------------------------------------------===//
85 /// ISel - X86 specific code to select X86 machine instructions for
86 /// SelectionDAG operations.
88 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
89 /// ContainsFPCode - Every instruction we select that uses or defines a FP
90 /// register should set this to true.
93 /// TM - Keep a reference to X86TargetMachine.
97 /// X86Lowering - This object fully describes how to lower LLVM code to an
98 /// X86-specific SelectionDAG.
99 X86TargetLowering X86Lowering;
101 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
102 /// make the right decision when generating code for different targets.
103 const X86Subtarget *Subtarget;
105 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
107 unsigned GlobalBaseReg;
109 /// CurBB - Current BB being isel'd.
111 MachineBasicBlock *CurBB;
114 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
115 : SelectionDAGISel(X86Lowering, fast),
116 ContainsFPCode(false), TM(tm),
117 X86Lowering(*TM.getTargetLowering()),
118 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
120 virtual bool runOnFunction(Function &Fn) {
121 // Make sure we re-emit a set of the global base reg if necessary
123 return SelectionDAGISel::runOnFunction(Fn);
126 virtual const char *getPassName() const {
127 return "X86 DAG->DAG Instruction Selection";
130 /// InstructionSelect - This callback is invoked by
131 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
132 virtual void InstructionSelect(SelectionDAG &DAG);
134 /// InstructionSelectPostProcessing - Post processing of selected and
135 /// scheduled basic blocks.
136 virtual void InstructionSelectPostProcessing(SelectionDAG &DAG);
138 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
140 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
142 // Include the pieces autogenerated from the target description.
143 #include "X86GenDAGISel.inc"
146 SDNode *Select(SDOperand N);
148 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
149 bool isRoot = true, unsigned Depth = 0);
150 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
151 bool isRoot, unsigned Depth);
152 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
153 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
154 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
155 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
156 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
157 SDOperand N, SDOperand &Base, SDOperand &Scale,
158 SDOperand &Index, SDOperand &Disp,
159 SDOperand &InChain, SDOperand &OutChain);
160 bool TryFoldLoad(SDOperand P, SDOperand N,
161 SDOperand &Base, SDOperand &Scale,
162 SDOperand &Index, SDOperand &Disp);
163 void PreprocessForRMW(SelectionDAG &DAG);
164 void PreprocessForFPConvert(SelectionDAG &DAG);
166 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
167 /// inline asm expressions.
168 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
170 std::vector<SDOperand> &OutOps,
173 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
175 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
176 SDOperand &Scale, SDOperand &Index,
178 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
179 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
181 Scale = getI8Imm(AM.Scale);
183 // These are 32-bit even in 64-bit mode since RIP relative offset
186 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
188 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
190 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
191 else if (AM.JT != -1)
192 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
194 Disp = getI32Imm(AM.Disp);
197 /// getI8Imm - Return a target constant with the specified value, of type
199 inline SDOperand getI8Imm(unsigned Imm) {
200 return CurDAG->getTargetConstant(Imm, MVT::i8);
203 /// getI16Imm - Return a target constant with the specified value, of type
205 inline SDOperand getI16Imm(unsigned Imm) {
206 return CurDAG->getTargetConstant(Imm, MVT::i16);
209 /// getI32Imm - Return a target constant with the specified value, of type
211 inline SDOperand getI32Imm(unsigned Imm) {
212 return CurDAG->getTargetConstant(Imm, MVT::i32);
215 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
216 /// base register. Return the virtual register that holds this value.
217 SDNode *getGlobalBaseReg();
219 /// getTruncate - return an SDNode that implements a subreg based truncate
220 /// of the specified operand to the the specified value type.
221 SDNode *getTruncate(SDOperand N0, MVT VT);
229 /// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
231 static SDNode *findFlagUse(SDNode *N) {
232 unsigned FlagResNo = N->getNumValues()-1;
233 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
234 SDNode *User = I->getUser();
235 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
236 SDOperand Op = User->getOperand(i);
237 if (Op.Val == N && Op.ResNo == FlagResNo)
244 /// findNonImmUse - Return true by reference in "found" if "Use" is an
245 /// non-immediate use of "Def". This function recursively traversing
246 /// up the operand chain ignoring certain nodes.
247 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
248 SDNode *Root, SDNode *Skip, bool &found,
249 SmallPtrSet<SDNode*, 16> &Visited) {
251 Use->getNodeId() > Def->getNodeId() ||
252 !Visited.insert(Use))
255 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
256 SDNode *N = Use->getOperand(i).Val;
261 continue; // We are not looking for immediate use.
263 // Must be a chain reading node where it is possible to reach its own
264 // chain operand through a path started from another operand.
265 assert(Use->getOpcode() == ISD::STORE ||
266 Use->getOpcode() == X86ISD::CMP ||
267 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
268 Use->getOpcode() == ISD::INTRINSIC_VOID);
275 // Traverse up the operand chain.
276 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
280 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
281 /// be reached. Return true if that's the case. However, ignore direct uses
282 /// by ImmedUse (which would be U in the example illustrated in
283 /// CanBeFoldedBy) and by Root (which can happen in the store case).
284 /// FIXME: to be really generic, we should allow direct use by any node
285 /// that is being folded. But realisticly since we only fold loads which
286 /// have one non-chain use, we only need to watch out for load/op/store
287 /// and load/op/cmp case where the root (store / cmp) may reach the load via
288 /// its chain operand.
289 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
290 SDNode *Skip = NULL) {
291 SmallPtrSet<SDNode*, 16> Visited;
293 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
298 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
299 if (FastISel) return false;
301 // If U use can somehow reach N through another path then U can't fold N or
302 // it will create a cycle. e.g. In the following diagram, U can reach N
303 // through X. If N is folded into into U, then X is both a predecessor and
314 if (isNonImmUse(Root, N, U))
317 // If U produces a flag, then it gets (even more) interesting. Since it
318 // would have been "glued" together with its flag use, we need to check if
331 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
332 // NU), then TF is a predecessor of FU and a successor of NU. But since
333 // NU and FU are flagged together, this effectively creates a cycle.
334 bool HasFlagUse = false;
335 MVT VT = Root->getValueType(Root->getNumValues()-1);
336 while ((VT == MVT::Flag && !Root->use_empty())) {
337 SDNode *FU = findFlagUse(Root);
344 VT = Root->getValueType(Root->getNumValues()-1);
348 return !isNonImmUse(Root, N, Root, U);
352 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
353 /// and move load below the TokenFactor. Replace store's chain operand with
354 /// load's chain result.
355 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
356 SDOperand Store, SDOperand TF) {
357 std::vector<SDOperand> Ops;
358 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
359 if (Load.Val == TF.Val->getOperand(i).Val)
360 Ops.push_back(Load.Val->getOperand(0));
362 Ops.push_back(TF.Val->getOperand(i));
363 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
364 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
365 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
366 Store.getOperand(2), Store.getOperand(3));
369 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
371 static bool isRMWLoad(SDOperand N, SDOperand Chain, SDOperand Address,
373 if (N.getOpcode() == ISD::BIT_CONVERT)
376 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
377 if (!LD || LD->isVolatile())
379 if (LD->getAddressingMode() != ISD::UNINDEXED)
382 ISD::LoadExtType ExtType = LD->getExtensionType();
383 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
387 N.getOperand(1) == Address &&
388 N.Val->isOperandOf(Chain.Val)) {
395 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
396 /// This is only run if not in -fast mode (aka -O0).
397 /// This allows the instruction selector to pick more read-modify-write
398 /// instructions. This is a common case:
408 /// [TokenFactor] [Op]
415 /// The fact the store's chain operand != load's chain will prevent the
416 /// (store (op (load))) instruction from being selected. We can transform it to:
435 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
436 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
437 E = DAG.allnodes_end(); I != E; ++I) {
438 if (!ISD::isNON_TRUNCStore(I))
440 SDOperand Chain = I->getOperand(0);
441 if (Chain.Val->getOpcode() != ISD::TokenFactor)
444 SDOperand N1 = I->getOperand(1);
445 SDOperand N2 = I->getOperand(2);
446 if ((N1.getValueType().isFloatingPoint() &&
447 !N1.getValueType().isVector()) ||
453 unsigned Opcode = N1.Val->getOpcode();
462 case ISD::VECTOR_SHUFFLE: {
463 SDOperand N10 = N1.getOperand(0);
464 SDOperand N11 = N1.getOperand(1);
465 RModW = isRMWLoad(N10, Chain, N2, Load);
467 RModW = isRMWLoad(N11, Chain, N2, Load);
480 SDOperand N10 = N1.getOperand(0);
481 RModW = isRMWLoad(N10, Chain, N2, Load);
487 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
494 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
495 /// nodes that target the FP stack to be store and load to the stack. This is a
496 /// gross hack. We would like to simply mark these as being illegal, but when
497 /// we do that, legalize produces these when it expands calls, then expands
498 /// these in the same legalize pass. We would like dag combine to be able to
499 /// hack on these between the call expansion and the node legalization. As such
500 /// this pass basically does "really late" legalization of these inline with the
502 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
503 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
504 E = DAG.allnodes_end(); I != E; ) {
505 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
506 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
509 // If the source and destination are SSE registers, then this is a legal
510 // conversion that should not be lowered.
511 MVT SrcVT = N->getOperand(0).getValueType();
512 MVT DstVT = N->getValueType(0);
513 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
514 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
515 if (SrcIsSSE && DstIsSSE)
518 if (!SrcIsSSE && !DstIsSSE) {
519 // If this is an FPStack extension, it is a noop.
520 if (N->getOpcode() == ISD::FP_EXTEND)
522 // If this is a value-preserving FPStack truncation, it is a noop.
523 if (N->getConstantOperandVal(1))
527 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
528 // FPStack has extload and truncstore. SSE can fold direct loads into other
529 // operations. Based on this, decide what we want to do.
531 if (N->getOpcode() == ISD::FP_ROUND)
532 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
534 MemVT = SrcIsSSE ? SrcVT : DstVT;
536 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
538 // FIXME: optimize the case where the src/dest is a load or store?
539 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
540 MemTmp, NULL, 0, MemVT);
541 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
544 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
545 // extload we created. This will cause general havok on the dag because
546 // anything below the conversion could be folded into other existing nodes.
547 // To avoid invalidating 'I', back it up to the convert node.
549 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
551 // Now that we did that, the node is dead. Increment the iterator to the
552 // next node to process, then delete N.
558 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
559 /// when it has created a SelectionDAG for us to codegen.
560 void X86DAGToDAGISel::InstructionSelect(SelectionDAG &DAG) {
561 CurBB = BB; // BB can change as result of isel.
565 PreprocessForRMW(DAG);
567 // FIXME: This should only happen when not -fast.
568 PreprocessForFPConvert(DAG);
570 // Codegen the basic block.
572 DOUT << "===== Instruction selection begins:\n";
575 DAG.setRoot(SelectRoot(DAG.getRoot()));
577 DOUT << "===== Instruction selection ends:\n";
580 DAG.RemoveDeadNodes();
583 void X86DAGToDAGISel::InstructionSelectPostProcessing(SelectionDAG &DAG) {
584 // If we are emitting FP stack code, scan the basic block to determine if this
585 // block defines any FP values. If so, put an FP_REG_KILL instruction before
586 // the terminator of the block.
588 // Note that FP stack instructions are used in all modes for long double,
589 // so we always need to do this check.
590 // Also note that it's possible for an FP stack register to be live across
591 // an instruction that produces multiple basic blocks (SSE CMOV) so we
592 // must check all the generated basic blocks.
594 // Scan all of the machine instructions in these MBBs, checking for FP
595 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
596 MachineFunction::iterator MBBI = CurBB;
597 MachineFunction::iterator EndMBB = BB; ++EndMBB;
598 for (; MBBI != EndMBB; ++MBBI) {
599 MachineBasicBlock *MBB = MBBI;
601 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
602 // before the return.
604 MachineBasicBlock::iterator EndI = MBB->end();
606 if (EndI->getDesc().isReturn())
610 bool ContainsFPCode = false;
611 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
612 !ContainsFPCode && I != E; ++I) {
613 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
614 const TargetRegisterClass *clas;
615 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
616 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
617 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
618 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
619 X86::RFP32RegisterClass ||
620 clas == X86::RFP64RegisterClass ||
621 clas == X86::RFP80RegisterClass)) {
622 ContainsFPCode = true;
628 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
629 // a copy of the input value in this block. In SSE mode, we only care about
631 if (!ContainsFPCode) {
632 // Final check, check LLVM BB's that are successors to the LLVM BB
633 // corresponding to BB for FP PHI nodes.
634 const BasicBlock *LLVMBB = BB->getBasicBlock();
636 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
637 !ContainsFPCode && SI != E; ++SI) {
638 for (BasicBlock::const_iterator II = SI->begin();
639 (PN = dyn_cast<PHINode>(II)); ++II) {
640 if (PN->getType()==Type::X86_FP80Ty ||
641 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
642 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
643 ContainsFPCode = true;
649 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
650 if (ContainsFPCode) {
651 BuildMI(*MBB, MBBI->getFirstTerminator(),
652 TM.getInstrInfo()->get(X86::FP_REG_KILL));
658 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
659 /// the main function.
660 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
661 MachineFrameInfo *MFI) {
662 const TargetInstrInfo *TII = TM.getInstrInfo();
663 if (Subtarget->isTargetCygMing())
664 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
667 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
668 // If this is main, emit special code for main.
669 MachineBasicBlock *BB = MF.begin();
670 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
671 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
674 /// MatchAddress - Add the specified node to the specified addressing mode,
675 /// returning true if it cannot be done. This just pattern matches for the
677 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
678 bool isRoot, unsigned Depth) {
681 return MatchAddressBase(N, AM, isRoot, Depth);
683 // RIP relative addressing: %rip + 32-bit displacement!
685 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
686 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
687 if (isInt32(AM.Disp + Val)) {
695 int id = N.Val->getNodeId();
696 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
698 switch (N.getOpcode()) {
700 case ISD::Constant: {
701 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
702 if (isInt32(AM.Disp + Val)) {
709 case X86ISD::Wrapper: {
710 bool is64Bit = Subtarget->is64Bit();
711 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
712 // Also, base and index reg must be 0 in order to use rip as base.
713 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
714 AM.Base.Reg.Val || AM.IndexReg.Val))
716 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
718 // If value is available in a register both base and index components have
719 // been picked, we can't fit the result available in the register in the
720 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
721 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
722 SDOperand N0 = N.getOperand(0);
723 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
724 GlobalValue *GV = G->getGlobal();
726 AM.Disp += G->getOffset();
727 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
728 Subtarget->isPICStyleRIPRel();
730 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
731 AM.CP = CP->getConstVal();
732 AM.Align = CP->getAlignment();
733 AM.Disp += CP->getOffset();
734 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
735 Subtarget->isPICStyleRIPRel();
737 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
738 AM.ES = S->getSymbol();
739 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
740 Subtarget->isPICStyleRIPRel();
742 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
743 AM.JT = J->getIndex();
744 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
745 Subtarget->isPICStyleRIPRel();
752 case ISD::FrameIndex:
753 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
754 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
755 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
761 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
764 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
765 unsigned Val = CN->getValue();
766 if (Val == 1 || Val == 2 || Val == 3) {
768 SDOperand ShVal = N.Val->getOperand(0);
770 // Okay, we know that we have a scale by now. However, if the scaled
771 // value is an add of something and a constant, we can fold the
772 // constant into the disp field here.
773 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
774 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
775 AM.IndexReg = ShVal.Val->getOperand(0);
776 ConstantSDNode *AddVal =
777 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
778 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
793 // A mul_lohi where we need the low part can be folded as a plain multiply.
794 if (N.ResNo != 0) break;
797 // X*[3,5,9] -> X+X*[2,4,8]
798 if (!AlreadySelected &&
799 AM.BaseType == X86ISelAddressMode::RegBase &&
800 AM.Base.Reg.Val == 0 &&
801 AM.IndexReg.Val == 0 &&
803 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
804 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
805 AM.Scale = unsigned(CN->getValue())-1;
807 SDOperand MulVal = N.Val->getOperand(0);
810 // Okay, we know that we have a scale by now. However, if the scaled
811 // value is an add of something and a constant, we can fold the
812 // constant into the disp field here.
813 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
814 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
815 Reg = MulVal.Val->getOperand(0);
816 ConstantSDNode *AddVal =
817 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
818 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
822 Reg = N.Val->getOperand(0);
824 Reg = N.Val->getOperand(0);
827 AM.IndexReg = AM.Base.Reg = Reg;
834 if (!AlreadySelected) {
835 X86ISelAddressMode Backup = AM;
836 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
837 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
840 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
841 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
848 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
849 if (AlreadySelected) break;
851 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
852 X86ISelAddressMode Backup = AM;
853 // Start with the LHS as an addr mode.
854 if (!MatchAddress(N.getOperand(0), AM, false) &&
855 // Address could not have picked a GV address for the displacement.
857 // On x86-64, the resultant disp must fit in 32-bits.
858 isInt32(AM.Disp + CN->getSignExtended()) &&
859 // Check to see if the LHS & C is zero.
860 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
861 AM.Disp += CN->getValue();
869 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
870 // allows us to fold the shift into this addressing mode.
871 if (AlreadySelected) break;
872 SDOperand Shift = N.getOperand(0);
873 if (Shift.getOpcode() != ISD::SHL) break;
875 // Scale must not be used already.
876 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
878 // Not when RIP is used as the base.
879 if (AM.isRIPRel) break;
881 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
882 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
883 if (!C1 || !C2) break;
885 // Not likely to be profitable if either the AND or SHIFT node has more
886 // than one use (unless all uses are for address computation). Besides,
887 // isel mechanism requires their node ids to be reused.
888 if (!N.hasOneUse() || !Shift.hasOneUse())
891 // Verify that the shift amount is something we can fold.
892 unsigned ShiftCst = C1->getValue();
893 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
896 // Get the new AND mask, this folds to a constant.
897 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
898 SDOperand(C2, 0), SDOperand(C1, 0));
899 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
900 Shift.getOperand(0), NewANDMask);
901 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
902 NewAND.Val->setNodeId(N.Val->getNodeId());
904 AM.Scale = 1 << ShiftCst;
905 AM.IndexReg = NewAND;
910 return MatchAddressBase(N, AM, isRoot, Depth);
913 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
914 /// specified addressing mode without any further recursion.
915 bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
916 bool isRoot, unsigned Depth) {
917 // Is the base register already occupied?
918 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
919 // If so, check to see if the scale index register is set.
920 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
926 // Otherwise, we cannot select it.
930 // Default, generate it as a register.
931 AM.BaseType = X86ISelAddressMode::RegBase;
936 /// SelectAddr - returns true if it is able pattern match an addressing mode.
937 /// It returns the operands which make up the maximal addressing mode it can
938 /// match by reference.
939 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
940 SDOperand &Scale, SDOperand &Index,
942 X86ISelAddressMode AM;
943 if (MatchAddress(N, AM))
946 MVT VT = N.getValueType();
947 if (AM.BaseType == X86ISelAddressMode::RegBase) {
948 if (!AM.Base.Reg.Val)
949 AM.Base.Reg = CurDAG->getRegister(0, VT);
952 if (!AM.IndexReg.Val)
953 AM.IndexReg = CurDAG->getRegister(0, VT);
955 getAddressOperands(AM, Base, Scale, Index, Disp);
959 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
961 static inline bool isZeroNode(SDOperand Elt) {
962 return ((isa<ConstantSDNode>(Elt) &&
963 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
964 (isa<ConstantFPSDNode>(Elt) &&
965 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
969 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
970 /// match a load whose top elements are either undef or zeros. The load flavor
971 /// is derived from the type of N, which is either v4f32 or v2f64.
972 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
973 SDOperand N, SDOperand &Base,
974 SDOperand &Scale, SDOperand &Index,
975 SDOperand &Disp, SDOperand &InChain,
976 SDOperand &OutChain) {
977 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
978 InChain = N.getOperand(0).getValue(1);
979 if (ISD::isNON_EXTLoad(InChain.Val) &&
980 InChain.getValue(0).hasOneUse() &&
982 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
983 LoadSDNode *LD = cast<LoadSDNode>(InChain);
984 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
986 OutChain = LD->getChain();
991 // Also handle the case where we explicitly require zeros in the top
992 // elements. This is a vector shuffle from the zero vector.
993 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
994 // Check to see if the top elements are all zeros (or bitcast of zeros).
995 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
996 N.getOperand(0).Val->hasOneUse() &&
997 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
998 N.getOperand(0).getOperand(0).hasOneUse()) {
999 // Okay, this is a zero extending load. Fold it.
1000 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1001 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1003 OutChain = LD->getChain();
1004 InChain = SDOperand(LD, 1);
1011 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1012 /// mode it matches can be cost effectively emitted as an LEA instruction.
1013 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1014 SDOperand &Base, SDOperand &Scale,
1015 SDOperand &Index, SDOperand &Disp) {
1016 X86ISelAddressMode AM;
1017 if (MatchAddress(N, AM))
1020 MVT VT = N.getValueType();
1021 unsigned Complexity = 0;
1022 if (AM.BaseType == X86ISelAddressMode::RegBase)
1023 if (AM.Base.Reg.Val)
1026 AM.Base.Reg = CurDAG->getRegister(0, VT);
1027 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1030 if (AM.IndexReg.Val)
1033 AM.IndexReg = CurDAG->getRegister(0, VT);
1035 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1040 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1041 // to a LEA. This is determined with some expermentation but is by no means
1042 // optimal (especially for code size consideration). LEA is nice because of
1043 // its three-address nature. Tweak the cost function again when we can run
1044 // convertToThreeAddress() at register allocation time.
1045 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1046 // For X86-64, we should always use lea to materialize RIP relative
1048 if (Subtarget->is64Bit())
1054 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1057 if (Complexity > 2) {
1058 getAddressOperands(AM, Base, Scale, Index, Disp);
1064 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1065 SDOperand &Base, SDOperand &Scale,
1066 SDOperand &Index, SDOperand &Disp) {
1067 if (ISD::isNON_EXTLoad(N.Val) &&
1069 CanBeFoldedBy(N.Val, P.Val, P.Val))
1070 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1074 /// getGlobalBaseReg - Output the instructions required to put the
1075 /// base address to use for accessing globals into a register.
1077 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1078 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1079 if (!GlobalBaseReg) {
1080 // Insert the set of GlobalBaseReg into the first MBB of the function
1081 MachineFunction *MF = BB->getParent();
1082 MachineBasicBlock &FirstMBB = MF->front();
1083 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1084 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1085 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1087 const TargetInstrInfo *TII = TM.getInstrInfo();
1088 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1089 // only used in JIT code emission as displacement to pc.
1090 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1092 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1093 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1094 if (TM.getRelocationModel() == Reloc::PIC_ &&
1095 Subtarget->isPICStyleGOT()) {
1096 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1097 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1098 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1104 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1107 static SDNode *FindCallStartFromCall(SDNode *Node) {
1108 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1109 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1110 "Node doesn't have a token chain argument!");
1111 return FindCallStartFromCall(Node->getOperand(0).Val);
1114 SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT VT) {
1116 switch (VT.getSimpleVT()) {
1117 default: assert(0 && "Unknown truncate!");
1119 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1120 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1121 if (!Subtarget->is64Bit()) {
1123 MVT N0VT = N0.getValueType();
1124 switch (N0VT.getSimpleVT()) {
1125 default: assert(0 && "Unknown truncate!");
1127 Opc = X86::MOV16to16_;
1130 Opc = X86::MOV32to32_;
1133 N0 = SDOperand(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
1134 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1135 VT, N0, SRIdx, N0.getValue(1));
1139 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1142 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1145 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
1149 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1150 SDNode *Node = N.Val;
1151 MVT NVT = Node->getValueType(0);
1153 unsigned Opcode = Node->getOpcode();
1156 DOUT << std::string(Indent, ' ') << "Selecting: ";
1157 DEBUG(Node->dump(CurDAG));
1162 if (Node->isMachineOpcode()) {
1164 DOUT << std::string(Indent-2, ' ') << "== ";
1165 DEBUG(Node->dump(CurDAG));
1169 return NULL; // Already selected.
1174 case X86ISD::GlobalBaseReg:
1175 return getGlobalBaseReg();
1178 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1179 // code and is matched first so to prevent it from being turned into
1181 // In 64-bit small code size mode, use LEA to take advantage of
1182 // RIP-relative addressing.
1183 if (TM.getCodeModel() != CodeModel::Small)
1185 MVT PtrVT = TLI.getPointerTy();
1186 SDOperand N0 = N.getOperand(0);
1187 SDOperand N1 = N.getOperand(1);
1188 if (N.Val->getValueType(0) == PtrVT &&
1189 N0.getOpcode() == X86ISD::Wrapper &&
1190 N1.getOpcode() == ISD::Constant) {
1191 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1193 // TODO: handle ExternalSymbolSDNode.
1194 if (GlobalAddressSDNode *G =
1195 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1196 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1197 G->getOffset() + Offset);
1198 } else if (ConstantPoolSDNode *CP =
1199 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1200 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1202 CP->getOffset()+Offset);
1206 if (Subtarget->is64Bit()) {
1207 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1208 CurDAG->getRegister(0, PtrVT), C };
1209 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1211 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1215 // Other cases are handled by auto-generated code.
1219 case ISD::SMUL_LOHI:
1220 case ISD::UMUL_LOHI: {
1221 SDOperand N0 = Node->getOperand(0);
1222 SDOperand N1 = Node->getOperand(1);
1224 bool isSigned = Opcode == ISD::SMUL_LOHI;
1226 switch (NVT.getSimpleVT()) {
1227 default: assert(0 && "Unsupported VT!");
1228 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1229 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1230 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1231 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1234 switch (NVT.getSimpleVT()) {
1235 default: assert(0 && "Unsupported VT!");
1236 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1237 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1238 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1239 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1242 unsigned LoReg, HiReg;
1243 switch (NVT.getSimpleVT()) {
1244 default: assert(0 && "Unsupported VT!");
1245 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1246 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1247 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1248 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1251 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1252 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1253 // multiplty is commmutative
1255 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1261 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1262 N0, SDOperand()).getValue(1);
1265 AddToISelQueue(N1.getOperand(0));
1266 AddToISelQueue(Tmp0);
1267 AddToISelQueue(Tmp1);
1268 AddToISelQueue(Tmp2);
1269 AddToISelQueue(Tmp3);
1270 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1272 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1273 InFlag = SDOperand(CNode, 1);
1274 // Update the chain.
1275 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1279 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1282 // Copy the low half of the result, if it is needed.
1283 if (!N.getValue(0).use_empty()) {
1284 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1285 LoReg, NVT, InFlag);
1286 InFlag = Result.getValue(2);
1287 ReplaceUses(N.getValue(0), Result);
1289 DOUT << std::string(Indent-2, ' ') << "=> ";
1290 DEBUG(Result.Val->dump(CurDAG));
1294 // Copy the high half of the result, if it is needed.
1295 if (!N.getValue(1).use_empty()) {
1297 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1298 // Prevent use of AH in a REX instruction by referencing AX instead.
1299 // Shift it down 8 bits.
1300 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1301 X86::AX, MVT::i16, InFlag);
1302 InFlag = Result.getValue(2);
1303 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1304 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1305 // Then truncate it down to i8.
1306 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1307 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1308 MVT::i8, Result, SRIdx), 0);
1310 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1311 HiReg, NVT, InFlag);
1312 InFlag = Result.getValue(2);
1314 ReplaceUses(N.getValue(1), Result);
1316 DOUT << std::string(Indent-2, ' ') << "=> ";
1317 DEBUG(Result.Val->dump(CurDAG));
1330 case ISD::UDIVREM: {
1331 SDOperand N0 = Node->getOperand(0);
1332 SDOperand N1 = Node->getOperand(1);
1334 bool isSigned = Opcode == ISD::SDIVREM;
1336 switch (NVT.getSimpleVT()) {
1337 default: assert(0 && "Unsupported VT!");
1338 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1339 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1340 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1341 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1344 switch (NVT.getSimpleVT()) {
1345 default: assert(0 && "Unsupported VT!");
1346 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1347 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1348 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1349 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1352 unsigned LoReg, HiReg;
1353 unsigned ClrOpcode, SExtOpcode;
1354 switch (NVT.getSimpleVT()) {
1355 default: assert(0 && "Unsupported VT!");
1357 LoReg = X86::AL; HiReg = X86::AH;
1359 SExtOpcode = X86::CBW;
1362 LoReg = X86::AX; HiReg = X86::DX;
1363 ClrOpcode = X86::MOV16r0;
1364 SExtOpcode = X86::CWD;
1367 LoReg = X86::EAX; HiReg = X86::EDX;
1368 ClrOpcode = X86::MOV32r0;
1369 SExtOpcode = X86::CDQ;
1372 LoReg = X86::RAX; HiReg = X86::RDX;
1373 ClrOpcode = X86::MOV64r0;
1374 SExtOpcode = X86::CQO;
1378 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1379 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1382 if (NVT == MVT::i8 && !isSigned) {
1383 // Special case for div8, just use a move with zero extension to AX to
1384 // clear the upper 8 bits (AH).
1385 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1386 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1387 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1388 AddToISelQueue(N0.getOperand(0));
1389 AddToISelQueue(Tmp0);
1390 AddToISelQueue(Tmp1);
1391 AddToISelQueue(Tmp2);
1392 AddToISelQueue(Tmp3);
1394 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1396 Chain = Move.getValue(1);
1397 ReplaceUses(N0.getValue(1), Chain);
1401 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1402 Chain = CurDAG->getEntryNode();
1404 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
1405 InFlag = Chain.getValue(1);
1409 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1410 LoReg, N0, SDOperand()).getValue(1);
1412 // Sign extend the low part into the high part.
1414 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1416 // Zero out the high part, effectively zero extending the input.
1417 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1418 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1419 ClrNode, InFlag).getValue(1);
1424 AddToISelQueue(N1.getOperand(0));
1425 AddToISelQueue(Tmp0);
1426 AddToISelQueue(Tmp1);
1427 AddToISelQueue(Tmp2);
1428 AddToISelQueue(Tmp3);
1429 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1431 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1432 InFlag = SDOperand(CNode, 1);
1433 // Update the chain.
1434 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1438 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1441 // Copy the division (low) result, if it is needed.
1442 if (!N.getValue(0).use_empty()) {
1443 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1444 LoReg, NVT, InFlag);
1445 InFlag = Result.getValue(2);
1446 ReplaceUses(N.getValue(0), Result);
1448 DOUT << std::string(Indent-2, ' ') << "=> ";
1449 DEBUG(Result.Val->dump(CurDAG));
1453 // Copy the remainder (high) result, if it is needed.
1454 if (!N.getValue(1).use_empty()) {
1456 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1457 // Prevent use of AH in a REX instruction by referencing AX instead.
1458 // Shift it down 8 bits.
1459 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1460 X86::AX, MVT::i16, InFlag);
1461 InFlag = Result.getValue(2);
1462 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1463 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1464 // Then truncate it down to i8.
1465 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1466 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1467 MVT::i8, Result, SRIdx), 0);
1469 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1470 HiReg, NVT, InFlag);
1471 InFlag = Result.getValue(2);
1473 ReplaceUses(N.getValue(1), Result);
1475 DOUT << std::string(Indent-2, ' ') << "=> ";
1476 DEBUG(Result.Val->dump(CurDAG));
1488 case ISD::ANY_EXTEND: {
1489 // Check if the type extended to supports subregs.
1493 SDOperand N0 = Node->getOperand(0);
1494 // Get the subregsiter index for the type to extend.
1495 MVT N0VT = N0.getValueType();
1496 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1497 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1498 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1500 // If we don't have a subreg Idx, let generated ISel have a try.
1504 // If we have an index, generate an insert_subreg into undef.
1507 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
1508 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1509 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1510 NVT, Undef, N0, SRIdx);
1513 DOUT << std::string(Indent-2, ' ') << "=> ";
1514 DEBUG(ResNode->dump(CurDAG));
1521 case ISD::SIGN_EXTEND_INREG: {
1522 SDOperand N0 = Node->getOperand(0);
1525 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1526 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1528 switch (NVT.getSimpleVT()) {
1529 default: assert(0 && "Unknown sign_extend_inreg!");
1531 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1532 else assert(0 && "Unknown sign_extend_inreg!");
1535 switch (SVT.getSimpleVT()) {
1536 default: assert(0 && "Unknown sign_extend_inreg!");
1537 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1538 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1542 switch (SVT.getSimpleVT()) {
1543 default: assert(0 && "Unknown sign_extend_inreg!");
1544 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1545 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1546 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1551 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1554 DOUT << std::string(Indent-2, ' ') << "=> ";
1555 DEBUG(TruncOp.Val->dump(CurDAG));
1557 DOUT << std::string(Indent-2, ' ') << "=> ";
1558 DEBUG(ResNode->dump(CurDAG));
1566 case ISD::TRUNCATE: {
1567 SDOperand Input = Node->getOperand(0);
1568 AddToISelQueue(Node->getOperand(0));
1569 SDNode *ResNode = getTruncate(Input, NVT);
1572 DOUT << std::string(Indent-2, ' ') << "=> ";
1573 DEBUG(ResNode->dump(CurDAG));
1581 case ISD::DECLARE: {
1582 // Handle DECLARE nodes here because the second operand may have been
1583 // wrapped in X86ISD::Wrapper.
1584 SDOperand Chain = Node->getOperand(0);
1585 SDOperand N1 = Node->getOperand(1);
1586 SDOperand N2 = Node->getOperand(2);
1587 if (!isa<FrameIndexSDNode>(N1))
1589 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1590 if (N2.getOpcode() == ISD::ADD &&
1591 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1592 N2 = N2.getOperand(1);
1593 if (N2.getOpcode() == X86ISD::Wrapper &&
1594 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
1596 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1597 SDOperand Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1598 SDOperand Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1599 AddToISelQueue(Chain);
1600 SDOperand Ops[] = { Tmp1, Tmp2, Chain };
1601 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1602 MVT::Other, Ops, 3);
1608 SDNode *ResNode = SelectCode(N);
1611 DOUT << std::string(Indent-2, ' ') << "=> ";
1612 if (ResNode == NULL || ResNode == N.Val)
1613 DEBUG(N.Val->dump(CurDAG));
1615 DEBUG(ResNode->dump(CurDAG));
1623 bool X86DAGToDAGISel::
1624 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1625 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1626 SDOperand Op0, Op1, Op2, Op3;
1627 switch (ConstraintCode) {
1628 case 'o': // offsetable ??
1629 case 'v': // not offsetable ??
1630 default: return true;
1632 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1637 OutOps.push_back(Op0);
1638 OutOps.push_back(Op1);
1639 OutOps.push_back(Op2);
1640 OutOps.push_back(Op3);
1641 AddToISelQueue(Op0);
1642 AddToISelQueue(Op1);
1643 AddToISelQueue(Op2);
1644 AddToISelQueue(Op3);
1648 /// createX86ISelDag - This pass converts a legalized DAG into a
1649 /// X86-specific DAG, ready for instruction scheduling.
1651 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1652 return new X86DAGToDAGISel(TM, Fast);