1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Type.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
45 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
46 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
48 //===----------------------------------------------------------------------===//
49 // Pattern Matcher Implementation
50 //===----------------------------------------------------------------------===//
53 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
54 /// SDOperand's instead of register numbers for the leaves of the matched
56 struct X86ISelAddressMode {
62 struct { // This is really a union, discriminated by BaseType!
67 bool isRIPRel; // RIP as base?
75 unsigned Align; // CP alignment.
78 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
79 GV(0), CP(0), ES(0), JT(-1), Align(0) {
85 //===--------------------------------------------------------------------===//
86 /// ISel - X86 specific code to select X86 machine instructions for
87 /// SelectionDAG operations.
89 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
90 /// ContainsFPCode - Every instruction we select that uses or defines a FP
91 /// register should set this to true.
94 /// FastISel - Enable fast(er) instruction selection.
98 /// TM - Keep a reference to X86TargetMachine.
100 X86TargetMachine &TM;
102 /// X86Lowering - This object fully describes how to lower LLVM code to an
103 /// X86-specific SelectionDAG.
104 X86TargetLowering X86Lowering;
106 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
107 /// make the right decision when generating code for different targets.
108 const X86Subtarget *Subtarget;
110 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
112 unsigned GlobalBaseReg;
115 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
116 : SelectionDAGISel(X86Lowering),
117 ContainsFPCode(false), FastISel(fast), TM(tm),
118 X86Lowering(*TM.getTargetLowering()),
119 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
121 virtual bool runOnFunction(Function &Fn) {
122 // Make sure we re-emit a set of the global base reg if necessary
124 return SelectionDAGISel::runOnFunction(Fn);
127 virtual const char *getPassName() const {
128 return "X86 DAG->DAG Instruction Selection";
131 /// InstructionSelectBasicBlock - This callback is invoked by
132 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
133 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
135 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
137 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
139 // Include the pieces autogenerated from the target description.
140 #include "X86GenDAGISel.inc"
143 SDNode *Select(SDOperand N);
145 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
146 bool isRoot = true, unsigned Depth = 0);
147 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
148 bool isRoot, unsigned Depth);
149 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
150 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
151 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
152 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
153 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
154 SDOperand N, SDOperand &Base, SDOperand &Scale,
155 SDOperand &Index, SDOperand &Disp,
156 SDOperand &InChain, SDOperand &OutChain);
157 bool TryFoldLoad(SDOperand P, SDOperand N,
158 SDOperand &Base, SDOperand &Scale,
159 SDOperand &Index, SDOperand &Disp);
160 void PreprocessForRMW(SelectionDAG &DAG);
161 void PreprocessForFPConvert(SelectionDAG &DAG);
163 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
164 /// inline asm expressions.
165 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
167 std::vector<SDOperand> &OutOps,
170 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
172 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
173 SDOperand &Scale, SDOperand &Index,
175 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
176 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
178 Scale = getI8Imm(AM.Scale);
180 // These are 32-bit even in 64-bit mode since RIP relative offset
183 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
185 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
187 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
188 else if (AM.JT != -1)
189 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
191 Disp = getI32Imm(AM.Disp);
194 /// getI8Imm - Return a target constant with the specified value, of type
196 inline SDOperand getI8Imm(unsigned Imm) {
197 return CurDAG->getTargetConstant(Imm, MVT::i8);
200 /// getI16Imm - Return a target constant with the specified value, of type
202 inline SDOperand getI16Imm(unsigned Imm) {
203 return CurDAG->getTargetConstant(Imm, MVT::i16);
206 /// getI32Imm - Return a target constant with the specified value, of type
208 inline SDOperand getI32Imm(unsigned Imm) {
209 return CurDAG->getTargetConstant(Imm, MVT::i32);
212 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
213 /// base register. Return the virtual register that holds this value.
214 SDNode *getGlobalBaseReg();
216 /// getTruncate - return an SDNode that implements a subreg based truncate
217 /// of the specified operand to the the specified value type.
218 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
226 /// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
228 static SDNode *findFlagUse(SDNode *N) {
229 unsigned FlagResNo = N->getNumValues()-1;
230 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
231 SDNode *User = I->getUser();
232 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
233 SDOperand Op = User->getOperand(i);
234 if (Op.Val == N && Op.ResNo == FlagResNo)
241 /// findNonImmUse - Return true by reference in "found" if "Use" is an
242 /// non-immediate use of "Def". This function recursively traversing
243 /// up the operand chain ignoring certain nodes.
244 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
245 SDNode *Root, SDNode *Skip, bool &found,
246 SmallPtrSet<SDNode*, 16> &Visited) {
248 Use->getNodeId() > Def->getNodeId() ||
249 !Visited.insert(Use))
252 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
253 SDNode *N = Use->getOperand(i).Val;
258 continue; // We are not looking for immediate use.
260 // Must be a chain reading node where it is possible to reach its own
261 // chain operand through a path started from another operand.
262 assert(Use->getOpcode() == ISD::STORE ||
263 Use->getOpcode() == X86ISD::CMP ||
264 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
265 Use->getOpcode() == ISD::INTRINSIC_VOID);
272 // Traverse up the operand chain.
273 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
277 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
278 /// be reached. Return true if that's the case. However, ignore direct uses
279 /// by ImmedUse (which would be U in the example illustrated in
280 /// CanBeFoldedBy) and by Root (which can happen in the store case).
281 /// FIXME: to be really generic, we should allow direct use by any node
282 /// that is being folded. But realisticly since we only fold loads which
283 /// have one non-chain use, we only need to watch out for load/op/store
284 /// and load/op/cmp case where the root (store / cmp) may reach the load via
285 /// its chain operand.
286 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
287 SDNode *Skip = NULL) {
288 SmallPtrSet<SDNode*, 16> Visited;
290 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
295 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
296 if (FastISel) return false;
298 // If U use can somehow reach N through another path then U can't fold N or
299 // it will create a cycle. e.g. In the following diagram, U can reach N
300 // through X. If N is folded into into U, then X is both a predecessor and
311 if (isNonImmUse(Root, N, U))
314 // If U produces a flag, then it gets (even more) interesting. Since it
315 // would have been "glued" together with its flag use, we need to check if
328 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
329 // NU), then TF is a predecessor of FU and a successor of NU. But since
330 // NU and FU are flagged together, this effectively creates a cycle.
331 bool HasFlagUse = false;
332 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
333 while ((VT == MVT::Flag && !Root->use_empty())) {
334 SDNode *FU = findFlagUse(Root);
341 VT = Root->getValueType(Root->getNumValues()-1);
345 return !isNonImmUse(Root, N, Root, U);
349 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
350 /// and move load below the TokenFactor. Replace store's chain operand with
351 /// load's chain result.
352 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
353 SDOperand Store, SDOperand TF) {
354 std::vector<SDOperand> Ops;
355 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
356 if (Load.Val == TF.Val->getOperand(i).Val)
357 Ops.push_back(Load.Val->getOperand(0));
359 Ops.push_back(TF.Val->getOperand(i));
360 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
361 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
362 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
363 Store.getOperand(2), Store.getOperand(3));
366 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
368 static bool isRMWLoad(SDOperand N, SDOperand Chain, SDOperand Address,
370 if (N.getOpcode() == ISD::BIT_CONVERT)
373 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
374 if (!LD || LD->isVolatile())
376 if (LD->getAddressingMode() != ISD::UNINDEXED)
379 ISD::LoadExtType ExtType = LD->getExtensionType();
380 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
384 N.getOperand(1) == Address &&
385 N.Val->isOperandOf(Chain.Val)) {
392 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
393 /// This is only run if not in -fast mode (aka -O0).
394 /// This allows the instruction selector to pick more read-modify-write
395 /// instructions. This is a common case:
405 /// [TokenFactor] [Op]
412 /// The fact the store's chain operand != load's chain will prevent the
413 /// (store (op (load))) instruction from being selected. We can transform it to:
432 void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
433 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
434 E = DAG.allnodes_end(); I != E; ++I) {
435 if (!ISD::isNON_TRUNCStore(I))
437 SDOperand Chain = I->getOperand(0);
438 if (Chain.Val->getOpcode() != ISD::TokenFactor)
441 SDOperand N1 = I->getOperand(1);
442 SDOperand N2 = I->getOperand(2);
443 if ((MVT::isFloatingPoint(N1.getValueType()) &&
444 !MVT::isVector(N1.getValueType())) ||
450 unsigned Opcode = N1.Val->getOpcode();
459 case ISD::VECTOR_SHUFFLE: {
460 SDOperand N10 = N1.getOperand(0);
461 SDOperand N11 = N1.getOperand(1);
462 RModW = isRMWLoad(N10, Chain, N2, Load);
464 RModW = isRMWLoad(N11, Chain, N2, Load);
477 SDOperand N10 = N1.getOperand(0);
478 RModW = isRMWLoad(N10, Chain, N2, Load);
484 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
491 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
492 /// nodes that target the FP stack to be store and load to the stack. This is a
493 /// gross hack. We would like to simply mark these as being illegal, but when
494 /// we do that, legalize produces these when it expands calls, then expands
495 /// these in the same legalize pass. We would like dag combine to be able to
496 /// hack on these between the call expansion and the node legalization. As such
497 /// this pass basically does "really late" legalization of these inline with the
499 void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
500 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
501 E = DAG.allnodes_end(); I != E; ) {
502 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
503 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
506 // If the source and destination are SSE registers, then this is a legal
507 // conversion that should not be lowered.
508 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
509 MVT::ValueType DstVT = N->getValueType(0);
510 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
511 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
512 if (SrcIsSSE && DstIsSSE)
515 if (!SrcIsSSE && !DstIsSSE) {
516 // If this is an FPStack extension, it is a noop.
517 if (N->getOpcode() == ISD::FP_EXTEND)
519 // If this is a value-preserving FPStack truncation, it is a noop.
520 if (N->getConstantOperandVal(1))
524 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
525 // FPStack has extload and truncstore. SSE can fold direct loads into other
526 // operations. Based on this, decide what we want to do.
527 MVT::ValueType MemVT;
528 if (N->getOpcode() == ISD::FP_ROUND)
529 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
531 MemVT = SrcIsSSE ? SrcVT : DstVT;
533 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
535 // FIXME: optimize the case where the src/dest is a load or store?
536 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
537 MemTmp, NULL, 0, MemVT);
538 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
541 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
542 // extload we created. This will cause general havok on the dag because
543 // anything below the conversion could be folded into other existing nodes.
544 // To avoid invalidating 'I', back it up to the convert node.
546 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
548 // Now that we did that, the node is dead. Increment the iterator to the
549 // next node to process, then delete N.
555 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
556 /// when it has created a SelectionDAG for us to codegen.
557 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
559 MachineFunction::iterator FirstMBB = BB;
562 PreprocessForRMW(DAG);
564 // FIXME: This should only happen when not -fast.
565 PreprocessForFPConvert(DAG);
567 // Codegen the basic block.
569 DOUT << "===== Instruction selection begins:\n";
572 DAG.setRoot(SelectRoot(DAG.getRoot()));
574 DOUT << "===== Instruction selection ends:\n";
577 DAG.RemoveDeadNodes();
579 // Emit machine code to BB. This can change 'BB' to the last block being
581 ScheduleAndEmitDAG(DAG);
583 // If we are emitting FP stack code, scan the basic block to determine if this
584 // block defines any FP values. If so, put an FP_REG_KILL instruction before
585 // the terminator of the block.
587 // Note that FP stack instructions are used in all modes for long double,
588 // so we always need to do this check.
589 // Also note that it's possible for an FP stack register to be live across
590 // an instruction that produces multiple basic blocks (SSE CMOV) so we
591 // must check all the generated basic blocks.
593 // Scan all of the machine instructions in these MBBs, checking for FP
594 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
595 MachineFunction::iterator MBBI = FirstMBB;
596 MachineFunction::iterator EndMBB = BB; ++EndMBB;
597 for (; MBBI != EndMBB; ++MBBI) {
598 MachineBasicBlock *MBB = MBBI;
600 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
601 // before the return.
603 MachineBasicBlock::iterator EndI = MBB->end();
605 if (EndI->getDesc().isReturn())
609 bool ContainsFPCode = false;
610 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
611 !ContainsFPCode && I != E; ++I) {
612 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
613 const TargetRegisterClass *clas;
614 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
615 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
616 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
617 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
618 X86::RFP32RegisterClass ||
619 clas == X86::RFP64RegisterClass ||
620 clas == X86::RFP80RegisterClass)) {
621 ContainsFPCode = true;
627 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
628 // a copy of the input value in this block. In SSE mode, we only care about
630 if (!ContainsFPCode) {
631 // Final check, check LLVM BB's that are successors to the LLVM BB
632 // corresponding to BB for FP PHI nodes.
633 const BasicBlock *LLVMBB = BB->getBasicBlock();
635 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
636 !ContainsFPCode && SI != E; ++SI) {
637 for (BasicBlock::const_iterator II = SI->begin();
638 (PN = dyn_cast<PHINode>(II)); ++II) {
639 if (PN->getType()==Type::X86_FP80Ty ||
640 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
641 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
642 ContainsFPCode = true;
648 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
649 if (ContainsFPCode) {
650 BuildMI(*MBB, MBBI->getFirstTerminator(),
651 TM.getInstrInfo()->get(X86::FP_REG_KILL));
657 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
658 /// the main function.
659 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
660 MachineFrameInfo *MFI) {
661 const TargetInstrInfo *TII = TM.getInstrInfo();
662 if (Subtarget->isTargetCygMing())
663 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
666 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
667 // If this is main, emit special code for main.
668 MachineBasicBlock *BB = MF.begin();
669 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
670 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
673 /// MatchAddress - Add the specified node to the specified addressing mode,
674 /// returning true if it cannot be done. This just pattern matches for the
676 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
677 bool isRoot, unsigned Depth) {
680 return MatchAddressBase(N, AM, isRoot, Depth);
682 // RIP relative addressing: %rip + 32-bit displacement!
684 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
685 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
686 if (isInt32(AM.Disp + Val)) {
694 int id = N.Val->getNodeId();
695 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
697 switch (N.getOpcode()) {
699 case ISD::Constant: {
700 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
701 if (isInt32(AM.Disp + Val)) {
708 case X86ISD::Wrapper: {
709 bool is64Bit = Subtarget->is64Bit();
710 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
711 // Also, base and index reg must be 0 in order to use rip as base.
712 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
713 AM.Base.Reg.Val || AM.IndexReg.Val))
715 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
717 // If value is available in a register both base and index components have
718 // been picked, we can't fit the result available in the register in the
719 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
720 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
721 SDOperand N0 = N.getOperand(0);
722 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
723 GlobalValue *GV = G->getGlobal();
725 AM.Disp += G->getOffset();
726 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
727 Subtarget->isPICStyleRIPRel();
729 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
730 AM.CP = CP->getConstVal();
731 AM.Align = CP->getAlignment();
732 AM.Disp += CP->getOffset();
733 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
734 Subtarget->isPICStyleRIPRel();
736 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
737 AM.ES = S->getSymbol();
738 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
739 Subtarget->isPICStyleRIPRel();
741 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
742 AM.JT = J->getIndex();
743 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
744 Subtarget->isPICStyleRIPRel();
751 case ISD::FrameIndex:
752 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
753 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
754 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
760 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
763 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
764 unsigned Val = CN->getValue();
765 if (Val == 1 || Val == 2 || Val == 3) {
767 SDOperand ShVal = N.Val->getOperand(0);
769 // Okay, we know that we have a scale by now. However, if the scaled
770 // value is an add of something and a constant, we can fold the
771 // constant into the disp field here.
772 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
773 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
774 AM.IndexReg = ShVal.Val->getOperand(0);
775 ConstantSDNode *AddVal =
776 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
777 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
792 // A mul_lohi where we need the low part can be folded as a plain multiply.
793 if (N.ResNo != 0) break;
796 // X*[3,5,9] -> X+X*[2,4,8]
797 if (!AlreadySelected &&
798 AM.BaseType == X86ISelAddressMode::RegBase &&
799 AM.Base.Reg.Val == 0 &&
800 AM.IndexReg.Val == 0 &&
802 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
803 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
804 AM.Scale = unsigned(CN->getValue())-1;
806 SDOperand MulVal = N.Val->getOperand(0);
809 // Okay, we know that we have a scale by now. However, if the scaled
810 // value is an add of something and a constant, we can fold the
811 // constant into the disp field here.
812 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
813 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
814 Reg = MulVal.Val->getOperand(0);
815 ConstantSDNode *AddVal =
816 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
817 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
821 Reg = N.Val->getOperand(0);
823 Reg = N.Val->getOperand(0);
826 AM.IndexReg = AM.Base.Reg = Reg;
833 if (!AlreadySelected) {
834 X86ISelAddressMode Backup = AM;
835 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
836 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
839 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
840 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
847 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
848 if (AlreadySelected) break;
850 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
851 X86ISelAddressMode Backup = AM;
852 // Start with the LHS as an addr mode.
853 if (!MatchAddress(N.getOperand(0), AM, false) &&
854 // Address could not have picked a GV address for the displacement.
856 // On x86-64, the resultant disp must fit in 32-bits.
857 isInt32(AM.Disp + CN->getSignExtended()) &&
858 // Check to see if the LHS & C is zero.
859 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
860 AM.Disp += CN->getValue();
868 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
869 // allows us to fold the shift into this addressing mode.
870 if (AlreadySelected) break;
871 SDOperand Shift = N.getOperand(0);
872 if (Shift.getOpcode() != ISD::SHL) break;
874 // Scale must not be used already.
875 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
877 // Not when RIP is used as the base.
878 if (AM.isRIPRel) break;
880 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
881 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
882 if (!C1 || !C2) break;
884 // Not likely to be profitable if either the AND or SHIFT node has more
885 // than one use (unless all uses are for address computation). Besides,
886 // isel mechanism requires their node ids to be reused.
887 if (!N.hasOneUse() || !Shift.hasOneUse())
890 // Verify that the shift amount is something we can fold.
891 unsigned ShiftCst = C1->getValue();
892 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
895 // Get the new AND mask, this folds to a constant.
896 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
897 SDOperand(C2, 0), SDOperand(C1, 0));
898 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
899 Shift.getOperand(0), NewANDMask);
900 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
901 NewAND.Val->setNodeId(N.Val->getNodeId());
903 AM.Scale = 1 << ShiftCst;
904 AM.IndexReg = NewAND;
909 return MatchAddressBase(N, AM, isRoot, Depth);
912 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
913 /// specified addressing mode without any further recursion.
914 bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
915 bool isRoot, unsigned Depth) {
916 // Is the base register already occupied?
917 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
918 // If so, check to see if the scale index register is set.
919 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
925 // Otherwise, we cannot select it.
929 // Default, generate it as a register.
930 AM.BaseType = X86ISelAddressMode::RegBase;
935 /// SelectAddr - returns true if it is able pattern match an addressing mode.
936 /// It returns the operands which make up the maximal addressing mode it can
937 /// match by reference.
938 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
939 SDOperand &Scale, SDOperand &Index,
941 X86ISelAddressMode AM;
942 if (MatchAddress(N, AM))
945 MVT::ValueType VT = N.getValueType();
946 if (AM.BaseType == X86ISelAddressMode::RegBase) {
947 if (!AM.Base.Reg.Val)
948 AM.Base.Reg = CurDAG->getRegister(0, VT);
951 if (!AM.IndexReg.Val)
952 AM.IndexReg = CurDAG->getRegister(0, VT);
954 getAddressOperands(AM, Base, Scale, Index, Disp);
958 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
960 static inline bool isZeroNode(SDOperand Elt) {
961 return ((isa<ConstantSDNode>(Elt) &&
962 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
963 (isa<ConstantFPSDNode>(Elt) &&
964 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
968 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
969 /// match a load whose top elements are either undef or zeros. The load flavor
970 /// is derived from the type of N, which is either v4f32 or v2f64.
971 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
972 SDOperand N, SDOperand &Base,
973 SDOperand &Scale, SDOperand &Index,
974 SDOperand &Disp, SDOperand &InChain,
975 SDOperand &OutChain) {
976 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
977 InChain = N.getOperand(0).getValue(1);
978 if (ISD::isNON_EXTLoad(InChain.Val) &&
979 InChain.getValue(0).hasOneUse() &&
981 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
982 LoadSDNode *LD = cast<LoadSDNode>(InChain);
983 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
985 OutChain = LD->getChain();
990 // Also handle the case where we explicitly require zeros in the top
991 // elements. This is a vector shuffle from the zero vector.
992 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
993 // Check to see if the top elements are all zeros (or bitcast of zeros).
994 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
995 N.getOperand(0).Val->hasOneUse() &&
996 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
997 N.getOperand(0).getOperand(0).hasOneUse()) {
998 // Okay, this is a zero extending load. Fold it.
999 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1000 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1002 OutChain = LD->getChain();
1003 InChain = SDOperand(LD, 1);
1010 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1011 /// mode it matches can be cost effectively emitted as an LEA instruction.
1012 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1013 SDOperand &Base, SDOperand &Scale,
1014 SDOperand &Index, SDOperand &Disp) {
1015 X86ISelAddressMode AM;
1016 if (MatchAddress(N, AM))
1019 MVT::ValueType VT = N.getValueType();
1020 unsigned Complexity = 0;
1021 if (AM.BaseType == X86ISelAddressMode::RegBase)
1022 if (AM.Base.Reg.Val)
1025 AM.Base.Reg = CurDAG->getRegister(0, VT);
1026 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1029 if (AM.IndexReg.Val)
1032 AM.IndexReg = CurDAG->getRegister(0, VT);
1034 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1039 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1040 // to a LEA. This is determined with some expermentation but is by no means
1041 // optimal (especially for code size consideration). LEA is nice because of
1042 // its three-address nature. Tweak the cost function again when we can run
1043 // convertToThreeAddress() at register allocation time.
1044 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1045 // For X86-64, we should always use lea to materialize RIP relative
1047 if (Subtarget->is64Bit())
1053 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1056 if (Complexity > 2) {
1057 getAddressOperands(AM, Base, Scale, Index, Disp);
1063 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1064 SDOperand &Base, SDOperand &Scale,
1065 SDOperand &Index, SDOperand &Disp) {
1066 if (ISD::isNON_EXTLoad(N.Val) &&
1068 CanBeFoldedBy(N.Val, P.Val, P.Val))
1069 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1073 /// getGlobalBaseReg - Output the instructions required to put the
1074 /// base address to use for accessing globals into a register.
1076 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1077 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1078 if (!GlobalBaseReg) {
1079 // Insert the set of GlobalBaseReg into the first MBB of the function
1080 MachineFunction *MF = BB->getParent();
1081 MachineBasicBlock &FirstMBB = MF->front();
1082 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
1083 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1084 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1086 const TargetInstrInfo *TII = TM.getInstrInfo();
1087 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1088 // only used in JIT code emission as displacement to pc.
1089 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
1091 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1092 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1093 if (TM.getRelocationModel() == Reloc::PIC_ &&
1094 Subtarget->isPICStyleGOT()) {
1095 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
1096 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1097 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
1103 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1106 static SDNode *FindCallStartFromCall(SDNode *Node) {
1107 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1108 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1109 "Node doesn't have a token chain argument!");
1110 return FindCallStartFromCall(Node->getOperand(0).Val);
1113 SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1117 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1118 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1119 if (!Subtarget->is64Bit()) {
1122 switch (N0.getValueType()) {
1123 default: assert(0 && "Unknown truncate!");
1125 Opc = X86::MOV16to16_;
1129 Opc = X86::MOV32to32_;
1133 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1134 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1135 VT, N0, SRIdx, N0.getValue(1));
1139 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1142 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1144 default: assert(0 && "Unknown truncate!"); break;
1146 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
1150 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1151 SDNode *Node = N.Val;
1152 MVT::ValueType NVT = Node->getValueType(0);
1154 unsigned Opcode = Node->getOpcode();
1157 DOUT << std::string(Indent, ' ') << "Selecting: ";
1158 DEBUG(Node->dump(CurDAG));
1163 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1165 DOUT << std::string(Indent-2, ' ') << "== ";
1166 DEBUG(Node->dump(CurDAG));
1170 return NULL; // Already selected.
1175 case X86ISD::GlobalBaseReg:
1176 return getGlobalBaseReg();
1178 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1179 case X86ISD::RET_FLAG:
1180 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1181 if (Amt->getSignExtended() != 0) break;
1183 // Match (X86retflag 0).
1184 SDOperand Chain = N.getOperand(0);
1185 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1187 SmallVector<SDOperand, 8> Ops0;
1188 AddToISelQueue(Chain);
1189 SDOperand InFlag(0, 0);
1191 InFlag = N.getOperand(N.getNumOperands()-1);
1192 AddToISelQueue(InFlag);
1194 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1196 AddToISelQueue(N.getOperand(i));
1197 Ops0.push_back(N.getOperand(i));
1199 Ops0.push_back(Chain);
1201 Ops0.push_back(InFlag);
1202 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1203 &Ops0[0], Ops0.size());
1208 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1209 // code and is matched first so to prevent it from being turned into
1211 // In 64-bit small code size mode, use LEA to take advantage of
1212 // RIP-relative addressing.
1213 if (TM.getCodeModel() != CodeModel::Small)
1215 MVT::ValueType PtrVT = TLI.getPointerTy();
1216 SDOperand N0 = N.getOperand(0);
1217 SDOperand N1 = N.getOperand(1);
1218 if (N.Val->getValueType(0) == PtrVT &&
1219 N0.getOpcode() == X86ISD::Wrapper &&
1220 N1.getOpcode() == ISD::Constant) {
1221 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1223 // TODO: handle ExternalSymbolSDNode.
1224 if (GlobalAddressSDNode *G =
1225 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1226 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1227 G->getOffset() + Offset);
1228 } else if (ConstantPoolSDNode *CP =
1229 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1230 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1232 CP->getOffset()+Offset);
1236 if (Subtarget->is64Bit()) {
1237 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1238 CurDAG->getRegister(0, PtrVT), C };
1239 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1241 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1245 // Other cases are handled by auto-generated code.
1249 case ISD::SMUL_LOHI:
1250 case ISD::UMUL_LOHI: {
1251 SDOperand N0 = Node->getOperand(0);
1252 SDOperand N1 = Node->getOperand(1);
1254 bool isSigned = Opcode == ISD::SMUL_LOHI;
1257 default: assert(0 && "Unsupported VT!");
1258 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1259 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1260 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1261 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1265 default: assert(0 && "Unsupported VT!");
1266 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1267 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1268 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1269 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1272 unsigned LoReg, HiReg;
1274 default: assert(0 && "Unsupported VT!");
1275 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1276 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1277 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1278 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1281 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1282 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1283 // multiplty is commmutative
1285 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1291 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1292 N0, SDOperand()).getValue(1);
1295 AddToISelQueue(N1.getOperand(0));
1296 AddToISelQueue(Tmp0);
1297 AddToISelQueue(Tmp1);
1298 AddToISelQueue(Tmp2);
1299 AddToISelQueue(Tmp3);
1300 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1302 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1303 InFlag = SDOperand(CNode, 1);
1304 // Update the chain.
1305 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1309 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1312 // Copy the low half of the result, if it is needed.
1313 if (!N.getValue(0).use_empty()) {
1314 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1315 LoReg, NVT, InFlag);
1316 InFlag = Result.getValue(2);
1317 ReplaceUses(N.getValue(0), Result);
1319 DOUT << std::string(Indent-2, ' ') << "=> ";
1320 DEBUG(Result.Val->dump(CurDAG));
1324 // Copy the high half of the result, if it is needed.
1325 if (!N.getValue(1).use_empty()) {
1327 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1328 // Prevent use of AH in a REX instruction by referencing AX instead.
1329 // Shift it down 8 bits.
1330 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1331 X86::AX, MVT::i16, InFlag);
1332 InFlag = Result.getValue(2);
1333 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1334 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1335 // Then truncate it down to i8.
1336 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1337 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1338 MVT::i8, Result, SRIdx), 0);
1340 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1341 HiReg, NVT, InFlag);
1342 InFlag = Result.getValue(2);
1344 ReplaceUses(N.getValue(1), Result);
1346 DOUT << std::string(Indent-2, ' ') << "=> ";
1347 DEBUG(Result.Val->dump(CurDAG));
1360 case ISD::UDIVREM: {
1361 SDOperand N0 = Node->getOperand(0);
1362 SDOperand N1 = Node->getOperand(1);
1364 bool isSigned = Opcode == ISD::SDIVREM;
1367 default: assert(0 && "Unsupported VT!");
1368 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1369 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1370 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1371 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1375 default: assert(0 && "Unsupported VT!");
1376 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1377 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1378 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1379 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1382 unsigned LoReg, HiReg;
1383 unsigned ClrOpcode, SExtOpcode;
1385 default: assert(0 && "Unsupported VT!");
1387 LoReg = X86::AL; HiReg = X86::AH;
1389 SExtOpcode = X86::CBW;
1392 LoReg = X86::AX; HiReg = X86::DX;
1393 ClrOpcode = X86::MOV16r0;
1394 SExtOpcode = X86::CWD;
1397 LoReg = X86::EAX; HiReg = X86::EDX;
1398 ClrOpcode = X86::MOV32r0;
1399 SExtOpcode = X86::CDQ;
1402 LoReg = X86::RAX; HiReg = X86::RDX;
1403 ClrOpcode = X86::MOV64r0;
1404 SExtOpcode = X86::CQO;
1408 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1409 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1412 if (NVT == MVT::i8 && !isSigned) {
1413 // Special case for div8, just use a move with zero extension to AX to
1414 // clear the upper 8 bits (AH).
1415 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1416 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1417 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1418 AddToISelQueue(N0.getOperand(0));
1419 AddToISelQueue(Tmp0);
1420 AddToISelQueue(Tmp1);
1421 AddToISelQueue(Tmp2);
1422 AddToISelQueue(Tmp3);
1424 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1426 Chain = Move.getValue(1);
1427 ReplaceUses(N0.getValue(1), Chain);
1431 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1432 Chain = CurDAG->getEntryNode();
1434 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
1435 InFlag = Chain.getValue(1);
1439 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1440 LoReg, N0, SDOperand()).getValue(1);
1442 // Sign extend the low part into the high part.
1444 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1446 // Zero out the high part, effectively zero extending the input.
1447 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1448 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1449 ClrNode, InFlag).getValue(1);
1454 AddToISelQueue(N1.getOperand(0));
1455 AddToISelQueue(Tmp0);
1456 AddToISelQueue(Tmp1);
1457 AddToISelQueue(Tmp2);
1458 AddToISelQueue(Tmp3);
1459 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1461 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1462 InFlag = SDOperand(CNode, 1);
1463 // Update the chain.
1464 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
1468 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1471 // Copy the division (low) result, if it is needed.
1472 if (!N.getValue(0).use_empty()) {
1473 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1474 LoReg, NVT, InFlag);
1475 InFlag = Result.getValue(2);
1476 ReplaceUses(N.getValue(0), Result);
1478 DOUT << std::string(Indent-2, ' ') << "=> ";
1479 DEBUG(Result.Val->dump(CurDAG));
1483 // Copy the remainder (high) result, if it is needed.
1484 if (!N.getValue(1).use_empty()) {
1486 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1487 // Prevent use of AH in a REX instruction by referencing AX instead.
1488 // Shift it down 8 bits.
1489 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1490 X86::AX, MVT::i16, InFlag);
1491 InFlag = Result.getValue(2);
1492 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1493 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1494 // Then truncate it down to i8.
1495 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1496 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1497 MVT::i8, Result, SRIdx), 0);
1499 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1500 HiReg, NVT, InFlag);
1501 InFlag = Result.getValue(2);
1503 ReplaceUses(N.getValue(1), Result);
1505 DOUT << std::string(Indent-2, ' ') << "=> ";
1506 DEBUG(Result.Val->dump(CurDAG));
1518 case ISD::ANY_EXTEND: {
1519 // Check if the type extended to supports subregs.
1523 SDOperand N0 = Node->getOperand(0);
1524 // Get the subregsiter index for the type to extend.
1525 MVT::ValueType N0VT = N0.getValueType();
1526 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1527 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1528 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1530 // If we don't have a subreg Idx, let generated ISel have a try.
1534 // If we have an index, generate an insert_subreg into undef.
1537 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
1538 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1539 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1540 NVT, Undef, N0, SRIdx);
1543 DOUT << std::string(Indent-2, ' ') << "=> ";
1544 DEBUG(ResNode->dump(CurDAG));
1551 case ISD::SIGN_EXTEND_INREG: {
1552 SDOperand N0 = Node->getOperand(0);
1555 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1556 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
1560 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1561 else assert(0 && "Unknown sign_extend_inreg!");
1565 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1566 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1567 default: assert(0 && "Unknown sign_extend_inreg!");
1572 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1573 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1574 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1575 default: assert(0 && "Unknown sign_extend_inreg!");
1578 default: assert(0 && "Unknown sign_extend_inreg!");
1581 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1584 DOUT << std::string(Indent-2, ' ') << "=> ";
1585 DEBUG(TruncOp.Val->dump(CurDAG));
1587 DOUT << std::string(Indent-2, ' ') << "=> ";
1588 DEBUG(ResNode->dump(CurDAG));
1596 case ISD::TRUNCATE: {
1597 SDOperand Input = Node->getOperand(0);
1598 AddToISelQueue(Node->getOperand(0));
1599 SDNode *ResNode = getTruncate(Input, NVT);
1602 DOUT << std::string(Indent-2, ' ') << "=> ";
1603 DEBUG(ResNode->dump(CurDAG));
1612 SDNode *ResNode = SelectCode(N);
1615 DOUT << std::string(Indent-2, ' ') << "=> ";
1616 if (ResNode == NULL || ResNode == N.Val)
1617 DEBUG(N.Val->dump(CurDAG));
1619 DEBUG(ResNode->dump(CurDAG));
1627 bool X86DAGToDAGISel::
1628 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1629 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1630 SDOperand Op0, Op1, Op2, Op3;
1631 switch (ConstraintCode) {
1632 case 'o': // offsetable ??
1633 case 'v': // not offsetable ??
1634 default: return true;
1636 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1641 OutOps.push_back(Op0);
1642 OutOps.push_back(Op1);
1643 OutOps.push_back(Op2);
1644 OutOps.push_back(Op3);
1645 AddToISelQueue(Op0);
1646 AddToISelQueue(Op1);
1647 AddToISelQueue(Op2);
1648 AddToISelQueue(Op3);
1652 /// createX86ISelDag - This pass converts a legalized DAG into a
1653 /// X86-specific DAG, ready for instruction scheduling.
1655 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1656 return new X86DAGToDAGISel(TM, Fast);