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"
46 STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
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 cerr << "X86ISelAddressMode " << this << "\n";
85 if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
87 cerr << " Base.FrameIndex " << Base.FrameIndex << "\n";
88 cerr << "isRIPRel " << isRIPRel << " Scale" << Scale << "\n";
90 if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
92 cerr << " Disp " << Disp << "\n";
93 cerr << "GV "; if (GV) GV->dump();
95 cerr << " CP "; if (CP) CP->dump();
98 cerr << "ES "; if (ES) cerr << ES; else cerr << "nul";
99 cerr << " JT" << JT << " Align" << Align << "\n";
105 //===--------------------------------------------------------------------===//
106 /// ISel - X86 specific code to select X86 machine instructions for
107 /// SelectionDAG operations.
109 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
110 /// TM - Keep a reference to X86TargetMachine.
112 X86TargetMachine &TM;
114 /// X86Lowering - This object fully describes how to lower LLVM code to an
115 /// X86-specific SelectionDAG.
116 X86TargetLowering X86Lowering;
118 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
119 /// make the right decision when generating code for different targets.
120 const X86Subtarget *Subtarget;
122 /// CurBB - Current BB being isel'd.
124 MachineBasicBlock *CurBB;
126 /// OptForSize - If true, selector should try to optimize for code size
127 /// instead of performance.
131 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
132 : SelectionDAGISel(X86Lowering, fast),
133 TM(tm), X86Lowering(*TM.getTargetLowering()),
134 Subtarget(&TM.getSubtarget<X86Subtarget>()),
137 virtual const char *getPassName() const {
138 return "X86 DAG->DAG Instruction Selection";
141 /// InstructionSelect - This callback is invoked by
142 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
143 virtual void InstructionSelect();
145 /// InstructionSelectPostProcessing - Post processing of selected and
146 /// scheduled basic blocks.
147 virtual void InstructionSelectPostProcessing();
149 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
151 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
153 // Include the pieces autogenerated from the target description.
154 #include "X86GenDAGISel.inc"
157 SDNode *Select(SDValue N);
158 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
160 bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
161 bool isRoot = true, unsigned Depth = 0);
162 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
163 bool isRoot, unsigned Depth);
164 bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
165 SDValue &Scale, SDValue &Index, SDValue &Disp);
166 bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
167 SDValue &Scale, SDValue &Index, SDValue &Disp);
168 bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
169 SDValue N, SDValue &Base, SDValue &Scale,
170 SDValue &Index, SDValue &Disp,
171 SDValue &InChain, SDValue &OutChain);
172 bool TryFoldLoad(SDValue P, SDValue N,
173 SDValue &Base, SDValue &Scale,
174 SDValue &Index, SDValue &Disp);
175 void PreprocessForRMW();
176 void PreprocessForFPConvert();
178 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
179 /// inline asm expressions.
180 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
182 std::vector<SDValue> &OutOps);
184 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
186 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
187 SDValue &Scale, SDValue &Index,
189 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
190 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
192 Scale = getI8Imm(AM.Scale);
194 // These are 32-bit even in 64-bit mode since RIP relative offset
197 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
199 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
202 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
203 else if (AM.JT != -1)
204 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
206 Disp = getI32Imm(AM.Disp);
209 /// getI8Imm - Return a target constant with the specified value, of type
211 inline SDValue getI8Imm(unsigned Imm) {
212 return CurDAG->getTargetConstant(Imm, MVT::i8);
215 /// getI16Imm - Return a target constant with the specified value, of type
217 inline SDValue getI16Imm(unsigned Imm) {
218 return CurDAG->getTargetConstant(Imm, MVT::i16);
221 /// getI32Imm - Return a target constant with the specified value, of type
223 inline SDValue getI32Imm(unsigned Imm) {
224 return CurDAG->getTargetConstant(Imm, MVT::i32);
227 /// getGlobalBaseReg - Return an SDNode that returns the value of
228 /// the global base register. Output instructions required to
229 /// initialize the global base register, if necessary.
231 SDNode *getGlobalBaseReg();
233 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
234 /// truncate of the specified operand to i8. This can be done with tablegen,
235 /// except that this code uses MVT::Flag in a tricky way that happens to
236 /// improve scheduling in some cases.
237 SDNode *getTruncateTo8Bit(SDValue N0);
245 /// findFlagUse - Return use of MVT::Flag value produced by the specified
248 static SDNode *findFlagUse(SDNode *N) {
249 unsigned FlagResNo = N->getNumValues()-1;
250 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
252 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
253 SDValue Op = User->getOperand(i);
254 if (Op.getNode() == N && Op.getResNo() == FlagResNo)
261 /// findNonImmUse - Return true by reference in "found" if "Use" is an
262 /// non-immediate use of "Def". This function recursively traversing
263 /// up the operand chain ignoring certain nodes.
264 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
265 SDNode *Root, bool &found,
266 SmallPtrSet<SDNode*, 16> &Visited) {
268 Use->getNodeId() < Def->getNodeId() ||
269 !Visited.insert(Use))
272 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
273 SDNode *N = Use->getOperand(i).getNode();
275 if (Use == ImmedUse || Use == Root)
276 continue; // We are not looking for immediate use.
282 // Traverse up the operand chain.
283 findNonImmUse(N, Def, ImmedUse, Root, found, Visited);
287 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
288 /// be reached. Return true if that's the case. However, ignore direct uses
289 /// by ImmedUse (which would be U in the example illustrated in
290 /// CanBeFoldedBy) and by Root (which can happen in the store case).
291 /// FIXME: to be really generic, we should allow direct use by any node
292 /// that is being folded. But realisticly since we only fold loads which
293 /// have one non-chain use, we only need to watch out for load/op/store
294 /// and load/op/cmp case where the root (store / cmp) may reach the load via
295 /// its chain operand.
296 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
297 SmallPtrSet<SDNode*, 16> Visited;
299 findNonImmUse(Root, Def, ImmedUse, Root, found, Visited);
304 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
305 if (Fast) return false;
307 // If Root use can somehow reach N through a path that that doesn't contain
308 // U then folding N would create a cycle. e.g. In the following
309 // diagram, Root can reach N through X. If N is folded into into Root, then
310 // X is both a predecessor and a successor of U.
321 // * indicates nodes to be folded together.
323 // If Root produces a flag, then it gets (even more) interesting. Since it
324 // will be "glued" together with its flag use in the scheduler, we need to
325 // check if it might reach N.
344 // If FU (flag use) indirectly reaches N (the load), and Root folds N
345 // (call it Fold), then X is a predecessor of FU and a successor of
346 // Fold. But since Fold and FU are flagged together, this will create
347 // a cycle in the scheduling graph.
349 MVT VT = Root->getValueType(Root->getNumValues()-1);
350 while (VT == MVT::Flag) {
351 SDNode *FU = findFlagUse(Root);
355 VT = Root->getValueType(Root->getNumValues()-1);
358 return !isNonImmUse(Root, N, U);
361 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
362 /// and move load below the TokenFactor. Replace store's chain operand with
363 /// load's chain result.
364 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
365 SDValue Store, SDValue TF) {
366 SmallVector<SDValue, 4> Ops;
367 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
368 if (Load.getNode() == TF.getOperand(i).getNode())
369 Ops.push_back(Load.getOperand(0));
371 Ops.push_back(TF.getOperand(i));
372 CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
373 CurDAG->UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
374 CurDAG->UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
375 Store.getOperand(2), Store.getOperand(3));
378 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
380 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
382 if (N.getOpcode() == ISD::BIT_CONVERT)
385 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
386 if (!LD || LD->isVolatile())
388 if (LD->getAddressingMode() != ISD::UNINDEXED)
391 ISD::LoadExtType ExtType = LD->getExtensionType();
392 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
396 N.getOperand(1) == Address &&
397 N.getNode()->isOperandOf(Chain.getNode())) {
404 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
405 /// operand and move load below the call's chain operand.
406 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
407 SDValue Call, SDValue Chain) {
408 SmallVector<SDValue, 8> Ops;
409 for (unsigned i = 0, e = Chain.getNode()->getNumOperands(); i != e; ++i)
410 if (Load.getNode() == Chain.getOperand(i).getNode())
411 Ops.push_back(Load.getOperand(0));
413 Ops.push_back(Chain.getOperand(i));
414 CurDAG->UpdateNodeOperands(Chain, &Ops[0], Ops.size());
415 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
416 Load.getOperand(1), Load.getOperand(2));
418 Ops.push_back(SDValue(Load.getNode(), 1));
419 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
420 Ops.push_back(Call.getOperand(i));
421 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
424 /// isCalleeLoad - Return true if call address is a load and it can be
425 /// moved below CALLSEQ_START and the chains leading up to the call.
426 /// Return the CALLSEQ_START by reference as a second output.
427 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
428 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
430 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
433 LD->getAddressingMode() != ISD::UNINDEXED ||
434 LD->getExtensionType() != ISD::NON_EXTLOAD)
437 // Now let's find the callseq_start.
438 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
439 if (!Chain.hasOneUse())
441 Chain = Chain.getOperand(0);
443 return Chain.getOperand(0).getNode() == Callee.getNode();
447 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
448 /// This is only run if not in -fast mode (aka -O0).
449 /// This allows the instruction selector to pick more read-modify-write
450 /// instructions. This is a common case:
460 /// [TokenFactor] [Op]
467 /// The fact the store's chain operand != load's chain will prevent the
468 /// (store (op (load))) instruction from being selected. We can transform it to:
487 void X86DAGToDAGISel::PreprocessForRMW() {
488 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
489 E = CurDAG->allnodes_end(); I != E; ++I) {
490 if (I->getOpcode() == X86ISD::CALL) {
491 /// Also try moving call address load from outside callseq_start to just
492 /// before the call to allow it to be folded.
510 SDValue Chain = I->getOperand(0);
511 SDValue Load = I->getOperand(1);
512 if (!isCalleeLoad(Load, Chain))
514 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
519 if (!ISD::isNON_TRUNCStore(I))
521 SDValue Chain = I->getOperand(0);
523 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
526 SDValue N1 = I->getOperand(1);
527 SDValue N2 = I->getOperand(2);
528 if ((N1.getValueType().isFloatingPoint() &&
529 !N1.getValueType().isVector()) ||
535 unsigned Opcode = N1.getNode()->getOpcode();
544 case ISD::VECTOR_SHUFFLE: {
545 SDValue N10 = N1.getOperand(0);
546 SDValue N11 = N1.getOperand(1);
547 RModW = isRMWLoad(N10, Chain, N2, Load);
549 RModW = isRMWLoad(N11, Chain, N2, Load);
562 SDValue N10 = N1.getOperand(0);
563 RModW = isRMWLoad(N10, Chain, N2, Load);
569 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
576 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
577 /// nodes that target the FP stack to be store and load to the stack. This is a
578 /// gross hack. We would like to simply mark these as being illegal, but when
579 /// we do that, legalize produces these when it expands calls, then expands
580 /// these in the same legalize pass. We would like dag combine to be able to
581 /// hack on these between the call expansion and the node legalization. As such
582 /// this pass basically does "really late" legalization of these inline with the
584 void X86DAGToDAGISel::PreprocessForFPConvert() {
585 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
586 E = CurDAG->allnodes_end(); I != E; ) {
587 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
588 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
591 // If the source and destination are SSE registers, then this is a legal
592 // conversion that should not be lowered.
593 MVT SrcVT = N->getOperand(0).getValueType();
594 MVT DstVT = N->getValueType(0);
595 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
596 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
597 if (SrcIsSSE && DstIsSSE)
600 if (!SrcIsSSE && !DstIsSSE) {
601 // If this is an FPStack extension, it is a noop.
602 if (N->getOpcode() == ISD::FP_EXTEND)
604 // If this is a value-preserving FPStack truncation, it is a noop.
605 if (N->getConstantOperandVal(1))
609 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
610 // FPStack has extload and truncstore. SSE can fold direct loads into other
611 // operations. Based on this, decide what we want to do.
613 if (N->getOpcode() == ISD::FP_ROUND)
614 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
616 MemVT = SrcIsSSE ? SrcVT : DstVT;
618 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
620 // FIXME: optimize the case where the src/dest is a load or store?
621 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(),
623 MemTmp, NULL, 0, MemVT);
624 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
627 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
628 // extload we created. This will cause general havok on the dag because
629 // anything below the conversion could be folded into other existing nodes.
630 // To avoid invalidating 'I', back it up to the convert node.
632 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
634 // Now that we did that, the node is dead. Increment the iterator to the
635 // next node to process, then delete N.
637 CurDAG->DeleteNode(N);
641 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
642 /// when it has created a SelectionDAG for us to codegen.
643 void X86DAGToDAGISel::InstructionSelect() {
644 CurBB = BB; // BB can change as result of isel.
646 const Function *F = CurDAG->getMachineFunction().getFunction();
647 OptForSize = !F->isDeclaration() &&
648 F->hasFnAttr(Attribute::OptimizeForSize);
655 // FIXME: This should only happen when not -fast.
656 PreprocessForFPConvert();
658 // Codegen the basic block.
660 DOUT << "===== Instruction selection begins:\n";
665 DOUT << "===== Instruction selection ends:\n";
668 CurDAG->RemoveDeadNodes();
671 void X86DAGToDAGISel::InstructionSelectPostProcessing() {
672 // If we are emitting FP stack code, scan the basic block to determine if this
673 // block defines any FP values. If so, put an FP_REG_KILL instruction before
674 // the terminator of the block.
676 // Note that FP stack instructions are used in all modes for long double,
677 // so we always need to do this check.
678 // Also note that it's possible for an FP stack register to be live across
679 // an instruction that produces multiple basic blocks (SSE CMOV) so we
680 // must check all the generated basic blocks.
682 // Scan all of the machine instructions in these MBBs, checking for FP
683 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
684 MachineFunction::iterator MBBI = CurBB;
685 MachineFunction::iterator EndMBB = BB; ++EndMBB;
686 for (; MBBI != EndMBB; ++MBBI) {
687 MachineBasicBlock *MBB = MBBI;
689 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
690 // before the return.
692 MachineBasicBlock::iterator EndI = MBB->end();
694 if (EndI->getDesc().isReturn())
698 bool ContainsFPCode = false;
699 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
700 !ContainsFPCode && I != E; ++I) {
701 if (I->getNumOperands() != 0 && I->getOperand(0).isReg()) {
702 const TargetRegisterClass *clas;
703 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
704 if (I->getOperand(op).isReg() && I->getOperand(op).isDef() &&
705 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
706 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
707 X86::RFP32RegisterClass ||
708 clas == X86::RFP64RegisterClass ||
709 clas == X86::RFP80RegisterClass)) {
710 ContainsFPCode = true;
716 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
717 // a copy of the input value in this block. In SSE mode, we only care about
719 if (!ContainsFPCode) {
720 // Final check, check LLVM BB's that are successors to the LLVM BB
721 // corresponding to BB for FP PHI nodes.
722 const BasicBlock *LLVMBB = BB->getBasicBlock();
724 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
725 !ContainsFPCode && SI != E; ++SI) {
726 for (BasicBlock::const_iterator II = SI->begin();
727 (PN = dyn_cast<PHINode>(II)); ++II) {
728 if (PN->getType()==Type::X86_FP80Ty ||
729 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
730 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
731 ContainsFPCode = true;
737 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
738 if (ContainsFPCode) {
739 BuildMI(*MBB, MBBI->getFirstTerminator(),
740 TM.getInstrInfo()->get(X86::FP_REG_KILL));
746 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
747 /// the main function.
748 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
749 MachineFrameInfo *MFI) {
750 const TargetInstrInfo *TII = TM.getInstrInfo();
751 if (Subtarget->isTargetCygMing())
752 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
755 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
756 // If this is main, emit special code for main.
757 MachineBasicBlock *BB = MF.begin();
758 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
759 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
762 /// MatchAddress - Add the specified node to the specified addressing mode,
763 /// returning true if it cannot be done. This just pattern matches for the
765 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
766 bool isRoot, unsigned Depth) {
767 DOUT << "MatchAddress: "; DEBUG(AM.dump());
770 return MatchAddressBase(N, AM, isRoot, Depth);
772 // RIP relative addressing: %rip + 32-bit displacement!
774 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
775 int64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
776 if (isInt32(AM.Disp + Val)) {
784 int id = N.getNode()->getNodeId();
785 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
787 switch (N.getOpcode()) {
789 case ISD::Constant: {
790 int64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
791 if (isInt32(AM.Disp + Val)) {
798 case X86ISD::Wrapper: {
799 DOUT << "Wrapper: 64bit " << Subtarget->is64Bit();
800 DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
801 DOUT << "AlreadySelected " << AlreadySelected << "\n";
802 bool is64Bit = Subtarget->is64Bit();
803 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
804 // Also, base and index reg must be 0 in order to use rip as base.
805 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
806 AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
808 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
810 // If value is available in a register both base and index components have
811 // been picked, we can't fit the result available in the register in the
812 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
813 if (!AlreadySelected || (AM.Base.Reg.getNode() && AM.IndexReg.getNode())) {
814 SDValue N0 = N.getOperand(0);
815 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
816 GlobalValue *GV = G->getGlobal();
818 AM.Disp += G->getOffset();
819 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
821 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
822 AM.CP = CP->getConstVal();
823 AM.Align = CP->getAlignment();
824 AM.Disp += CP->getOffset();
825 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
827 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
828 AM.ES = S->getSymbol();
829 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
831 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
832 AM.JT = J->getIndex();
833 AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
840 case ISD::FrameIndex:
841 if (AM.BaseType == X86ISelAddressMode::RegBase
842 && AM.Base.Reg.getNode() == 0) {
843 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
844 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
850 if (AlreadySelected || AM.IndexReg.getNode() != 0
851 || AM.Scale != 1 || AM.isRIPRel)
855 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
856 unsigned Val = CN->getZExtValue();
857 if (Val == 1 || Val == 2 || Val == 3) {
859 SDValue ShVal = N.getNode()->getOperand(0);
861 // Okay, we know that we have a scale by now. However, if the scaled
862 // value is an add of something and a constant, we can fold the
863 // constant into the disp field here.
864 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
865 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
866 AM.IndexReg = ShVal.getNode()->getOperand(0);
867 ConstantSDNode *AddVal =
868 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
869 uint64_t Disp = AM.Disp + (AddVal->getZExtValue() << Val);
884 // A mul_lohi where we need the low part can be folded as a plain multiply.
885 if (N.getResNo() != 0) break;
888 // X*[3,5,9] -> X+X*[2,4,8]
889 if (!AlreadySelected &&
890 AM.BaseType == X86ISelAddressMode::RegBase &&
891 AM.Base.Reg.getNode() == 0 &&
892 AM.IndexReg.getNode() == 0 &&
895 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
896 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
897 CN->getZExtValue() == 9) {
898 AM.Scale = unsigned(CN->getZExtValue())-1;
900 SDValue MulVal = N.getNode()->getOperand(0);
903 // Okay, we know that we have a scale by now. However, if the scaled
904 // value is an add of something and a constant, we can fold the
905 // constant into the disp field here.
906 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
907 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
908 Reg = MulVal.getNode()->getOperand(0);
909 ConstantSDNode *AddVal =
910 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
911 uint64_t Disp = AM.Disp + AddVal->getZExtValue() *
916 Reg = N.getNode()->getOperand(0);
918 Reg = N.getNode()->getOperand(0);
921 AM.IndexReg = AM.Base.Reg = Reg;
928 if (!AlreadySelected) {
929 X86ISelAddressMode Backup = AM;
930 if (!MatchAddress(N.getNode()->getOperand(0), AM, false, Depth+1) &&
931 !MatchAddress(N.getNode()->getOperand(1), AM, false, Depth+1))
934 if (!MatchAddress(N.getNode()->getOperand(1), AM, false, Depth+1) &&
935 !MatchAddress(N.getNode()->getOperand(0), AM, false, Depth+1))
942 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
943 if (AlreadySelected) break;
945 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
946 X86ISelAddressMode Backup = AM;
947 // Start with the LHS as an addr mode.
948 if (!MatchAddress(N.getOperand(0), AM, false) &&
949 // Address could not have picked a GV address for the displacement.
951 // On x86-64, the resultant disp must fit in 32-bits.
952 isInt32(AM.Disp + CN->getSExtValue()) &&
953 // Check to see if the LHS & C is zero.
954 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
955 AM.Disp += CN->getZExtValue();
963 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
964 // allows us to fold the shift into this addressing mode.
965 if (AlreadySelected) break;
966 SDValue Shift = N.getOperand(0);
967 if (Shift.getOpcode() != ISD::SHL) break;
969 // Scale must not be used already.
970 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
972 // Not when RIP is used as the base.
973 if (AM.isRIPRel) break;
975 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
976 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
977 if (!C1 || !C2) break;
979 // Not likely to be profitable if either the AND or SHIFT node has more
980 // than one use (unless all uses are for address computation). Besides,
981 // isel mechanism requires their node ids to be reused.
982 if (!N.hasOneUse() || !Shift.hasOneUse())
985 // Verify that the shift amount is something we can fold.
986 unsigned ShiftCst = C1->getZExtValue();
987 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
990 // Get the new AND mask, this folds to a constant.
991 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
992 SDValue(C2, 0), SDValue(C1, 0));
993 SDValue NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
994 Shift.getOperand(0), NewANDMask);
995 NewANDMask.getNode()->setNodeId(Shift.getNode()->getNodeId());
996 NewAND.getNode()->setNodeId(N.getNode()->getNodeId());
998 AM.Scale = 1 << ShiftCst;
999 AM.IndexReg = NewAND;
1004 return MatchAddressBase(N, AM, isRoot, Depth);
1007 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1008 /// specified addressing mode without any further recursion.
1009 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM,
1010 bool isRoot, unsigned Depth) {
1011 // Is the base register already occupied?
1012 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1013 // If so, check to see if the scale index register is set.
1014 if (AM.IndexReg.getNode() == 0 && !AM.isRIPRel) {
1020 // Otherwise, we cannot select it.
1024 // Default, generate it as a register.
1025 AM.BaseType = X86ISelAddressMode::RegBase;
1030 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1031 /// It returns the operands which make up the maximal addressing mode it can
1032 /// match by reference.
1033 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1034 SDValue &Scale, SDValue &Index,
1036 X86ISelAddressMode AM;
1037 if (MatchAddress(N, AM))
1040 MVT VT = N.getValueType();
1041 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1042 if (!AM.Base.Reg.getNode())
1043 AM.Base.Reg = CurDAG->getRegister(0, VT);
1046 if (!AM.IndexReg.getNode())
1047 AM.IndexReg = CurDAG->getRegister(0, VT);
1049 getAddressOperands(AM, Base, Scale, Index, Disp);
1053 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1054 /// match a load whose top elements are either undef or zeros. The load flavor
1055 /// is derived from the type of N, which is either v4f32 or v2f64.
1056 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1057 SDValue N, SDValue &Base,
1058 SDValue &Scale, SDValue &Index,
1059 SDValue &Disp, SDValue &InChain,
1060 SDValue &OutChain) {
1061 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1062 InChain = N.getOperand(0).getValue(1);
1063 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1064 InChain.getValue(0).hasOneUse() &&
1066 CanBeFoldedBy(N.getNode(), Pred.getNode(), Op.getNode())) {
1067 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1068 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1070 OutChain = LD->getChain();
1075 // Also handle the case where we explicitly require zeros in the top
1076 // elements. This is a vector shuffle from the zero vector.
1077 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1078 // Check to see if the top elements are all zeros (or bitcast of zeros).
1079 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1080 N.getOperand(0).getNode()->hasOneUse() &&
1081 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1082 N.getOperand(0).getOperand(0).hasOneUse()) {
1083 // Okay, this is a zero extending load. Fold it.
1084 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1085 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1087 OutChain = LD->getChain();
1088 InChain = SDValue(LD, 1);
1095 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1096 /// mode it matches can be cost effectively emitted as an LEA instruction.
1097 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1098 SDValue &Base, SDValue &Scale,
1099 SDValue &Index, SDValue &Disp) {
1100 X86ISelAddressMode AM;
1101 if (MatchAddress(N, AM))
1104 MVT VT = N.getValueType();
1105 unsigned Complexity = 0;
1106 if (AM.BaseType == X86ISelAddressMode::RegBase)
1107 if (AM.Base.Reg.getNode())
1110 AM.Base.Reg = CurDAG->getRegister(0, VT);
1111 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1114 if (AM.IndexReg.getNode())
1117 AM.IndexReg = CurDAG->getRegister(0, VT);
1119 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1124 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1125 // to a LEA. This is determined with some expermentation but is by no means
1126 // optimal (especially for code size consideration). LEA is nice because of
1127 // its three-address nature. Tweak the cost function again when we can run
1128 // convertToThreeAddress() at register allocation time.
1129 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1130 // For X86-64, we should always use lea to materialize RIP relative
1132 if (Subtarget->is64Bit())
1138 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1141 if (Complexity > 2) {
1142 getAddressOperands(AM, Base, Scale, Index, Disp);
1148 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1149 SDValue &Base, SDValue &Scale,
1150 SDValue &Index, SDValue &Disp) {
1151 if (ISD::isNON_EXTLoad(N.getNode()) &&
1153 CanBeFoldedBy(N.getNode(), P.getNode(), P.getNode()))
1154 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1158 /// getGlobalBaseReg - Return an SDNode that returns the value of
1159 /// the global base register. Output instructions required to
1160 /// initialize the global base register, if necessary.
1162 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1163 MachineFunction *MF = CurBB->getParent();
1164 unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF);
1165 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1168 static SDNode *FindCallStartFromCall(SDNode *Node) {
1169 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1170 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1171 "Node doesn't have a token chain argument!");
1172 return FindCallStartFromCall(Node->getOperand(0).getNode());
1175 /// getTruncateTo8Bit - return an SDNode that implements a subreg based
1176 /// truncate of the specified operand to i8. This can be done with tablegen,
1177 /// except that this code uses MVT::Flag in a tricky way that happens to
1178 /// improve scheduling in some cases.
1179 SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
1180 assert(!Subtarget->is64Bit() &&
1181 "getTruncateTo8Bit is only needed on x86-32!");
1182 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1184 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1186 MVT N0VT = N0.getValueType();
1187 switch (N0VT.getSimpleVT()) {
1188 default: assert(0 && "Unknown truncate!");
1190 Opc = X86::MOV16to16_;
1193 Opc = X86::MOV32to32_;
1197 // The use of MVT::Flag here is not strictly accurate, but it helps
1198 // scheduling in some cases.
1199 N0 = SDValue(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
1200 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1201 MVT::i8, N0, SRIdx, N0.getValue(1));
1204 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1205 SDValue Chain = Node->getOperand(0);
1206 SDValue In1 = Node->getOperand(1);
1207 SDValue In2L = Node->getOperand(2);
1208 SDValue In2H = Node->getOperand(3);
1209 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1210 if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3))
1212 AddToISelQueue(Tmp0);
1213 AddToISelQueue(Tmp1);
1214 AddToISelQueue(Tmp2);
1215 AddToISelQueue(Tmp3);
1216 AddToISelQueue(In2L);
1217 AddToISelQueue(In2H);
1218 AddToISelQueue(Chain);
1219 SDValue LSI = CurDAG->getMemOperand(cast<MemSDNode>(In1)->getMemOperand());
1220 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, In2L, In2H, LSI, Chain };
1221 return CurDAG->getTargetNode(Opc, MVT::i32, MVT::i32, MVT::Other, Ops, 8);
1224 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1225 SDNode *Node = N.getNode();
1226 MVT NVT = Node->getValueType(0);
1228 unsigned Opcode = Node->getOpcode();
1231 DOUT << std::string(Indent, ' ') << "Selecting: ";
1232 DEBUG(Node->dump(CurDAG));
1237 if (Node->isMachineOpcode()) {
1239 DOUT << std::string(Indent-2, ' ') << "== ";
1240 DEBUG(Node->dump(CurDAG));
1244 return NULL; // Already selected.
1249 case X86ISD::GlobalBaseReg:
1250 return getGlobalBaseReg();
1253 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1254 // code and is matched first so to prevent it from being turned into
1256 // In 64-bit small code size mode, use LEA to take advantage of
1257 // RIP-relative addressing.
1258 if (TM.getCodeModel() != CodeModel::Small)
1260 MVT PtrVT = TLI.getPointerTy();
1261 SDValue N0 = N.getOperand(0);
1262 SDValue N1 = N.getOperand(1);
1263 if (N.getNode()->getValueType(0) == PtrVT &&
1264 N0.getOpcode() == X86ISD::Wrapper &&
1265 N1.getOpcode() == ISD::Constant) {
1266 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getZExtValue();
1268 // TODO: handle ExternalSymbolSDNode.
1269 if (GlobalAddressSDNode *G =
1270 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1271 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1272 G->getOffset() + Offset);
1273 } else if (ConstantPoolSDNode *CP =
1274 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1275 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1277 CP->getOffset()+Offset);
1281 if (Subtarget->is64Bit()) {
1282 SDValue Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1283 CurDAG->getRegister(0, PtrVT), C };
1284 return CurDAG->SelectNodeTo(N.getNode(), X86::LEA64r,
1287 return CurDAG->SelectNodeTo(N.getNode(), X86::MOV32ri, PtrVT, C);
1291 // Other cases are handled by auto-generated code.
1295 case X86ISD::ATOMOR64_DAG:
1296 return SelectAtomic64(Node, X86::ATOMOR6432);
1297 case X86ISD::ATOMXOR64_DAG:
1298 return SelectAtomic64(Node, X86::ATOMXOR6432);
1299 case X86ISD::ATOMADD64_DAG:
1300 return SelectAtomic64(Node, X86::ATOMADD6432);
1301 case X86ISD::ATOMSUB64_DAG:
1302 return SelectAtomic64(Node, X86::ATOMSUB6432);
1303 case X86ISD::ATOMNAND64_DAG:
1304 return SelectAtomic64(Node, X86::ATOMNAND6432);
1305 case X86ISD::ATOMAND64_DAG:
1306 return SelectAtomic64(Node, X86::ATOMAND6432);
1308 case ISD::SMUL_LOHI:
1309 case ISD::UMUL_LOHI: {
1310 SDValue N0 = Node->getOperand(0);
1311 SDValue N1 = Node->getOperand(1);
1313 bool isSigned = Opcode == ISD::SMUL_LOHI;
1315 switch (NVT.getSimpleVT()) {
1316 default: assert(0 && "Unsupported VT!");
1317 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1318 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1319 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1320 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1323 switch (NVT.getSimpleVT()) {
1324 default: assert(0 && "Unsupported VT!");
1325 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1326 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1327 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1328 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1331 unsigned LoReg, HiReg;
1332 switch (NVT.getSimpleVT()) {
1333 default: assert(0 && "Unsupported VT!");
1334 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1335 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1336 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1337 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1340 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1341 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1342 // multiplty is commmutative
1344 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1350 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1351 N0, SDValue()).getValue(1);
1354 AddToISelQueue(N1.getOperand(0));
1355 AddToISelQueue(Tmp0);
1356 AddToISelQueue(Tmp1);
1357 AddToISelQueue(Tmp2);
1358 AddToISelQueue(Tmp3);
1359 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1361 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1362 InFlag = SDValue(CNode, 1);
1363 // Update the chain.
1364 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1368 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1371 // Copy the low half of the result, if it is needed.
1372 if (!N.getValue(0).use_empty()) {
1373 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1374 LoReg, NVT, InFlag);
1375 InFlag = Result.getValue(2);
1376 ReplaceUses(N.getValue(0), Result);
1378 DOUT << std::string(Indent-2, ' ') << "=> ";
1379 DEBUG(Result.getNode()->dump(CurDAG));
1383 // Copy the high half of the result, if it is needed.
1384 if (!N.getValue(1).use_empty()) {
1386 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1387 // Prevent use of AH in a REX instruction by referencing AX instead.
1388 // Shift it down 8 bits.
1389 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1390 X86::AX, MVT::i16, InFlag);
1391 InFlag = Result.getValue(2);
1392 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1393 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1394 // Then truncate it down to i8.
1395 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1396 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1397 MVT::i8, Result, SRIdx), 0);
1399 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1400 HiReg, NVT, InFlag);
1401 InFlag = Result.getValue(2);
1403 ReplaceUses(N.getValue(1), Result);
1405 DOUT << std::string(Indent-2, ' ') << "=> ";
1406 DEBUG(Result.getNode()->dump(CurDAG));
1419 case ISD::UDIVREM: {
1420 SDValue N0 = Node->getOperand(0);
1421 SDValue N1 = Node->getOperand(1);
1423 bool isSigned = Opcode == ISD::SDIVREM;
1425 switch (NVT.getSimpleVT()) {
1426 default: assert(0 && "Unsupported VT!");
1427 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1428 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1429 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1430 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1433 switch (NVT.getSimpleVT()) {
1434 default: assert(0 && "Unsupported VT!");
1435 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1436 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1437 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1438 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1441 unsigned LoReg, HiReg;
1442 unsigned ClrOpcode, SExtOpcode;
1443 switch (NVT.getSimpleVT()) {
1444 default: assert(0 && "Unsupported VT!");
1446 LoReg = X86::AL; HiReg = X86::AH;
1448 SExtOpcode = X86::CBW;
1451 LoReg = X86::AX; HiReg = X86::DX;
1452 ClrOpcode = X86::MOV16r0;
1453 SExtOpcode = X86::CWD;
1456 LoReg = X86::EAX; HiReg = X86::EDX;
1457 ClrOpcode = X86::MOV32r0;
1458 SExtOpcode = X86::CDQ;
1461 LoReg = X86::RAX; HiReg = X86::RDX;
1462 ClrOpcode = X86::MOV64r0;
1463 SExtOpcode = X86::CQO;
1467 SDValue Tmp0, Tmp1, Tmp2, Tmp3;
1468 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1471 if (NVT == MVT::i8 && !isSigned) {
1472 // Special case for div8, just use a move with zero extension to AX to
1473 // clear the upper 8 bits (AH).
1474 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1475 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1476 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1477 AddToISelQueue(N0.getOperand(0));
1478 AddToISelQueue(Tmp0);
1479 AddToISelQueue(Tmp1);
1480 AddToISelQueue(Tmp2);
1481 AddToISelQueue(Tmp3);
1483 SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1485 Chain = Move.getValue(1);
1486 ReplaceUses(N0.getValue(1), Chain);
1490 SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1491 Chain = CurDAG->getEntryNode();
1493 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDValue());
1494 InFlag = Chain.getValue(1);
1498 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1499 LoReg, N0, SDValue()).getValue(1);
1501 // Sign extend the low part into the high part.
1503 SDValue(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1505 // Zero out the high part, effectively zero extending the input.
1506 SDValue ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1507 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1508 ClrNode, InFlag).getValue(1);
1513 AddToISelQueue(N1.getOperand(0));
1514 AddToISelQueue(Tmp0);
1515 AddToISelQueue(Tmp1);
1516 AddToISelQueue(Tmp2);
1517 AddToISelQueue(Tmp3);
1518 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1520 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1521 InFlag = SDValue(CNode, 1);
1522 // Update the chain.
1523 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1527 SDValue(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1530 // Copy the division (low) result, if it is needed.
1531 if (!N.getValue(0).use_empty()) {
1532 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1533 LoReg, NVT, InFlag);
1534 InFlag = Result.getValue(2);
1535 ReplaceUses(N.getValue(0), Result);
1537 DOUT << std::string(Indent-2, ' ') << "=> ";
1538 DEBUG(Result.getNode()->dump(CurDAG));
1542 // Copy the remainder (high) result, if it is needed.
1543 if (!N.getValue(1).use_empty()) {
1545 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1546 // Prevent use of AH in a REX instruction by referencing AX instead.
1547 // Shift it down 8 bits.
1548 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1549 X86::AX, MVT::i16, InFlag);
1550 InFlag = Result.getValue(2);
1551 Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1552 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1553 // Then truncate it down to i8.
1554 SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1555 Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1556 MVT::i8, Result, SRIdx), 0);
1558 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1559 HiReg, NVT, InFlag);
1560 InFlag = Result.getValue(2);
1562 ReplaceUses(N.getValue(1), Result);
1564 DOUT << std::string(Indent-2, ' ') << "=> ";
1565 DEBUG(Result.getNode()->dump(CurDAG));
1577 case ISD::SIGN_EXTEND_INREG: {
1578 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1579 if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
1580 SDValue N0 = Node->getOperand(0);
1583 SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
1585 switch (NVT.getSimpleVT()) {
1586 default: assert(0 && "Unknown sign_extend_inreg!");
1588 Opc = X86::MOVSX16rr8;
1591 Opc = X86::MOVSX32rr8;
1595 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1598 DOUT << std::string(Indent-2, ' ') << "=> ";
1599 DEBUG(TruncOp.getNode()->dump(CurDAG));
1601 DOUT << std::string(Indent-2, ' ') << "=> ";
1602 DEBUG(ResNode->dump(CurDAG));
1611 case ISD::TRUNCATE: {
1612 if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
1613 SDValue Input = Node->getOperand(0);
1614 AddToISelQueue(Node->getOperand(0));
1615 SDNode *ResNode = getTruncateTo8Bit(Input);
1618 DOUT << std::string(Indent-2, ' ') << "=> ";
1619 DEBUG(ResNode->dump(CurDAG));
1628 case ISD::DECLARE: {
1629 // Handle DECLARE nodes here because the second operand may have been
1630 // wrapped in X86ISD::Wrapper.
1631 SDValue Chain = Node->getOperand(0);
1632 SDValue N1 = Node->getOperand(1);
1633 SDValue N2 = Node->getOperand(2);
1634 if (!isa<FrameIndexSDNode>(N1))
1636 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1637 if (N2.getOpcode() == ISD::ADD &&
1638 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1639 N2 = N2.getOperand(1);
1640 if (N2.getOpcode() == X86ISD::Wrapper &&
1641 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
1643 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1644 SDValue Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1645 SDValue Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1646 AddToISelQueue(Chain);
1647 SDValue Ops[] = { Tmp1, Tmp2, Chain };
1648 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1649 MVT::Other, Ops, 3);
1655 SDNode *ResNode = SelectCode(N);
1658 DOUT << std::string(Indent-2, ' ') << "=> ";
1659 if (ResNode == NULL || ResNode == N.getNode())
1660 DEBUG(N.getNode()->dump(CurDAG));
1662 DEBUG(ResNode->dump(CurDAG));
1670 bool X86DAGToDAGISel::
1671 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1672 std::vector<SDValue> &OutOps) {
1673 SDValue Op0, Op1, Op2, Op3;
1674 switch (ConstraintCode) {
1675 case 'o': // offsetable ??
1676 case 'v': // not offsetable ??
1677 default: return true;
1679 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1684 OutOps.push_back(Op0);
1685 OutOps.push_back(Op1);
1686 OutOps.push_back(Op2);
1687 OutOps.push_back(Op3);
1688 AddToISelQueue(Op0);
1689 AddToISelQueue(Op1);
1690 AddToISelQueue(Op2);
1691 AddToISelQueue(Op3);
1695 /// createX86ISelDag - This pass converts a legalized DAG into a
1696 /// X86-specific DAG, ready for instruction scheduling.
1698 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1699 return new X86DAGToDAGISel(TM, Fast);