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/Target/TargetOptions.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Streams.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46 //===----------------------------------------------------------------------===//
47 // Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
51 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52 /// SDValue's instead of register numbers for the leaves of the matched
54 struct X86ISelAddressMode {
60 struct { // This is really a union, discriminated by BaseType!
65 bool isRIPRel; // RIP as base?
73 unsigned Align; // CP alignment.
76 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
77 GV(0), CP(0), ES(0), JT(-1), Align(0) {
80 cerr << "X86ISelAddressMode " << this << "\n";
82 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
84 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
85 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
87 if (IndexReg.getNode() != 0) IndexReg.getNode()->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 /// TM - Keep a reference to X86TargetMachine.
109 X86TargetMachine &TM;
111 /// X86Lowering - This object fully describes how to lower LLVM code to an
112 /// X86-specific SelectionDAG.
113 X86TargetLowering &X86Lowering;
115 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
116 /// make the right decision when generating code for different targets.
117 const X86Subtarget *Subtarget;
119 /// CurBB - Current BB being isel'd.
121 MachineBasicBlock *CurBB;
123 /// OptForSize - If true, selector should try to optimize for code size
124 /// instead of performance.
128 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
129 : SelectionDAGISel(tm, fast),
130 TM(tm), X86Lowering(*TM.getTargetLowering()),
131 Subtarget(&TM.getSubtarget<X86Subtarget>()),
134 virtual const char *getPassName() const {
135 return "X86 DAG->DAG Instruction Selection";
138 /// InstructionSelect - This callback is invoked by
139 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
140 virtual void InstructionSelect();
142 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
145 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
147 // Include the pieces autogenerated from the target description.
148 #include "X86GenDAGISel.inc"
151 SDNode *Select(SDValue N);
152 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
154 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
155 bool isRoot = true, unsigned Depth = 0);
156 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
157 bool isRoot, unsigned Depth);
158 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
159 SDValue &Scale, SDValue &Index, SDValue &Disp);
160 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
161 SDValue &Scale, SDValue &Index, SDValue &Disp);
162 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
163 SDValue N, SDValue &Base, SDValue &Scale,
164 SDValue &Index, SDValue &Disp,
165 SDValue &InChain, SDValue &OutChain);
166 bool TryFoldLoad(SDValue P, SDValue N,
167 SDValue &Base, SDValue &Scale,
168 SDValue &Index, SDValue &Disp);
169 void PreprocessForRMW();
170 void PreprocessForFPConvert();
172 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
173 /// inline asm expressions.
174 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
176 std::vector<SDValue> &OutOps);
178 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
180 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
181 SDValue &Scale, SDValue &Index,
183 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
184 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
186 Scale = getI8Imm(AM.Scale);
188 // These are 32-bit even in 64-bit mode since RIP relative offset
191 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
193 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
196 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
197 else if (AM.JT != -1)
198 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
200 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
203 /// getI8Imm - Return a target constant with the specified value, of type
205 inline SDValue getI8Imm(unsigned Imm) {
206 return CurDAG->getTargetConstant(Imm, MVT::i8);
209 /// getI16Imm - Return a target constant with the specified value, of type
211 inline SDValue getI16Imm(unsigned Imm) {
212 return CurDAG->getTargetConstant(Imm, MVT::i16);
215 /// getI32Imm - Return a target constant with the specified value, of type
217 inline SDValue getI32Imm(unsigned Imm) {
218 return CurDAG->getTargetConstant(Imm, MVT::i32);
221 /// getGlobalBaseReg - Return an SDNode that returns the value of
222 /// the global base register. Output instructions required to
223 /// initialize the global base register, if necessary.
225 SDNode *getGlobalBaseReg();
227 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
228 /// truncate of the specified operand to i8. This can be done with tablegen,
229 /// except that this code uses MVT::Flag in a tricky way that happens to
230 /// improve scheduling in some cases.
231 SDNode *getTruncateTo8Bit(SDValue N0);
239 /// findFlagUse - Return use of MVT::Flag value produced by the specified
242 static SDNode *findFlagUse(SDNode *N) {
243 unsigned FlagResNo = N->getNumValues()-1;
244 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
245 SDUse &Use = I.getUse();
246 if (Use.getResNo() == FlagResNo)
247 return Use.getUser();
252 /// findNonImmUse - Return true by reference in "found" if "Use" is an
253 /// non-immediate use of "Def". This function recursively traversing
254 /// up the operand chain ignoring certain nodes.
255 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
256 SDNode *Root, bool &found,
257 SmallPtrSet<SDNode*, 16> &Visited) {
259 Use->getNodeId() < Def->getNodeId() ||
260 !Visited.insert(Use))
263 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
264 SDNode *N = Use->getOperand(i).getNode();
266 if (Use == ImmedUse || Use == Root)
267 continue; // We are not looking for immediate use.
273 // Traverse up the operand chain.
274 findNonImmUse(N, Def, ImmedUse, Root, found, Visited);
278 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
279 /// be reached. Return true if that's the case. However, ignore direct uses
280 /// by ImmedUse (which would be U in the example illustrated in
281 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
283 /// FIXME: to be really generic, we should allow direct use by any node
284 /// that is being folded. But realisticly since we only fold loads which
285 /// have one non-chain use, we only need to watch out for load/op/store
286 /// and load/op/cmp case where the root (store / cmp) may reach the load via
287 /// its chain operand.
288 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
289 SmallPtrSet<SDNode*, 16> Visited;
291 findNonImmUse(Root, Def, ImmedUse, Root, found, Visited);
296 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
297 SDNode *Root) const {
298 if (Fast) return false;
301 switch (U->getOpcode()) {
309 // If the other operand is a 8-bit immediate we should fold the immediate
310 // instead. This reduces code size.
312 // movl 4(%esp), %eax
316 // addl 4(%esp), %eax
317 // The former is 2 bytes shorter. In case where the increment is 1, then
318 // the saving can be 4 bytes (by using incl %eax).
319 ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(U->getOperand(1));
321 if (U->getValueType(0) == MVT::i64) {
322 if ((int32_t)Imm->getZExtValue() == (int64_t)Imm->getZExtValue())
325 if ((int8_t)Imm->getZExtValue() == (int64_t)Imm->getZExtValue())
332 // If Root use can somehow reach N through a path that that doesn't contain
333 // U then folding N would create a cycle. e.g. In the following
334 // diagram, Root can reach N through X. If N is folded into into Root, then
335 // X is both a predecessor and a successor of U.
346 // * indicates nodes to be folded together.
348 // If Root produces a flag, then it gets (even more) interesting. Since it
349 // will be "glued" together with its flag use in the scheduler, we need to
350 // check if it might reach N.
369 // If FU (flag use) indirectly reaches N (the load), and Root folds N
370 // (call it Fold), then X is a predecessor of FU and a successor of
371 // Fold. But since Fold and FU are flagged together, this will create
372 // a cycle in the scheduling graph.
374 MVT VT = Root->getValueType(Root->getNumValues()-1);
375 while (VT == MVT::Flag) {
376 SDNode *FU = findFlagUse(Root);
380 VT = Root->getValueType(Root->getNumValues()-1);
383 return !isNonImmUse(Root, N, U);
386 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
387 /// and move load below the TokenFactor. Replace store's chain operand with
388 /// load's chain result.
389 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
390 SDValue Store, SDValue TF) {
391 SmallVector<SDValue, 4> Ops;
392 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
393 if (Load.getNode() == TF.getOperand(i).getNode())
394 Ops.push_back(Load.getOperand(0));
396 Ops.push_back(TF.getOperand(i));
397 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
398 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
399 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
400 Store.getOperand(2), Store.getOperand(3));
403 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
405 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
407 if (N.getOpcode() == ISD::BIT_CONVERT)
410 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
411 if (!LD || LD->isVolatile())
413 if (LD->getAddressingMode() != ISD::UNINDEXED)
416 ISD::LoadExtType ExtType = LD->getExtensionType();
417 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
421 N.getOperand(1) == Address &&
422 N.getNode()->isOperandOf(Chain.getNode())) {
429 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
430 /// operand and move load below the call's chain operand.
431 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
432 SDValue Call, SDValue CallSeqStart) {
433 SmallVector<SDValue, 8> Ops;
434 SDValue Chain = CallSeqStart.getOperand(0);
435 if (Chain.getNode() == Load.getNode())
436 Ops.push_back(Load.getOperand(0));
438 assert(Chain.getOpcode() == ISD::TokenFactor &&
439 "Unexpected CallSeqStart chain operand");
440 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
441 if (Chain.getOperand(i).getNode() == Load.getNode())
442 Ops.push_back(Load.getOperand(0));
444 Ops.push_back(Chain.getOperand(i));
446 CurDAG->getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
448 Ops.push_back(NewChain);
450 for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
451 Ops.push_back(CallSeqStart.getOperand(i));
452 CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
453 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
454 Load.getOperand(1), Load.getOperand(2));
456 Ops.push_back(SDValue(Load.getNode(), 1));
457 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
458 Ops.push_back(Call.getOperand(i));
459 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
462 /// isCalleeLoad - Return true if call address is a load and it can be
463 /// moved below CALLSEQ_START and the chains leading up to the call.
464 /// Return the CALLSEQ_START by reference as a second output.
465 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
466 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
468 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
471 LD->getAddressingMode() != ISD::UNINDEXED ||
472 LD->getExtensionType() != ISD::NON_EXTLOAD)
475 // Now let's find the callseq_start.
476 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
477 if (!Chain.hasOneUse())
479 Chain = Chain.getOperand(0);
482 if (Chain.getOperand(0).getNode() == Callee.getNode())
484 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
485 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
491 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
492 /// This is only run if not in -fast mode (aka -O0).
493 /// This allows the instruction selector to pick more read-modify-write
494 /// instructions. This is a common case:
504 /// [TokenFactor] [Op]
511 /// The fact the store's chain operand != load's chain will prevent the
512 /// (store (op (load))) instruction from being selected. We can transform it to:
531 void X86DAGToDAGISel::PreprocessForRMW() {
532 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
533 E = CurDAG->allnodes_end(); I != E; ++I) {
534 if (I->getOpcode() == X86ISD::CALL) {
535 /// Also try moving call address load from outside callseq_start to just
536 /// before the call to allow it to be folded.
554 SDValue Chain = I->getOperand(0);
555 SDValue Load = I->getOperand(1);
556 if (!isCalleeLoad(Load, Chain))
558 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
563 if (!ISD::isNON_TRUNCStore(I))
565 SDValue Chain = I->getOperand(0);
567 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
570 SDValue N1 = I->getOperand(1);
571 SDValue N2 = I->getOperand(2);
572 if ((N1.getValueType().isFloatingPoint() &&
573 !N1.getValueType().isVector()) ||
579 unsigned Opcode = N1.getNode()->getOpcode();
588 case ISD::VECTOR_SHUFFLE: {
589 SDValue N10 = N1.getOperand(0);
590 SDValue N11 = N1.getOperand(1);
591 RModW = isRMWLoad(N10, Chain, N2, Load);
593 RModW = isRMWLoad(N11, Chain, N2, Load);
606 SDValue N10 = N1.getOperand(0);
607 RModW = isRMWLoad(N10, Chain, N2, Load);
613 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
620 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
621 /// nodes that target the FP stack to be store and load to the stack. This is a
622 /// gross hack. We would like to simply mark these as being illegal, but when
623 /// we do that, legalize produces these when it expands calls, then expands
624 /// these in the same legalize pass. We would like dag combine to be able to
625 /// hack on these between the call expansion and the node legalization. As such
626 /// this pass basically does "really late" legalization of these inline with the
628 void X86DAGToDAGISel::PreprocessForFPConvert() {
629 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
630 E = CurDAG->allnodes_end(); I != E; ) {
631 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
632 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
635 // If the source and destination are SSE registers, then this is a legal
636 // conversion that should not be lowered.
637 MVT SrcVT = N->getOperand(0).getValueType();
638 MVT DstVT = N->getValueType(0);
639 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
640 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
641 if (SrcIsSSE && DstIsSSE)
644 if (!SrcIsSSE && !DstIsSSE) {
645 // If this is an FPStack extension, it is a noop.
646 if (N->getOpcode() == ISD::FP_EXTEND)
648 // If this is a value-preserving FPStack truncation, it is a noop.
649 if (N->getConstantOperandVal(1))
653 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
654 // FPStack has extload and truncstore. SSE can fold direct loads into other
655 // operations. Based on this, decide what we want to do.
657 if (N->getOpcode() == ISD::FP_ROUND)
658 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
660 MemVT = SrcIsSSE ? SrcVT : DstVT;
662 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
664 // FIXME: optimize the case where the src/dest is a load or store?
665 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(),
667 MemTmp, NULL, 0, MemVT);
668 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
671 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
672 // extload we created. This will cause general havok on the dag because
673 // anything below the conversion could be folded into other existing nodes.
674 // To avoid invalidating 'I', back it up to the convert node.
676 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
678 // Now that we did that, the node is dead. Increment the iterator to the
679 // next node to process, then delete N.
681 CurDAG->DeleteNode(N);
685 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
686 /// when it has created a SelectionDAG for us to codegen.
687 void X86DAGToDAGISel::InstructionSelect() {
688 CurBB = BB; // BB can change as result of isel.
689 const Function *F = CurDAG->getMachineFunction().getFunction();
690 OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
696 // FIXME: This should only happen when not -fast.
697 PreprocessForFPConvert();
699 // Codegen the basic block.
701 DOUT << "===== Instruction selection begins:\n";
706 DOUT << "===== Instruction selection ends:\n";
709 CurDAG->RemoveDeadNodes();
712 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
713 /// the main function.
714 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
715 MachineFrameInfo *MFI) {
716 const TargetInstrInfo *TII = TM.getInstrInfo();
717 if (Subtarget->isTargetCygMing())
718 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
721 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
722 // If this is main, emit special code for main.
723 MachineBasicBlock *BB = MF.begin();
724 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
725 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
728 /// MatchAddress - Add the specified node to the specified addressing mode,
729 /// returning true if it cannot be done. This just pattern matches for the
731 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
732 bool isRoot, unsigned Depth) {
733 bool is64Bit = Subtarget->is64Bit();
734 DOUT << "MatchAddress: "; DEBUG(AM.dump());
737 return MatchAddressBase(N, AM, isRoot, Depth);
739 // RIP relative addressing: %rip + 32-bit displacement!
741 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
742 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
743 if (!is64Bit || isInt32(AM.Disp + Val)) {
751 switch (N.getOpcode()) {
753 case ISD::Constant: {
754 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
755 if (!is64Bit || isInt32(AM.Disp + Val)) {
762 case X86ISD::Wrapper: {
763 DOUT << "Wrapper: 64bit " << is64Bit;
764 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
765 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
766 // Also, base and index reg must be 0 in order to use rip as base.
767 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
768 AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
770 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
772 // If value is available in a register both base and index components have
773 // been picked, we can't fit the result available in the register in the
774 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
776 SDValue N0 = N.getOperand(0);
777 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
778 uint64_t Offset = G->getOffset();
779 if (!is64Bit || isInt32(AM.Disp + Offset)) {
780 GlobalValue *GV = G->getGlobal();
783 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
786 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
787 uint64_t Offset = CP->getOffset();
788 if (!is64Bit || isInt32(AM.Disp + Offset)) {
789 AM.CP = CP->getConstVal();
790 AM.Align = CP->getAlignment();
792 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
795 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
796 AM.ES = S->getSymbol();
797 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
799 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
800 AM.JT = J->getIndex();
801 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
808 case ISD::FrameIndex:
809 if (AM.BaseType == X86ISelAddressMode::RegBase
810 && AM.Base.Reg.getNode() == 0) {
811 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
812 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
818 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1 || AM.isRIPRel)
822 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
823 unsigned Val = CN->getZExtValue();
824 if (Val == 1 || Val == 2 || Val == 3) {
826 SDValue ShVal = N.getNode()->getOperand(0);
828 // Okay, we know that we have a scale by now. However, if the scaled
829 // value is an add of something and a constant, we can fold the
830 // constant into the disp field here.
831 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
832 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
833 AM.IndexReg = ShVal.getNode()->getOperand(0);
834 ConstantSDNode *AddVal =
835 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
836 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
837 if (!is64Bit || isInt32(Disp))
851 // A mul_lohi where we need the low part can be folded as a plain multiply.
852 if (N.getResNo() != 0) break;
855 // X*[3,5,9] -> X+X*[2,4,8]
856 if (AM.BaseType == X86ISelAddressMode::RegBase &&
857 AM.Base.Reg.getNode() == 0 &&
858 AM.IndexReg.getNode() == 0 &&
861 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
862 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
863 CN->getZExtValue() == 9) {
864 AM.Scale = unsigned(CN->getZExtValue())-1;
866 SDValue MulVal = N.getNode()->getOperand(0);
869 // Okay, we know that we have a scale by now. However, if the scaled
870 // value is an add of something and a constant, we can fold the
871 // constant into the disp field here.
872 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
873 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
874 Reg = MulVal.getNode()->getOperand(0);
875 ConstantSDNode *AddVal =
876 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
877 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
879 if (!is64Bit || isInt32(Disp))
882 Reg = N.getNode()->getOperand(0);
884 Reg = N.getNode()->getOperand(0);
887 AM.IndexReg = AM.Base.Reg = Reg;
894 X86ISelAddressMode Backup = AM;
895 if (!MatchAddress(N.getNode()->getOperand(0), AM, false, Depth+1) &&
896 !MatchAddress(N.getNode()->getOperand(1), AM, false, Depth+1))
899 if (!MatchAddress(N.getNode()->getOperand(1), AM, false, Depth+1) &&
900 !MatchAddress(N.getNode()->getOperand(0), AM, false, Depth+1))
907 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
908 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
909 X86ISelAddressMode Backup = AM;
910 uint64_t Offset = CN->getSExtValue();
911 // Start with the LHS as an addr mode.
912 if (!MatchAddress(N.getOperand(0), AM, false) &&
913 // Address could not have picked a GV address for the displacement.
915 // On x86-64, the resultant disp must fit in 32-bits.
916 (!is64Bit || isInt32(AM.Disp + Offset)) &&
917 // Check to see if the LHS & C is zero.
918 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
927 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
928 // allows us to fold the shift into this addressing mode.
929 SDValue Shift = N.getOperand(0);
930 if (Shift.getOpcode() != ISD::SHL) break;
932 // Scale must not be used already.
933 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
935 // Not when RIP is used as the base.
936 if (AM.isRIPRel) break;
938 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
939 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
940 if (!C1 || !C2) break;
942 // Not likely to be profitable if either the AND or SHIFT node has more
943 // than one use (unless all uses are for address computation). Besides,
944 // isel mechanism requires their node ids to be reused.
945 if (!N.hasOneUse() || !Shift.hasOneUse())
948 // Verify that the shift amount is something we can fold.
949 unsigned ShiftCst = C1->getZExtValue();
950 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
953 // Get the new AND mask, this folds to a constant.
954 SDValue X = Shift.getOperand(0);
955 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
956 SDValue(C2, 0), SDValue(C1, 0));
957 SDValue NewAND = CurDAG->getNode(ISD::AND, N.getValueType(), X, NewANDMask);
958 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, N.getValueType(),
959 NewAND, SDValue(C1, 0));
961 // Insert the new nodes into the topological ordering.
962 if (C1->getNodeId() > X.getNode()->getNodeId()) {
963 CurDAG->RepositionNode(X.getNode(), C1);
964 C1->setNodeId(X.getNode()->getNodeId());
966 if (NewANDMask.getNode()->getNodeId() == -1 ||
967 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
968 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
969 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
971 if (NewAND.getNode()->getNodeId() == -1 ||
972 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
973 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
974 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
976 if (NewSHIFT.getNode()->getNodeId() == -1 ||
977 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
978 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
979 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
982 CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
984 AM.Scale = 1 << ShiftCst;
985 AM.IndexReg = NewAND;
990 return MatchAddressBase(N, AM, isRoot, Depth);
993 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
994 /// specified addressing mode without any further recursion.
995 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
996 bool isRoot, unsigned Depth) {
997 // Is the base register already occupied?
998 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
999 // If so, check to see if the scale index register is set.
1000 if (AM.IndexReg.getNode() == 0 && !AM.isRIPRel) {
1006 // Otherwise, we cannot select it.
1010 // Default, generate it as a register.
1011 AM.BaseType = X86ISelAddressMode::RegBase;
1016 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1017 /// It returns the operands which make up the maximal addressing mode it can
1018 /// match by reference.
1019 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1020 SDValue &Scale, SDValue &Index,
1022 X86ISelAddressMode AM;
1023 if (MatchAddress(N, AM))
1026 MVT VT = N.getValueType();
1027 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1028 if (!AM.Base.Reg.getNode())
1029 AM.Base.Reg = CurDAG->getRegister(0, VT);
1032 if (!AM.IndexReg.getNode())
1033 AM.IndexReg = CurDAG->getRegister(0, VT);
1035 getAddressOperands(AM, Base, Scale, Index, Disp);
1039 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1040 /// match a load whose top elements are either undef or zeros. The load flavor
1041 /// is derived from the type of N, which is either v4f32 or v2f64.
1042 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1043 SDValue N, SDValue &Base,
1044 SDValue &Scale, SDValue &Index,
1045 SDValue &Disp, SDValue &InChain,
1046 SDValue &OutChain) {
1047 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1048 InChain = N.getOperand(0).getValue(1);
1049 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1050 InChain.getValue(0).hasOneUse() &&
1052 IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1053 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1054 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1056 OutChain = LD->getChain();
1061 // Also handle the case where we explicitly require zeros in the top
1062 // elements. This is a vector shuffle from the zero vector.
1063 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1064 // Check to see if the top elements are all zeros (or bitcast of zeros).
1065 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1066 N.getOperand(0).getNode()->hasOneUse() &&
1067 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1068 N.getOperand(0).getOperand(0).hasOneUse()) {
1069 // Okay, this is a zero extending load. Fold it.
1070 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1071 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1073 OutChain = LD->getChain();
1074 InChain = SDValue(LD, 1);
1081 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1082 /// mode it matches can be cost effectively emitted as an LEA instruction.
1083 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1084 SDValue &Base, SDValue &Scale,
1085 SDValue &Index, SDValue &Disp) {
1086 X86ISelAddressMode AM;
1087 if (MatchAddress(N, AM))
1090 MVT VT = N.getValueType();
1091 unsigned Complexity = 0;
1092 if (AM.BaseType == X86ISelAddressMode::RegBase)
1093 if (AM.Base.Reg.getNode())
1096 AM.Base.Reg = CurDAG->getRegister(0, VT);
1097 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1100 if (AM.IndexReg.getNode())
1103 AM.IndexReg = CurDAG->getRegister(0, VT);
1105 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1110 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1111 // to a LEA. This is determined with some expermentation but is by no means
1112 // optimal (especially for code size consideration). LEA is nice because of
1113 // its three-address nature. Tweak the cost function again when we can run
1114 // convertToThreeAddress() at register allocation time.
1115 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1116 // For X86-64, we should always use lea to materialize RIP relative
1118 if (Subtarget->is64Bit())
1124 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1127 if (Complexity > 2) {
1128 getAddressOperands(AM, Base, Scale, Index, Disp);
1134 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1135 SDValue &Base, SDValue &Scale,
1136 SDValue &Index, SDValue &Disp) {
1137 if (ISD::isNON_EXTLoad(N.getNode()) &&
1139 IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1140 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1144 /// getGlobalBaseReg - Return an SDNode that returns the value of
1145 /// the global base register. Output instructions required to
1146 /// initialize the global base register, if necessary.
1148 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1149 MachineFunction *MF = CurBB->getParent();
1150 unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF);
1151 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1154 static SDNode *FindCallStartFromCall(SDNode *Node) {
1155 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1156 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1157 "Node doesn't have a token chain argument!");
1158 return FindCallStartFromCall(Node->getOperand(0).getNode());
1161 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1162 /// truncate of the specified operand to i8. This can be done with tablegen,
1163 /// except that this code uses MVT::Flag in a tricky way that happens to
1164 /// improve scheduling in some cases.
1165 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1166 assert(!Subtarget->is64Bit() &&
1167 "getTruncateTo8Bit is only needed on x86-32!");
1168 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1170 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1172 MVT N0VT = N0.getValueType();
1173 switch (N0VT.getSimpleVT()) {
1174 default: assert(0 && "Unknown truncate!");
1176 Opc = X86::MOV16to16_;
1179 Opc = X86::MOV32to32_;
1183 // The use of MVT::Flag here is not strictly accurate, but it helps
1184 // scheduling in some cases.
1185 N0 = SDValue(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
1186 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1187 MVT::i8, N0, SRIdx, N0.getValue(1));
1190 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1191 SDValue Chain = Node->getOperand(0);
1192 SDValue In1 = Node->getOperand(1);
1193 SDValue In2L = Node->getOperand(2);
1194 SDValue In2H = Node->getOperand(3);
1195 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1196 if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3))
1198 SDValue LSI = Node->getOperand(4); // MemOperand
1199 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, In2L, In2H, LSI, Chain };
1200 return CurDAG->getTargetNode(Opc, MVT::i32, MVT::i32, MVT::Other, Ops, 8);
1203 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1204 SDNode *Node = N.getNode();
1205 MVT NVT = Node->getValueType(0);
1207 unsigned Opcode = Node->getOpcode();
1210 DOUT << std::string(Indent, ' ') << "Selecting: ";
1211 DEBUG(Node->dump(CurDAG));
1216 if (Node->isMachineOpcode()) {
1218 DOUT << std::string(Indent-2, ' ') << "== ";
1219 DEBUG(Node->dump(CurDAG));
1223 return NULL; // Already selected.
1228 case X86ISD::GlobalBaseReg:
1229 return getGlobalBaseReg();
1231 case X86ISD::ATOMOR64_DAG:
1232 return SelectAtomic64(Node, X86::ATOMOR6432);
1233 case X86ISD::ATOMXOR64_DAG:
1234 return SelectAtomic64(Node, X86::ATOMXOR6432);
1235 case X86ISD::ATOMADD64_DAG:
1236 return SelectAtomic64(Node, X86::ATOMADD6432);
1237 case X86ISD::ATOMSUB64_DAG:
1238 return SelectAtomic64(Node, X86::ATOMSUB6432);
1239 case X86ISD::ATOMNAND64_DAG:
1240 return SelectAtomic64(Node, X86::ATOMNAND6432);
1241 case X86ISD::ATOMAND64_DAG:
1242 return SelectAtomic64(Node, X86::ATOMAND6432);
1243 case X86ISD::ATOMSWAP64_DAG:
1244 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1246 case ISD::SMUL_LOHI:
1247 case ISD::UMUL_LOHI: {
1248 SDValue N0 = Node->getOperand(0);
1249 SDValue N1 = Node->getOperand(1);
1251 bool isSigned = Opcode == ISD::SMUL_LOHI;
1253 switch (NVT.getSimpleVT()) {
1254 default: assert(0 && "Unsupported VT!");
1255 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1256 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1257 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1258 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1261 switch (NVT.getSimpleVT()) {
1262 default: assert(0 && "Unsupported VT!");
1263 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1264 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1265 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1266 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1269 unsigned LoReg, HiReg;
1270 switch (NVT.getSimpleVT()) {
1271 default: assert(0 && "Unsupported VT!");
1272 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1273 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1274 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1275 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1278 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1279 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1280 // multiplty is commmutative
1282 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1287 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1288 N0, SDValue()).getValue(1);
1291 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1293 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1294 InFlag = SDValue(CNode, 1);
1295 // Update the chain.
1296 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1299 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1302 // Copy the low half of the result, if it is needed.
1303 if (!N.getValue(0).use_empty()) {
1304 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1305 LoReg, NVT, InFlag);
1306 InFlag = Result.getValue(2);
1307 ReplaceUses(N.getValue(0), Result);
1309 DOUT << std::string(Indent-2, ' ') << "=> ";
1310 DEBUG(Result.getNode()->dump(CurDAG));
1314 // Copy the high half of the result, if it is needed.
1315 if (!N.getValue(1).use_empty()) {
1317 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1318 // Prevent use of AH in a REX instruction by referencing AX instead.
1319 // Shift it down 8 bits.
1320 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1321 X86::AX, MVT::i16, InFlag);
1322 InFlag = Result.getValue(2);
1323 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1324 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1325 // Then truncate it down to i8.
1326 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1327 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1328 MVT::i8, Result, SRIdx), 0);
1330 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1331 HiReg, NVT, InFlag);
1332 InFlag = Result.getValue(2);
1334 ReplaceUses(N.getValue(1), Result);
1336 DOUT << std::string(Indent-2, ' ') << "=> ";
1337 DEBUG(Result.getNode()->dump(CurDAG));
1350 case ISD::UDIVREM: {
1351 SDValue N0 = Node->getOperand(0);
1352 SDValue N1 = Node->getOperand(1);
1354 bool isSigned = Opcode == ISD::SDIVREM;
1356 switch (NVT.getSimpleVT()) {
1357 default: assert(0 && "Unsupported VT!");
1358 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1359 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1360 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1361 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1364 switch (NVT.getSimpleVT()) {
1365 default: assert(0 && "Unsupported VT!");
1366 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1367 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1368 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1369 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1372 unsigned LoReg, HiReg;
1373 unsigned ClrOpcode, SExtOpcode;
1374 switch (NVT.getSimpleVT()) {
1375 default: assert(0 && "Unsupported VT!");
1377 LoReg = X86::AL; HiReg = X86::AH;
1379 SExtOpcode = X86::CBW;
1382 LoReg = X86::AX; HiReg = X86::DX;
1383 ClrOpcode = X86::MOV16r0;
1384 SExtOpcode = X86::CWD;
1387 LoReg = X86::EAX; HiReg = X86::EDX;
1388 ClrOpcode = X86::MOV32r0;
1389 SExtOpcode = X86::CDQ;
1392 LoReg = X86::RAX; HiReg = X86::RDX;
1393 ClrOpcode = X86::MOV64r0;
1394 SExtOpcode = X86::CQO;
1398 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1399 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1400 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1403 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1404 // Special case for div8, just use a move with zero extension to AX to
1405 // clear the upper 8 bits (AH).
1406 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1407 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1408 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1410 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1412 Chain = Move.getValue(1);
1413 ReplaceUses(N0.getValue(1), Chain);
1416 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1417 Chain = CurDAG->getEntryNode();
1419 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDValue());
1420 InFlag = Chain.getValue(1);
1423 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1424 LoReg, N0, SDValue()).getValue(1);
1425 if (isSigned && !signBitIsZero) {
1426 // Sign extend the low part into the high part.
1428 SDValue(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1430 // Zero out the high part, effectively zero extending the input.
1431 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1432 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1433 ClrNode, InFlag).getValue(1);
1438 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1440 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1441 InFlag = SDValue(CNode, 1);
1442 // Update the chain.
1443 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1446 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1449 // Copy the division (low) result, if it is needed.
1450 if (!N.getValue(0).use_empty()) {
1451 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1452 LoReg, NVT, InFlag);
1453 InFlag = Result.getValue(2);
1454 ReplaceUses(N.getValue(0), Result);
1456 DOUT << std::string(Indent-2, ' ') << "=> ";
1457 DEBUG(Result.getNode()->dump(CurDAG));
1461 // Copy the remainder (high) result, if it is needed.
1462 if (!N.getValue(1).use_empty()) {
1464 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1465 // Prevent use of AH in a REX instruction by referencing AX instead.
1466 // Shift it down 8 bits.
1467 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1468 X86::AX, MVT::i16, InFlag);
1469 InFlag = Result.getValue(2);
1470 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1471 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1472 // Then truncate it down to i8.
1473 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1474 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1475 MVT::i8, Result, SRIdx), 0);
1477 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1478 HiReg, NVT, InFlag);
1479 InFlag = Result.getValue(2);
1481 ReplaceUses(N.getValue(1), Result);
1483 DOUT << std::string(Indent-2, ' ') << "=> ";
1484 DEBUG(Result.getNode()->dump(CurDAG));
1496 case ISD::SIGN_EXTEND_INREG: {
1497 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1498 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1499 SDValue N0 = Node->getOperand(0);
1501 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1503 switch (NVT.getSimpleVT()) {
1504 default: assert(0 && "Unknown sign_extend_inreg!");
1506 Opc = X86::MOVSX16rr8;
1509 Opc = X86::MOVSX32rr8;
1513 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1516 DOUT << std::string(Indent-2, ' ') << "=> ";
1517 DEBUG(TruncOp.getNode()->dump(CurDAG));
1519 DOUT << std::string(Indent-2, ' ') << "=> ";
1520 DEBUG(ResNode->dump(CurDAG));
1529 case ISD::TRUNCATE: {
1530 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1531 SDValue Input = Node->getOperand(0);
1532 SDNode *ResNode = getTruncateTo8Bit(Input);
1535 DOUT << std::string(Indent-2, ' ') << "=> ";
1536 DEBUG(ResNode->dump(CurDAG));
1545 case ISD::DECLARE: {
1546 // Handle DECLARE nodes here because the second operand may have been
1547 // wrapped in X86ISD::Wrapper.
1548 SDValue Chain = Node->getOperand(0);
1549 SDValue N1 = Node->getOperand(1);
1550 SDValue N2 = Node->getOperand(2);
1551 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N1);
1554 if (N2.getOpcode() == ISD::ADD &&
1555 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1556 N2 = N2.getOperand(1);
1557 if (N2.getOpcode() != X86ISD::Wrapper)
1559 GlobalAddressSDNode *GVNode =
1560 dyn_cast<GlobalAddressSDNode>(N2.getOperand(0));
1563 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FINode->getIndex(),
1564 TLI.getPointerTy());
1565 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GVNode->getGlobal(),
1566 TLI.getPointerTy());
1567 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1568 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1569 MVT::Other, Ops, 3);
1574 SDNode *ResNode = SelectCode(N);
1577 DOUT << std::string(Indent-2, ' ') << "=> ";
1578 if (ResNode == NULL || ResNode == N.getNode())
1579 DEBUG(N.getNode()->dump(CurDAG));
1581 DEBUG(ResNode->dump(CurDAG));
1589 bool X86DAGToDAGISel::
1590 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1591 std::vector<SDValue> &OutOps) {
1592 SDValue Op0, Op1, Op2, Op3;
1593 switch (ConstraintCode) {
1594 case 'o': // offsetable ??
1595 case 'v': // not offsetable ??
1596 default: return true;
1598 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1603 OutOps.push_back(Op0);
1604 OutOps.push_back(Op1);
1605 OutOps.push_back(Op2);
1606 OutOps.push_back(Op3);
1610 /// createX86ISelDag - This pass converts a legalized DAG into a
1611 /// X86-specific DAG, ready for instruction scheduling.
1613 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1614 return new X86DAGToDAGISel(TM, Fast);