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 #include "llvm/Support/CommandLine.h"
45 static cl::opt<bool> AvoidDupAddrCompute("x86-avoid-dup-address", cl::Hidden);
47 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
49 //===----------------------------------------------------------------------===//
50 // Pattern Matcher Implementation
51 //===----------------------------------------------------------------------===//
54 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
55 /// SDValue's instead of register numbers for the leaves of the matched
57 struct X86ISelAddressMode {
63 struct { // This is really a union, discriminated by BaseType!
68 bool isRIPRel; // RIP as base?
76 unsigned Align; // CP alignment.
79 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
80 GV(0), CP(0), ES(0), JT(-1), Align(0) {
83 bool hasSymbolicDisplacement() const {
84 return GV != 0 || CP != 0 || ES != 0 || JT != -1;
88 cerr << "X86ISelAddressMode " << this << "\n";
90 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
92 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
93 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
95 if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
97 cerr << " Disp " << Disp << "\n";
98 cerr << "GV "; if (GV) GV->dump();
100 cerr << " CP "; if (CP) CP->dump();
103 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
104 cerr << " JT" << JT << " Align" << Align << "\n";
110 //===--------------------------------------------------------------------===//
111 /// ISel - X86 specific code to select X86 machine instructions for
112 /// SelectionDAG operations.
114 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
115 /// TM - Keep a reference to X86TargetMachine.
117 X86TargetMachine &TM;
119 /// X86Lowering - This object fully describes how to lower LLVM code to an
120 /// X86-specific SelectionDAG.
121 X86TargetLowering &X86Lowering;
123 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
124 /// make the right decision when generating code for different targets.
125 const X86Subtarget *Subtarget;
127 /// CurBB - Current BB being isel'd.
129 MachineBasicBlock *CurBB;
131 /// OptForSize - If true, selector should try to optimize for code size
132 /// instead of performance.
136 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
137 : SelectionDAGISel(tm, fast),
138 TM(tm), X86Lowering(*TM.getTargetLowering()),
139 Subtarget(&TM.getSubtarget<X86Subtarget>()),
142 virtual const char *getPassName() const {
143 return "X86 DAG->DAG Instruction Selection";
146 /// InstructionSelect - This callback is invoked by
147 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
148 virtual void InstructionSelect();
150 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
153 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
155 // Include the pieces autogenerated from the target description.
156 #include "X86GenDAGISel.inc"
159 SDNode *Select(SDValue N);
160 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
162 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
164 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
165 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
166 SDValue &Scale, SDValue &Index, SDValue &Disp);
167 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
168 SDValue &Scale, SDValue &Index, SDValue &Disp);
169 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
170 SDValue N, SDValue &Base, SDValue &Scale,
171 SDValue &Index, SDValue &Disp,
172 SDValue &InChain, SDValue &OutChain);
173 bool TryFoldLoad(SDValue P, SDValue N,
174 SDValue &Base, SDValue &Scale,
175 SDValue &Index, SDValue &Disp);
176 void PreprocessForRMW();
177 void PreprocessForFPConvert();
179 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
180 /// inline asm expressions.
181 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
183 std::vector<SDValue> &OutOps);
185 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
187 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
188 SDValue &Scale, SDValue &Index,
190 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
191 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
193 Scale = getI8Imm(AM.Scale);
195 // These are 32-bit even in 64-bit mode since RIP relative offset
198 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
200 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
203 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
204 else if (AM.JT != -1)
205 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
207 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
210 /// getI8Imm - Return a target constant with the specified value, of type
212 inline SDValue getI8Imm(unsigned Imm) {
213 return CurDAG->getTargetConstant(Imm, MVT::i8);
216 /// getI16Imm - Return a target constant with the specified value, of type
218 inline SDValue getI16Imm(unsigned Imm) {
219 return CurDAG->getTargetConstant(Imm, MVT::i16);
222 /// getI32Imm - Return a target constant with the specified value, of type
224 inline SDValue getI32Imm(unsigned Imm) {
225 return CurDAG->getTargetConstant(Imm, MVT::i32);
228 /// getGlobalBaseReg - Return an SDNode that returns the value of
229 /// the global base register. Output instructions required to
230 /// initialize the global base register, if necessary.
232 SDNode *getGlobalBaseReg();
234 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
235 /// truncate of the specified operand to i8. This can be done with tablegen,
236 /// except that this code uses MVT::Flag in a tricky way that happens to
237 /// improve scheduling in some cases.
238 SDNode *getTruncateTo8Bit(SDValue N0);
246 /// findFlagUse - Return use of MVT::Flag value produced by the specified
249 static SDNode *findFlagUse(SDNode *N) {
250 unsigned FlagResNo = N->getNumValues()-1;
251 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
252 SDUse &Use = I.getUse();
253 if (Use.getResNo() == FlagResNo)
254 return Use.getUser();
259 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
260 /// This function recursively traverses up the operand chain, ignoring
262 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
264 SmallPtrSet<SDNode*, 16> &Visited) {
265 if (Use->getNodeId() < Def->getNodeId() ||
266 !Visited.insert(Use))
269 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
270 SDNode *N = Use->getOperand(i).getNode();
272 if (Use == ImmedUse || Use == Root)
273 continue; // We are not looking for immediate use.
278 // Traverse up the operand chain.
279 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
285 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
286 /// be reached. Return true if that's the case. However, ignore direct uses
287 /// by ImmedUse (which would be U in the example illustrated in
288 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
290 /// FIXME: to be really generic, we should allow direct use by any node
291 /// that is being folded. But realisticly since we only fold loads which
292 /// have one non-chain use, we only need to watch out for load/op/store
293 /// and load/op/cmp case where the root (store / cmp) may reach the load via
294 /// its chain operand.
295 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
296 SmallPtrSet<SDNode*, 16> Visited;
297 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
301 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
302 SDNode *Root) const {
303 if (Fast) return false;
306 switch (U->getOpcode()) {
314 // If the other operand is a 8-bit immediate we should fold the immediate
315 // instead. This reduces code size.
317 // movl 4(%esp), %eax
321 // addl 4(%esp), %eax
322 // The former is 2 bytes shorter. In case where the increment is 1, then
323 // the saving can be 4 bytes (by using incl %eax).
324 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(U->getOperand(1)))
325 if (Imm->getAPIntValue().isSignedIntN(8))
330 // If Root use can somehow reach N through a path that that doesn't contain
331 // U then folding N would create a cycle. e.g. In the following
332 // diagram, Root can reach N through X. If N is folded into into Root, then
333 // X is both a predecessor and a successor of U.
344 // * indicates nodes to be folded together.
346 // If Root produces a flag, then it gets (even more) interesting. Since it
347 // will be "glued" together with its flag use in the scheduler, we need to
348 // check if it might reach N.
367 // If FU (flag use) indirectly reaches N (the load), and Root folds N
368 // (call it Fold), then X is a predecessor of FU and a successor of
369 // Fold. But since Fold and FU are flagged together, this will create
370 // a cycle in the scheduling graph.
372 MVT VT = Root->getValueType(Root->getNumValues()-1);
373 while (VT == MVT::Flag) {
374 SDNode *FU = findFlagUse(Root);
378 VT = Root->getValueType(Root->getNumValues()-1);
381 return !isNonImmUse(Root, N, U);
384 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
385 /// and move load below the TokenFactor. Replace store's chain operand with
386 /// load's chain result.
387 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
388 SDValue Store, SDValue TF) {
389 SmallVector<SDValue, 4> Ops;
390 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
391 if (Load.getNode() == TF.getOperand(i).getNode())
392 Ops.push_back(Load.getOperand(0));
394 Ops.push_back(TF.getOperand(i));
395 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
396 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
397 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
398 Store.getOperand(2), Store.getOperand(3));
401 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
403 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
405 if (N.getOpcode() == ISD::BIT_CONVERT)
408 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
409 if (!LD || LD->isVolatile())
411 if (LD->getAddressingMode() != ISD::UNINDEXED)
414 ISD::LoadExtType ExtType = LD->getExtensionType();
415 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
419 N.getOperand(1) == Address &&
420 N.getNode()->isOperandOf(Chain.getNode())) {
427 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
428 /// operand and move load below the call's chain operand.
429 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
430 SDValue Call, SDValue CallSeqStart) {
431 SmallVector<SDValue, 8> Ops;
432 SDValue Chain = CallSeqStart.getOperand(0);
433 if (Chain.getNode() == Load.getNode())
434 Ops.push_back(Load.getOperand(0));
436 assert(Chain.getOpcode() == ISD::TokenFactor &&
437 "Unexpected CallSeqStart chain operand");
438 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
439 if (Chain.getOperand(i).getNode() == Load.getNode())
440 Ops.push_back(Load.getOperand(0));
442 Ops.push_back(Chain.getOperand(i));
444 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
445 MVT::Other, &Ops[0], Ops.size());
447 Ops.push_back(NewChain);
449 for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
450 Ops.push_back(CallSeqStart.getOperand(i));
451 CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
452 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
453 Load.getOperand(1), Load.getOperand(2));
455 Ops.push_back(SDValue(Load.getNode(), 1));
456 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
457 Ops.push_back(Call.getOperand(i));
458 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
461 /// isCalleeLoad - Return true if call address is a load and it can be
462 /// moved below CALLSEQ_START and the chains leading up to the call.
463 /// Return the CALLSEQ_START by reference as a second output.
464 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
465 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
467 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
470 LD->getAddressingMode() != ISD::UNINDEXED ||
471 LD->getExtensionType() != ISD::NON_EXTLOAD)
474 // Now let's find the callseq_start.
475 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
476 if (!Chain.hasOneUse())
478 Chain = Chain.getOperand(0);
481 if (Chain.getOperand(0).getNode() == Callee.getNode())
483 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
484 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
490 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
491 /// This is only run if not in -fast mode (aka -O0).
492 /// This allows the instruction selector to pick more read-modify-write
493 /// instructions. This is a common case:
503 /// [TokenFactor] [Op]
510 /// The fact the store's chain operand != load's chain will prevent the
511 /// (store (op (load))) instruction from being selected. We can transform it to:
530 void X86DAGToDAGISel::PreprocessForRMW() {
531 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
532 E = CurDAG->allnodes_end(); I != E; ++I) {
533 if (I->getOpcode() == X86ISD::CALL) {
534 /// Also try moving call address load from outside callseq_start to just
535 /// before the call to allow it to be folded.
553 SDValue Chain = I->getOperand(0);
554 SDValue Load = I->getOperand(1);
555 if (!isCalleeLoad(Load, Chain))
557 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
562 if (!ISD::isNON_TRUNCStore(I))
564 SDValue Chain = I->getOperand(0);
566 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
569 SDValue N1 = I->getOperand(1);
570 SDValue N2 = I->getOperand(2);
571 if ((N1.getValueType().isFloatingPoint() &&
572 !N1.getValueType().isVector()) ||
578 unsigned Opcode = N1.getNode()->getOpcode();
587 case ISD::VECTOR_SHUFFLE: {
588 SDValue N10 = N1.getOperand(0);
589 SDValue N11 = N1.getOperand(1);
590 RModW = isRMWLoad(N10, Chain, N2, Load);
592 RModW = isRMWLoad(N11, Chain, N2, Load);
605 SDValue N10 = N1.getOperand(0);
606 RModW = isRMWLoad(N10, Chain, N2, Load);
612 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
619 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
620 /// nodes that target the FP stack to be store and load to the stack. This is a
621 /// gross hack. We would like to simply mark these as being illegal, but when
622 /// we do that, legalize produces these when it expands calls, then expands
623 /// these in the same legalize pass. We would like dag combine to be able to
624 /// hack on these between the call expansion and the node legalization. As such
625 /// this pass basically does "really late" legalization of these inline with the
627 void X86DAGToDAGISel::PreprocessForFPConvert() {
628 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
629 E = CurDAG->allnodes_end(); I != E; ) {
630 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
631 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
634 // If the source and destination are SSE registers, then this is a legal
635 // conversion that should not be lowered.
636 MVT SrcVT = N->getOperand(0).getValueType();
637 MVT DstVT = N->getValueType(0);
638 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
639 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
640 if (SrcIsSSE && DstIsSSE)
643 if (!SrcIsSSE && !DstIsSSE) {
644 // If this is an FPStack extension, it is a noop.
645 if (N->getOpcode() == ISD::FP_EXTEND)
647 // If this is a value-preserving FPStack truncation, it is a noop.
648 if (N->getConstantOperandVal(1))
652 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
653 // FPStack has extload and truncstore. SSE can fold direct loads into other
654 // operations. Based on this, decide what we want to do.
656 if (N->getOpcode() == ISD::FP_ROUND)
657 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
659 MemVT = SrcIsSSE ? SrcVT : DstVT;
661 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
662 DebugLoc dl = N->getDebugLoc();
664 // FIXME: optimize the case where the src/dest is a load or store?
665 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
667 MemTmp, NULL, 0, MemVT);
668 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, 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, DebugLoc::getUnknownLoc(),
719 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
722 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
723 // If this is main, emit special code for main.
724 MachineBasicBlock *BB = MF.begin();
725 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
726 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
729 /// MatchAddress - Add the specified node to the specified addressing mode,
730 /// returning true if it cannot be done. This just pattern matches for the
732 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
734 bool is64Bit = Subtarget->is64Bit();
735 DebugLoc dl = N.getDebugLoc();
736 DOUT << "MatchAddress: "; DEBUG(AM.dump());
739 return MatchAddressBase(N, AM);
741 // RIP relative addressing: %rip + 32-bit displacement!
743 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
744 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
745 if (!is64Bit || isInt32(AM.Disp + Val)) {
753 switch (N.getOpcode()) {
755 case ISD::Constant: {
756 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
757 if (!is64Bit || isInt32(AM.Disp + Val)) {
764 case X86ISD::Wrapper: {
765 DOUT << "Wrapper: 64bit " << is64Bit;
766 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
767 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
768 // Also, base and index reg must be 0 in order to use rip as base.
769 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
770 AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
772 if (AM.hasSymbolicDisplacement())
774 // If value is available in a register both base and index components have
775 // been picked, we can't fit the result available in the register in the
776 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
778 SDValue N0 = N.getOperand(0);
779 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
780 uint64_t Offset = G->getOffset();
781 if (!is64Bit || isInt32(AM.Disp + Offset)) {
782 GlobalValue *GV = G->getGlobal();
785 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
788 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
789 uint64_t Offset = CP->getOffset();
790 if (!is64Bit || isInt32(AM.Disp + Offset)) {
791 AM.CP = CP->getConstVal();
792 AM.Align = CP->getAlignment();
794 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
797 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
798 AM.ES = S->getSymbol();
799 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
801 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
802 AM.JT = J->getIndex();
803 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
810 case ISD::FrameIndex:
811 if (AM.BaseType == X86ISelAddressMode::RegBase
812 && AM.Base.Reg.getNode() == 0) {
813 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
814 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
820 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1 || AM.isRIPRel)
824 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
825 unsigned Val = CN->getZExtValue();
826 if (Val == 1 || Val == 2 || Val == 3) {
828 SDValue ShVal = N.getNode()->getOperand(0);
830 // Okay, we know that we have a scale by now. However, if the scaled
831 // value is an add of something and a constant, we can fold the
832 // constant into the disp field here.
833 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
834 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
835 AM.IndexReg = ShVal.getNode()->getOperand(0);
836 ConstantSDNode *AddVal =
837 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
838 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
839 if (!is64Bit || isInt32(Disp))
853 // A mul_lohi where we need the low part can be folded as a plain multiply.
854 if (N.getResNo() != 0) break;
857 case X86ISD::MUL_IMM:
858 // X*[3,5,9] -> X+X*[2,4,8]
859 if (AM.BaseType == X86ISelAddressMode::RegBase &&
860 AM.Base.Reg.getNode() == 0 &&
861 AM.IndexReg.getNode() == 0 &&
864 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
865 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
866 CN->getZExtValue() == 9) {
867 AM.Scale = unsigned(CN->getZExtValue())-1;
869 SDValue MulVal = N.getNode()->getOperand(0);
872 // Okay, we know that we have a scale by now. However, if the scaled
873 // value is an add of something and a constant, we can fold the
874 // constant into the disp field here.
875 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
876 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
877 Reg = MulVal.getNode()->getOperand(0);
878 ConstantSDNode *AddVal =
879 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
880 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
882 if (!is64Bit || isInt32(Disp))
885 Reg = N.getNode()->getOperand(0);
887 Reg = N.getNode()->getOperand(0);
890 AM.IndexReg = AM.Base.Reg = Reg;
897 X86ISelAddressMode Backup = AM;
898 if (!MatchAddress(N.getNode()->getOperand(0), AM, Depth+1) &&
899 !MatchAddress(N.getNode()->getOperand(1), AM, Depth+1))
902 if (!MatchAddress(N.getNode()->getOperand(1), AM, Depth+1) &&
903 !MatchAddress(N.getNode()->getOperand(0), AM, Depth+1))
907 // If we couldn't fold both operands into the address at the same time,
908 // see if we can just put each operand into a register and fold at least
910 if (AM.BaseType == X86ISelAddressMode::RegBase &&
911 !AM.Base.Reg.getNode() &&
912 !AM.IndexReg.getNode() &&
914 AM.Base.Reg = N.getNode()->getOperand(0);
915 AM.IndexReg = N.getNode()->getOperand(1);
923 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
924 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
925 X86ISelAddressMode Backup = AM;
926 uint64_t Offset = CN->getSExtValue();
927 // Start with the LHS as an addr mode.
928 if (!MatchAddress(N.getOperand(0), AM, Depth+1) &&
929 // Address could not have picked a GV address for the displacement.
931 // On x86-64, the resultant disp must fit in 32-bits.
932 (!is64Bit || isInt32(AM.Disp + Offset)) &&
933 // Check to see if the LHS & C is zero.
934 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
943 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
944 // allows us to fold the shift into this addressing mode.
945 SDValue Shift = N.getOperand(0);
946 if (Shift.getOpcode() != ISD::SHL) break;
948 // Scale must not be used already.
949 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
951 // Not when RIP is used as the base.
952 if (AM.isRIPRel) break;
954 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
955 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
956 if (!C1 || !C2) break;
958 // Not likely to be profitable if either the AND or SHIFT node has more
959 // than one use (unless all uses are for address computation). Besides,
960 // isel mechanism requires their node ids to be reused.
961 if (!N.hasOneUse() || !Shift.hasOneUse())
964 // Verify that the shift amount is something we can fold.
965 unsigned ShiftCst = C1->getZExtValue();
966 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
969 // Get the new AND mask, this folds to a constant.
970 SDValue X = Shift.getOperand(0);
971 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
972 SDValue(C2, 0), SDValue(C1, 0));
973 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
975 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
976 NewAND, SDValue(C1, 0));
978 // Insert the new nodes into the topological ordering.
979 if (C1->getNodeId() > X.getNode()->getNodeId()) {
980 CurDAG->RepositionNode(X.getNode(), C1);
981 C1->setNodeId(X.getNode()->getNodeId());
983 if (NewANDMask.getNode()->getNodeId() == -1 ||
984 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
985 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
986 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
988 if (NewAND.getNode()->getNodeId() == -1 ||
989 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
990 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
991 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
993 if (NewSHIFT.getNode()->getNodeId() == -1 ||
994 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
995 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
996 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
999 CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1001 AM.Scale = 1 << ShiftCst;
1002 AM.IndexReg = NewAND;
1007 return MatchAddressBase(N, AM);
1010 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1011 /// specified addressing mode without any further recursion.
1012 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1013 // Is the base register already occupied?
1014 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1015 // If so, check to see if the scale index register is set.
1016 if (AM.IndexReg.getNode() == 0 && !AM.isRIPRel) {
1022 // Otherwise, we cannot select it.
1026 // Default, generate it as a register.
1027 AM.BaseType = X86ISelAddressMode::RegBase;
1032 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1033 /// It returns the operands which make up the maximal addressing mode it can
1034 /// match by reference.
1035 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1036 SDValue &Scale, SDValue &Index,
1038 X86ISelAddressMode AM;
1040 if (AvoidDupAddrCompute && !N.hasOneUse()) {
1041 unsigned Opcode = N.getOpcode();
1042 if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex &&
1043 Opcode != X86ISD::Wrapper) {
1044 // If we are able to fold N into addressing mode, then we'll allow it even
1045 // if N has multiple uses. In general, addressing computation is used as
1046 // addresses by all of its uses. But watch out for CopyToReg uses, that
1047 // means the address computation is liveout. It will be computed by a LEA
1048 // so we want to avoid computing the address twice.
1049 for (SDNode::use_iterator UI = N.getNode()->use_begin(),
1050 UE = N.getNode()->use_end(); UI != UE; ++UI) {
1051 if (UI->getOpcode() == ISD::CopyToReg) {
1052 MatchAddressBase(N, AM);
1060 if (!Done && MatchAddress(N, AM))
1063 MVT VT = N.getValueType();
1064 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1065 if (!AM.Base.Reg.getNode())
1066 AM.Base.Reg = CurDAG->getRegister(0, VT);
1069 if (!AM.IndexReg.getNode())
1070 AM.IndexReg = CurDAG->getRegister(0, VT);
1072 getAddressOperands(AM, Base, Scale, Index, Disp);
1076 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1077 /// match a load whose top elements are either undef or zeros. The load flavor
1078 /// is derived from the type of N, which is either v4f32 or v2f64.
1079 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1080 SDValue N, SDValue &Base,
1081 SDValue &Scale, SDValue &Index,
1082 SDValue &Disp, SDValue &InChain,
1083 SDValue &OutChain) {
1084 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1085 InChain = N.getOperand(0).getValue(1);
1086 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1087 InChain.getValue(0).hasOneUse() &&
1089 IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1090 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1091 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1093 OutChain = LD->getChain();
1098 // Also handle the case where we explicitly require zeros in the top
1099 // elements. This is a vector shuffle from the zero vector.
1100 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1101 // Check to see if the top elements are all zeros (or bitcast of zeros).
1102 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1103 N.getOperand(0).getNode()->hasOneUse() &&
1104 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1105 N.getOperand(0).getOperand(0).hasOneUse()) {
1106 // Okay, this is a zero extending load. Fold it.
1107 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1108 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1110 OutChain = LD->getChain();
1111 InChain = SDValue(LD, 1);
1118 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1119 /// mode it matches can be cost effectively emitted as an LEA instruction.
1120 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1121 SDValue &Base, SDValue &Scale,
1122 SDValue &Index, SDValue &Disp) {
1123 X86ISelAddressMode AM;
1124 if (MatchAddress(N, AM))
1127 MVT VT = N.getValueType();
1128 unsigned Complexity = 0;
1129 if (AM.BaseType == X86ISelAddressMode::RegBase)
1130 if (AM.Base.Reg.getNode())
1133 AM.Base.Reg = CurDAG->getRegister(0, VT);
1134 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1137 if (AM.IndexReg.getNode())
1140 AM.IndexReg = CurDAG->getRegister(0, VT);
1142 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1147 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1148 // to a LEA. This is determined with some expermentation but is by no means
1149 // optimal (especially for code size consideration). LEA is nice because of
1150 // its three-address nature. Tweak the cost function again when we can run
1151 // convertToThreeAddress() at register allocation time.
1152 if (AM.hasSymbolicDisplacement()) {
1153 // For X86-64, we should always use lea to materialize RIP relative
1155 if (Subtarget->is64Bit())
1161 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1164 if (Complexity > 2) {
1165 getAddressOperands(AM, Base, Scale, Index, Disp);
1171 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1172 SDValue &Base, SDValue &Scale,
1173 SDValue &Index, SDValue &Disp) {
1174 if (ISD::isNON_EXTLoad(N.getNode()) &&
1176 IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1177 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1181 /// getGlobalBaseReg - Return an SDNode that returns the value of
1182 /// the global base register. Output instructions required to
1183 /// initialize the global base register, if necessary.
1185 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1186 MachineFunction *MF = CurBB->getParent();
1187 unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF);
1188 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1191 static SDNode *FindCallStartFromCall(SDNode *Node) {
1192 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1193 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1194 "Node doesn't have a token chain argument!");
1195 return FindCallStartFromCall(Node->getOperand(0).getNode());
1198 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1199 /// truncate of the specified operand to i8. This can be done with tablegen,
1200 /// except that this code uses MVT::Flag in a tricky way that happens to
1201 /// improve scheduling in some cases.
1202 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1203 assert(!Subtarget->is64Bit() &&
1204 "getTruncateTo8Bit is only needed on x86-32!");
1205 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1206 DebugLoc dl = N0.getDebugLoc();
1208 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1210 MVT N0VT = N0.getValueType();
1211 switch (N0VT.getSimpleVT()) {
1212 default: assert(0 && "Unknown truncate!");
1214 Opc = X86::MOV16to16_;
1217 Opc = X86::MOV32to32_;
1221 // The use of MVT::Flag here is not strictly accurate, but it helps
1222 // scheduling in some cases.
1223 N0 = SDValue(CurDAG->getTargetNode(Opc, dl, N0VT, MVT::Flag, N0), 0);
1224 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1225 MVT::i8, N0, SRIdx, N0.getValue(1));
1228 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1229 SDValue Chain = Node->getOperand(0);
1230 SDValue In1 = Node->getOperand(1);
1231 SDValue In2L = Node->getOperand(2);
1232 SDValue In2H = Node->getOperand(3);
1233 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1234 if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3))
1236 SDValue LSI = Node->getOperand(4); // MemOperand
1237 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, In2L, In2H, LSI, Chain };
1238 return CurDAG->getTargetNode(Opc, Node->getDebugLoc(),
1239 MVT::i32, MVT::i32, MVT::Other, Ops,
1240 array_lengthof(Ops));
1243 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1244 SDNode *Node = N.getNode();
1245 MVT NVT = Node->getValueType(0);
1247 unsigned Opcode = Node->getOpcode();
1248 DebugLoc dl = Node->getDebugLoc();
1251 DOUT << std::string(Indent, ' ') << "Selecting: ";
1252 DEBUG(Node->dump(CurDAG));
1257 if (Node->isMachineOpcode()) {
1259 DOUT << std::string(Indent-2, ' ') << "== ";
1260 DEBUG(Node->dump(CurDAG));
1264 return NULL; // Already selected.
1269 case X86ISD::GlobalBaseReg:
1270 return getGlobalBaseReg();
1272 case X86ISD::ATOMOR64_DAG:
1273 return SelectAtomic64(Node, X86::ATOMOR6432);
1274 case X86ISD::ATOMXOR64_DAG:
1275 return SelectAtomic64(Node, X86::ATOMXOR6432);
1276 case X86ISD::ATOMADD64_DAG:
1277 return SelectAtomic64(Node, X86::ATOMADD6432);
1278 case X86ISD::ATOMSUB64_DAG:
1279 return SelectAtomic64(Node, X86::ATOMSUB6432);
1280 case X86ISD::ATOMNAND64_DAG:
1281 return SelectAtomic64(Node, X86::ATOMNAND6432);
1282 case X86ISD::ATOMAND64_DAG:
1283 return SelectAtomic64(Node, X86::ATOMAND6432);
1284 case X86ISD::ATOMSWAP64_DAG:
1285 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1287 case ISD::SMUL_LOHI:
1288 case ISD::UMUL_LOHI: {
1289 SDValue N0 = Node->getOperand(0);
1290 SDValue N1 = Node->getOperand(1);
1292 bool isSigned = Opcode == ISD::SMUL_LOHI;
1294 switch (NVT.getSimpleVT()) {
1295 default: assert(0 && "Unsupported VT!");
1296 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1297 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1298 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1299 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1302 switch (NVT.getSimpleVT()) {
1303 default: assert(0 && "Unsupported VT!");
1304 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1305 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1306 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1307 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1310 unsigned LoReg, HiReg;
1311 switch (NVT.getSimpleVT()) {
1312 default: assert(0 && "Unsupported VT!");
1313 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1314 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1315 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1316 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1319 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1320 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1321 // multiplty is commmutative
1323 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1328 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1329 N0, SDValue()).getValue(1);
1332 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1334 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1335 array_lengthof(Ops));
1336 InFlag = SDValue(CNode, 1);
1337 // Update the chain.
1338 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1341 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1344 // Copy the low half of the result, if it is needed.
1345 if (!N.getValue(0).use_empty()) {
1346 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1347 LoReg, NVT, InFlag);
1348 InFlag = Result.getValue(2);
1349 ReplaceUses(N.getValue(0), Result);
1351 DOUT << std::string(Indent-2, ' ') << "=> ";
1352 DEBUG(Result.getNode()->dump(CurDAG));
1356 // Copy the high half of the result, if it is needed.
1357 if (!N.getValue(1).use_empty()) {
1359 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1360 // Prevent use of AH in a REX instruction by referencing AX instead.
1361 // Shift it down 8 bits.
1362 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1363 X86::AX, MVT::i16, InFlag);
1364 InFlag = Result.getValue(2);
1365 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1367 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1368 // Then truncate it down to i8.
1369 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1370 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1371 MVT::i8, Result, SRIdx), 0);
1373 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1374 HiReg, NVT, InFlag);
1375 InFlag = Result.getValue(2);
1377 ReplaceUses(N.getValue(1), Result);
1379 DOUT << std::string(Indent-2, ' ') << "=> ";
1380 DEBUG(Result.getNode()->dump(CurDAG));
1393 case ISD::UDIVREM: {
1394 SDValue N0 = Node->getOperand(0);
1395 SDValue N1 = Node->getOperand(1);
1397 bool isSigned = Opcode == ISD::SDIVREM;
1399 switch (NVT.getSimpleVT()) {
1400 default: assert(0 && "Unsupported VT!");
1401 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1402 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1403 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1404 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1407 switch (NVT.getSimpleVT()) {
1408 default: assert(0 && "Unsupported VT!");
1409 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1410 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1411 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1412 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1415 unsigned LoReg, HiReg;
1416 unsigned ClrOpcode, SExtOpcode;
1417 switch (NVT.getSimpleVT()) {
1418 default: assert(0 && "Unsupported VT!");
1420 LoReg = X86::AL; HiReg = X86::AH;
1422 SExtOpcode = X86::CBW;
1425 LoReg = X86::AX; HiReg = X86::DX;
1426 ClrOpcode = X86::MOV16r0;
1427 SExtOpcode = X86::CWD;
1430 LoReg = X86::EAX; HiReg = X86::EDX;
1431 ClrOpcode = X86::MOV32r0;
1432 SExtOpcode = X86::CDQ;
1435 LoReg = X86::RAX; HiReg = X86::RDX;
1436 ClrOpcode = X86::MOV64r0;
1437 SExtOpcode = X86::CQO;
1441 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1442 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1443 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1446 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1447 // Special case for div8, just use a move with zero extension to AX to
1448 // clear the upper 8 bits (AH).
1449 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1450 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1451 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1453 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, dl, MVT::i16,
1455 array_lengthof(Ops)), 0);
1456 Chain = Move.getValue(1);
1457 ReplaceUses(N0.getValue(1), Chain);
1460 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1461 Chain = CurDAG->getEntryNode();
1463 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1464 InFlag = Chain.getValue(1);
1467 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1468 LoReg, N0, SDValue()).getValue(1);
1469 if (isSigned && !signBitIsZero) {
1470 // Sign extend the low part into the high part.
1472 SDValue(CurDAG->getTargetNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1474 // Zero out the high part, effectively zero extending the input.
1475 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, dl, NVT),
1477 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, HiReg,
1478 ClrNode, InFlag).getValue(1);
1483 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1485 CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1486 array_lengthof(Ops));
1487 InFlag = SDValue(CNode, 1);
1488 // Update the chain.
1489 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1492 SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1495 // Copy the division (low) result, if it is needed.
1496 if (!N.getValue(0).use_empty()) {
1497 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1498 LoReg, NVT, InFlag);
1499 InFlag = Result.getValue(2);
1500 ReplaceUses(N.getValue(0), Result);
1502 DOUT << std::string(Indent-2, ' ') << "=> ";
1503 DEBUG(Result.getNode()->dump(CurDAG));
1507 // Copy the remainder (high) result, if it is needed.
1508 if (!N.getValue(1).use_empty()) {
1510 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1511 // Prevent use of AH in a REX instruction by referencing AX instead.
1512 // Shift it down 8 bits.
1513 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1514 X86::AX, MVT::i16, InFlag);
1515 InFlag = Result.getValue(2);
1516 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1518 CurDAG->getTargetConstant(8, MVT::i8)),
1520 // Then truncate it down to i8.
1521 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1522 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
1523 MVT::i8, Result, SRIdx), 0);
1525 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1526 HiReg, NVT, InFlag);
1527 InFlag = Result.getValue(2);
1529 ReplaceUses(N.getValue(1), Result);
1531 DOUT << std::string(Indent-2, ' ') << "=> ";
1532 DEBUG(Result.getNode()->dump(CurDAG));
1544 case ISD::SIGN_EXTEND_INREG: {
1545 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1546 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1547 SDValue N0 = Node->getOperand(0);
1549 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1551 switch (NVT.getSimpleVT()) {
1552 default: assert(0 && "Unknown sign_extend_inreg!");
1554 Opc = X86::MOVSX16rr8;
1557 Opc = X86::MOVSX32rr8;
1561 SDNode *ResNode = CurDAG->getTargetNode(Opc, dl, NVT, TruncOp);
1564 DOUT << std::string(Indent-2, ' ') << "=> ";
1565 DEBUG(TruncOp.getNode()->dump(CurDAG));
1567 DOUT << std::string(Indent-2, ' ') << "=> ";
1568 DEBUG(ResNode->dump(CurDAG));
1577 case ISD::TRUNCATE: {
1578 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1579 SDValue Input = Node->getOperand(0);
1580 SDNode *ResNode = getTruncateTo8Bit(Input);
1583 DOUT << std::string(Indent-2, ' ') << "=> ";
1584 DEBUG(ResNode->dump(CurDAG));
1593 case ISD::DECLARE: {
1594 // Handle DECLARE nodes here because the second operand may have been
1595 // wrapped in X86ISD::Wrapper.
1596 SDValue Chain = Node->getOperand(0);
1597 SDValue N1 = Node->getOperand(1);
1598 SDValue N2 = Node->getOperand(2);
1599 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N1);
1601 // FIXME: We need to handle this for VLAs.
1603 ReplaceUses(N.getValue(0), Chain);
1607 if (N2.getOpcode() == ISD::ADD &&
1608 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1609 N2 = N2.getOperand(1);
1611 // If N2 is not Wrapper(decriptor) then the llvm.declare is mangled
1612 // somehow, just ignore it.
1613 if (N2.getOpcode() != X86ISD::Wrapper) {
1614 ReplaceUses(N.getValue(0), Chain);
1617 GlobalAddressSDNode *GVNode =
1618 dyn_cast<GlobalAddressSDNode>(N2.getOperand(0));
1620 ReplaceUses(N.getValue(0), Chain);
1623 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FINode->getIndex(),
1624 TLI.getPointerTy());
1625 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GVNode->getGlobal(),
1626 TLI.getPointerTy());
1627 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1628 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE, dl,
1630 array_lengthof(Ops));
1634 SDNode *ResNode = SelectCode(N);
1637 DOUT << std::string(Indent-2, ' ') << "=> ";
1638 if (ResNode == NULL || ResNode == N.getNode())
1639 DEBUG(N.getNode()->dump(CurDAG));
1641 DEBUG(ResNode->dump(CurDAG));
1649 bool X86DAGToDAGISel::
1650 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1651 std::vector<SDValue> &OutOps) {
1652 SDValue Op0, Op1, Op2, Op3;
1653 switch (ConstraintCode) {
1654 case 'o': // offsetable ??
1655 case 'v': // not offsetable ??
1656 default: return true;
1658 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1663 OutOps.push_back(Op0);
1664 OutOps.push_back(Op1);
1665 OutOps.push_back(Op2);
1666 OutOps.push_back(Op3);
1670 /// createX86ISelDag - This pass converts a legalized DAG into a
1671 /// X86-specific DAG, ready for instruction scheduling.
1673 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1674 return new X86DAGToDAGISel(TM, Fast);