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 // Force NDEBUG on in any optimized build on Darwin.
17 // FIXME: This is a huge hack, to work around ridiculously awful compile times
18 // on this file with gcc-4.2 on Darwin, in Release mode.
19 #if (!defined(__llvm__) && defined(__APPLE__) && \
20 defined(__OPTIMIZE__) && !defined(NDEBUG))
24 #define DEBUG_TYPE "x86-isel"
26 #include "X86InstrBuilder.h"
27 #include "X86ISelLowering.h"
28 #include "X86MachineFunctionInfo.h"
29 #include "X86RegisterInfo.h"
30 #include "X86Subtarget.h"
31 #include "X86TargetMachine.h"
32 #include "llvm/GlobalValue.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Intrinsics.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Type.h"
37 #include "llvm/CodeGen/MachineConstantPool.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAGISel.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ADT/SmallPtrSet.h"
50 #include "llvm/ADT/Statistic.h"
53 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
55 //===----------------------------------------------------------------------===//
56 // Pattern Matcher Implementation
57 //===----------------------------------------------------------------------===//
60 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
61 /// SDValue's instead of register numbers for the leaves of the matched
63 struct X86ISelAddressMode {
69 struct { // This is really a union, discriminated by BaseType!
80 BlockAddress *BlockAddr;
83 unsigned Align; // CP alignment.
84 unsigned char SymbolFlags; // X86II::MO_*
87 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
88 Segment(), GV(0), CP(0), BlockAddr(0), ES(0), JT(-1), Align(0),
89 SymbolFlags(X86II::MO_NO_FLAG) {
92 bool hasSymbolicDisplacement() const {
93 return GV != 0 || CP != 0 || ES != 0 || JT != -1 || BlockAddr != 0;
96 bool hasBaseOrIndexReg() const {
97 return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
100 /// isRIPRelative - Return true if this addressing mode is already RIP
102 bool isRIPRelative() const {
103 if (BaseType != RegBase) return false;
104 if (RegisterSDNode *RegNode =
105 dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
106 return RegNode->getReg() == X86::RIP;
110 void setBaseReg(SDValue Reg) {
116 dbgs() << "X86ISelAddressMode " << this << '\n';
117 dbgs() << "Base.Reg ";
118 if (Base.Reg.getNode() != 0)
119 Base.Reg.getNode()->dump();
122 dbgs() << " Base.FrameIndex " << Base.FrameIndex << '\n'
123 << " Scale" << Scale << '\n'
125 if (IndexReg.getNode() != 0)
126 IndexReg.getNode()->dump();
129 dbgs() << " Disp " << Disp << '\n'
146 dbgs() << " JT" << JT << " Align" << Align << '\n';
152 //===--------------------------------------------------------------------===//
153 /// ISel - X86 specific code to select X86 machine instructions for
154 /// SelectionDAG operations.
156 class X86DAGToDAGISel : public SelectionDAGISel {
157 /// X86Lowering - This object fully describes how to lower LLVM code to an
158 /// X86-specific SelectionDAG.
159 X86TargetLowering &X86Lowering;
161 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
162 /// make the right decision when generating code for different targets.
163 const X86Subtarget *Subtarget;
165 /// OptForSize - If true, selector should try to optimize for code size
166 /// instead of performance.
170 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
171 : SelectionDAGISel(tm, OptLevel),
172 X86Lowering(*tm.getTargetLowering()),
173 Subtarget(&tm.getSubtarget<X86Subtarget>()),
176 virtual const char *getPassName() const {
177 return "X86 DAG->DAG Instruction Selection";
180 /// InstructionSelect - This callback is invoked by
181 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
182 virtual void InstructionSelect();
184 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
187 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
189 // Include the pieces autogenerated from the target description.
190 #include "X86GenDAGISel.inc"
193 SDNode *Select(SDNode *N);
194 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
195 SDNode *SelectAtomicLoadAdd(SDNode *Node, EVT NVT);
197 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
198 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
199 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
200 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
201 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
203 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
204 bool SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
205 SDValue &Scale, SDValue &Index, SDValue &Disp,
207 bool SelectLEAAddr(SDNode *Op, SDValue N, SDValue &Base,
208 SDValue &Scale, SDValue &Index, SDValue &Disp);
209 bool SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
210 SDValue &Scale, SDValue &Index, SDValue &Disp);
211 bool SelectScalarSSELoad(SDNode *Op, SDValue Pred,
212 SDValue N, SDValue &Base, SDValue &Scale,
213 SDValue &Index, SDValue &Disp,
215 SDValue &InChain, SDValue &OutChain);
216 bool TryFoldLoad(SDNode *P, SDValue N,
217 SDValue &Base, SDValue &Scale,
218 SDValue &Index, SDValue &Disp,
220 void PreprocessForRMW();
221 void PreprocessForFPConvert();
223 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
224 /// inline asm expressions.
225 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
227 std::vector<SDValue> &OutOps);
229 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
231 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
232 SDValue &Scale, SDValue &Index,
233 SDValue &Disp, SDValue &Segment) {
234 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
235 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
237 Scale = getI8Imm(AM.Scale);
239 // These are 32-bit even in 64-bit mode since RIP relative offset
242 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
245 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
246 AM.Align, AM.Disp, AM.SymbolFlags);
248 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
249 else if (AM.JT != -1)
250 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
251 else if (AM.BlockAddr)
252 Disp = CurDAG->getBlockAddress(AM.BlockAddr, MVT::i32,
253 true, AM.SymbolFlags);
255 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
257 if (AM.Segment.getNode())
258 Segment = AM.Segment;
260 Segment = CurDAG->getRegister(0, MVT::i32);
263 /// getI8Imm - Return a target constant with the specified value, of type
265 inline SDValue getI8Imm(unsigned Imm) {
266 return CurDAG->getTargetConstant(Imm, MVT::i8);
269 /// getI16Imm - Return a target constant with the specified value, of type
271 inline SDValue getI16Imm(unsigned Imm) {
272 return CurDAG->getTargetConstant(Imm, MVT::i16);
275 /// getI32Imm - Return a target constant with the specified value, of type
277 inline SDValue getI32Imm(unsigned Imm) {
278 return CurDAG->getTargetConstant(Imm, MVT::i32);
281 /// getGlobalBaseReg - Return an SDNode that returns the value of
282 /// the global base register. Output instructions required to
283 /// initialize the global base register, if necessary.
285 SDNode *getGlobalBaseReg();
287 /// getTargetMachine - Return a reference to the TargetMachine, casted
288 /// to the target-specific type.
289 const X86TargetMachine &getTargetMachine() {
290 return static_cast<const X86TargetMachine &>(TM);
293 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
294 /// to the target-specific type.
295 const X86InstrInfo *getInstrInfo() {
296 return getTargetMachine().getInstrInfo();
306 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
307 SDNode *Root) const {
308 if (OptLevel == CodeGenOpt::None) return false;
311 switch (U->getOpcode()) {
324 SDValue Op1 = U->getOperand(1);
326 // If the other operand is a 8-bit immediate we should fold the immediate
327 // instead. This reduces code size.
329 // movl 4(%esp), %eax
333 // addl 4(%esp), %eax
334 // The former is 2 bytes shorter. In case where the increment is 1, then
335 // the saving can be 4 bytes (by using incl %eax).
336 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
337 if (Imm->getAPIntValue().isSignedIntN(8))
340 // If the other operand is a TLS address, we should fold it instead.
343 // leal i@NTPOFF(%eax), %eax
345 // movl $i@NTPOFF, %eax
347 // if the block also has an access to a second TLS address this will save
349 // FIXME: This is probably also true for non TLS addresses.
350 if (Op1.getOpcode() == X86ISD::Wrapper) {
351 SDValue Val = Op1.getOperand(0);
352 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
358 // Proceed to 'generic' cycle finder code
359 return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
362 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
363 /// and move load below the TokenFactor. Replace store's chain operand with
364 /// load's chain result.
365 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
366 SDValue Store, SDValue TF) {
367 SmallVector<SDValue, 4> Ops;
368 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
369 if (Load.getNode() == TF.getOperand(i).getNode())
370 Ops.push_back(Load.getOperand(0));
372 Ops.push_back(TF.getOperand(i));
373 SDValue NewTF = CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
374 SDValue NewLoad = CurDAG->UpdateNodeOperands(Load, NewTF,
377 CurDAG->UpdateNodeOperands(Store, NewLoad.getValue(1), Store.getOperand(1),
378 Store.getOperand(2), Store.getOperand(3));
381 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG. The
382 /// chain produced by the load must only be used by the store's chain operand,
383 /// otherwise this may produce a cycle in the DAG.
385 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
387 if (N.getOpcode() == ISD::BIT_CONVERT)
390 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
391 if (!LD || LD->isVolatile())
393 if (LD->getAddressingMode() != ISD::UNINDEXED)
396 ISD::LoadExtType ExtType = LD->getExtensionType();
397 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
401 LD->hasNUsesOfValue(1, 1) &&
402 N.getOperand(1) == Address &&
403 LD->isOperandOf(Chain.getNode())) {
410 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
411 /// operand and move load below the call's chain operand.
412 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
413 SDValue Call, SDValue CallSeqStart) {
414 SmallVector<SDValue, 8> Ops;
415 SDValue Chain = CallSeqStart.getOperand(0);
416 if (Chain.getNode() == Load.getNode())
417 Ops.push_back(Load.getOperand(0));
419 assert(Chain.getOpcode() == ISD::TokenFactor &&
420 "Unexpected CallSeqStart chain operand");
421 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
422 if (Chain.getOperand(i).getNode() == Load.getNode())
423 Ops.push_back(Load.getOperand(0));
425 Ops.push_back(Chain.getOperand(i));
427 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
428 MVT::Other, &Ops[0], Ops.size());
430 Ops.push_back(NewChain);
432 for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
433 Ops.push_back(CallSeqStart.getOperand(i));
434 CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
435 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
436 Load.getOperand(1), Load.getOperand(2));
438 Ops.push_back(SDValue(Load.getNode(), 1));
439 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
440 Ops.push_back(Call.getOperand(i));
441 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
444 /// isCalleeLoad - Return true if call address is a load and it can be
445 /// moved below CALLSEQ_START and the chains leading up to the call.
446 /// Return the CALLSEQ_START by reference as a second output.
447 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
448 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
450 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
453 LD->getAddressingMode() != ISD::UNINDEXED ||
454 LD->getExtensionType() != ISD::NON_EXTLOAD)
457 // Now let's find the callseq_start.
458 while (Chain.getOpcode() != ISD::CALLSEQ_START) {
459 if (!Chain.hasOneUse())
461 Chain = Chain.getOperand(0);
464 if (Chain.getOperand(0).getNode() == Callee.getNode())
466 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
467 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
468 Callee.getValue(1).hasOneUse())
474 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
475 /// This is only run if not in -O0 mode.
476 /// This allows the instruction selector to pick more read-modify-write
477 /// instructions. This is a common case:
487 /// [TokenFactor] [Op]
494 /// The fact the store's chain operand != load's chain will prevent the
495 /// (store (op (load))) instruction from being selected. We can transform it to:
514 void X86DAGToDAGISel::PreprocessForRMW() {
515 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
516 E = CurDAG->allnodes_end(); I != E; ++I) {
517 if (I->getOpcode() == X86ISD::CALL) {
518 /// Also try moving call address load from outside callseq_start to just
519 /// before the call to allow it to be folded.
537 SDValue Chain = I->getOperand(0);
538 SDValue Load = I->getOperand(1);
539 if (!isCalleeLoad(Load, Chain))
541 MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
546 if (!ISD::isNON_TRUNCStore(I))
548 SDValue Chain = I->getOperand(0);
550 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
553 SDValue N1 = I->getOperand(1);
554 SDValue N2 = I->getOperand(2);
555 if ((N1.getValueType().isFloatingPoint() &&
556 !N1.getValueType().isVector()) ||
562 unsigned Opcode = N1.getNode()->getOpcode();
571 case ISD::VECTOR_SHUFFLE: {
572 SDValue N10 = N1.getOperand(0);
573 SDValue N11 = N1.getOperand(1);
574 RModW = isRMWLoad(N10, Chain, N2, Load);
576 RModW = isRMWLoad(N11, Chain, N2, Load);
589 SDValue N10 = N1.getOperand(0);
590 RModW = isRMWLoad(N10, Chain, N2, Load);
596 MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
603 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
604 /// nodes that target the FP stack to be store and load to the stack. This is a
605 /// gross hack. We would like to simply mark these as being illegal, but when
606 /// we do that, legalize produces these when it expands calls, then expands
607 /// these in the same legalize pass. We would like dag combine to be able to
608 /// hack on these between the call expansion and the node legalization. As such
609 /// this pass basically does "really late" legalization of these inline with the
611 void X86DAGToDAGISel::PreprocessForFPConvert() {
612 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
613 E = CurDAG->allnodes_end(); I != E; ) {
614 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
615 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
618 // If the source and destination are SSE registers, then this is a legal
619 // conversion that should not be lowered.
620 EVT SrcVT = N->getOperand(0).getValueType();
621 EVT DstVT = N->getValueType(0);
622 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
623 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
624 if (SrcIsSSE && DstIsSSE)
627 if (!SrcIsSSE && !DstIsSSE) {
628 // If this is an FPStack extension, it is a noop.
629 if (N->getOpcode() == ISD::FP_EXTEND)
631 // If this is a value-preserving FPStack truncation, it is a noop.
632 if (N->getConstantOperandVal(1))
636 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
637 // FPStack has extload and truncstore. SSE can fold direct loads into other
638 // operations. Based on this, decide what we want to do.
640 if (N->getOpcode() == ISD::FP_ROUND)
641 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
643 MemVT = SrcIsSSE ? SrcVT : DstVT;
645 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
646 DebugLoc dl = N->getDebugLoc();
648 // FIXME: optimize the case where the src/dest is a load or store?
649 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
651 MemTmp, NULL, 0, MemVT);
652 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
655 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
656 // extload we created. This will cause general havok on the dag because
657 // anything below the conversion could be folded into other existing nodes.
658 // To avoid invalidating 'I', back it up to the convert node.
660 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
662 // Now that we did that, the node is dead. Increment the iterator to the
663 // next node to process, then delete N.
665 CurDAG->DeleteNode(N);
669 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
670 /// when it has created a SelectionDAG for us to codegen.
671 void X86DAGToDAGISel::InstructionSelect() {
672 const Function *F = MF->getFunction();
673 OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
675 if (OptLevel != CodeGenOpt::None)
678 // FIXME: This should only happen when not compiled with -O0.
679 PreprocessForFPConvert();
681 // Codegen the basic block.
683 DEBUG(dbgs() << "===== Instruction selection begins:\n");
688 DEBUG(dbgs() << "===== Instruction selection ends:\n");
691 CurDAG->RemoveDeadNodes();
694 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
695 /// the main function.
696 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
697 MachineFrameInfo *MFI) {
698 const TargetInstrInfo *TII = TM.getInstrInfo();
699 if (Subtarget->isTargetCygMing())
700 BuildMI(BB, DebugLoc::getUnknownLoc(),
701 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
704 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
705 // If this is main, emit special code for main.
706 MachineBasicBlock *BB = MF.begin();
707 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
708 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
712 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
713 X86ISelAddressMode &AM) {
714 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
715 SDValue Segment = N.getOperand(0);
717 if (AM.Segment.getNode() == 0) {
718 AM.Segment = Segment;
725 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
726 // This optimization is valid because the GNU TLS model defines that
727 // gs:0 (or fs:0 on X86-64) contains its own address.
728 // For more information see http://people.redhat.com/drepper/tls.pdf
730 SDValue Address = N.getOperand(1);
731 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
732 !MatchSegmentBaseAddress (Address, AM))
738 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
739 /// into an addressing mode. These wrap things that will resolve down into a
740 /// symbol reference. If no match is possible, this returns true, otherwise it
742 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
743 // If the addressing mode already has a symbol as the displacement, we can
744 // never match another symbol.
745 if (AM.hasSymbolicDisplacement())
748 SDValue N0 = N.getOperand(0);
749 CodeModel::Model M = TM.getCodeModel();
751 // Handle X86-64 rip-relative addresses. We check this before checking direct
752 // folding because RIP is preferable to non-RIP accesses.
753 if (Subtarget->is64Bit() &&
754 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
755 // they cannot be folded into immediate fields.
756 // FIXME: This can be improved for kernel and other models?
757 (M == CodeModel::Small || M == CodeModel::Kernel) &&
758 // Base and index reg must be 0 in order to use %rip as base and lowering
760 !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
761 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
762 int64_t Offset = AM.Disp + G->getOffset();
763 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
764 AM.GV = G->getGlobal();
766 AM.SymbolFlags = G->getTargetFlags();
767 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
768 int64_t Offset = AM.Disp + CP->getOffset();
769 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
770 AM.CP = CP->getConstVal();
771 AM.Align = CP->getAlignment();
773 AM.SymbolFlags = CP->getTargetFlags();
774 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
775 AM.ES = S->getSymbol();
776 AM.SymbolFlags = S->getTargetFlags();
777 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
778 AM.JT = J->getIndex();
779 AM.SymbolFlags = J->getTargetFlags();
781 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
782 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
785 if (N.getOpcode() == X86ISD::WrapperRIP)
786 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
790 // Handle the case when globals fit in our immediate field: This is true for
791 // X86-32 always and X86-64 when in -static -mcmodel=small mode. In 64-bit
792 // mode, this results in a non-RIP-relative computation.
793 if (!Subtarget->is64Bit() ||
794 ((M == CodeModel::Small || M == CodeModel::Kernel) &&
795 TM.getRelocationModel() == Reloc::Static)) {
796 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
797 AM.GV = G->getGlobal();
798 AM.Disp += G->getOffset();
799 AM.SymbolFlags = G->getTargetFlags();
800 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
801 AM.CP = CP->getConstVal();
802 AM.Align = CP->getAlignment();
803 AM.Disp += CP->getOffset();
804 AM.SymbolFlags = CP->getTargetFlags();
805 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
806 AM.ES = S->getSymbol();
807 AM.SymbolFlags = S->getTargetFlags();
808 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
809 AM.JT = J->getIndex();
810 AM.SymbolFlags = J->getTargetFlags();
812 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
813 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
821 /// MatchAddress - Add the specified node to the specified addressing mode,
822 /// returning true if it cannot be done. This just pattern matches for the
824 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
825 if (MatchAddressRecursively(N, AM, 0))
828 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
829 // a smaller encoding and avoids a scaled-index.
831 AM.BaseType == X86ISelAddressMode::RegBase &&
832 AM.Base.Reg.getNode() == 0) {
833 AM.Base.Reg = AM.IndexReg;
837 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
838 // because it has a smaller encoding.
839 // TODO: Which other code models can use this?
840 if (TM.getCodeModel() == CodeModel::Small &&
841 Subtarget->is64Bit() &&
843 AM.BaseType == X86ISelAddressMode::RegBase &&
844 AM.Base.Reg.getNode() == 0 &&
845 AM.IndexReg.getNode() == 0 &&
846 AM.SymbolFlags == X86II::MO_NO_FLAG &&
847 AM.hasSymbolicDisplacement())
848 AM.Base.Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
853 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
855 bool is64Bit = Subtarget->is64Bit();
856 DebugLoc dl = N.getDebugLoc();
858 dbgs() << "MatchAddress: ";
863 return MatchAddressBase(N, AM);
865 CodeModel::Model M = TM.getCodeModel();
867 // If this is already a %rip relative address, we can only merge immediates
868 // into it. Instead of handling this in every case, we handle it here.
869 // RIP relative addressing: %rip + 32-bit displacement!
870 if (AM.isRIPRelative()) {
871 // FIXME: JumpTable and ExternalSymbol address currently don't like
872 // displacements. It isn't very important, but this should be fixed for
874 if (!AM.ES && AM.JT != -1) return true;
876 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
877 int64_t Val = AM.Disp + Cst->getSExtValue();
878 if (X86::isOffsetSuitableForCodeModel(Val, M,
879 AM.hasSymbolicDisplacement())) {
887 switch (N.getOpcode()) {
889 case ISD::Constant: {
890 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
892 X86::isOffsetSuitableForCodeModel(AM.Disp + Val, M,
893 AM.hasSymbolicDisplacement())) {
900 case X86ISD::SegmentBaseAddress:
901 if (!MatchSegmentBaseAddress(N, AM))
905 case X86ISD::Wrapper:
906 case X86ISD::WrapperRIP:
907 if (!MatchWrapper(N, AM))
912 if (!MatchLoad(N, AM))
916 case ISD::FrameIndex:
917 if (AM.BaseType == X86ISelAddressMode::RegBase
918 && AM.Base.Reg.getNode() == 0) {
919 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
920 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
926 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
930 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
931 unsigned Val = CN->getZExtValue();
932 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
933 // that the base operand remains free for further matching. If
934 // the base doesn't end up getting used, a post-processing step
935 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
936 if (Val == 1 || Val == 2 || Val == 3) {
938 SDValue ShVal = N.getNode()->getOperand(0);
940 // Okay, we know that we have a scale by now. However, if the scaled
941 // value is an add of something and a constant, we can fold the
942 // constant into the disp field here.
943 if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
944 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
945 AM.IndexReg = ShVal.getNode()->getOperand(0);
946 ConstantSDNode *AddVal =
947 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
948 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
950 X86::isOffsetSuitableForCodeModel(Disp, M,
951 AM.hasSymbolicDisplacement()))
965 // A mul_lohi where we need the low part can be folded as a plain multiply.
966 if (N.getResNo() != 0) break;
969 case X86ISD::MUL_IMM:
970 // X*[3,5,9] -> X+X*[2,4,8]
971 if (AM.BaseType == X86ISelAddressMode::RegBase &&
972 AM.Base.Reg.getNode() == 0 &&
973 AM.IndexReg.getNode() == 0) {
975 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
976 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
977 CN->getZExtValue() == 9) {
978 AM.Scale = unsigned(CN->getZExtValue())-1;
980 SDValue MulVal = N.getNode()->getOperand(0);
983 // Okay, we know that we have a scale by now. However, if the scaled
984 // value is an add of something and a constant, we can fold the
985 // constant into the disp field here.
986 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
987 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
988 Reg = MulVal.getNode()->getOperand(0);
989 ConstantSDNode *AddVal =
990 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
991 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
994 X86::isOffsetSuitableForCodeModel(Disp, M,
995 AM.hasSymbolicDisplacement()))
998 Reg = N.getNode()->getOperand(0);
1000 Reg = N.getNode()->getOperand(0);
1003 AM.IndexReg = AM.Base.Reg = Reg;
1010 // Given A-B, if A can be completely folded into the address and
1011 // the index field with the index field unused, use -B as the index.
1012 // This is a win if a has multiple parts that can be folded into
1013 // the address. Also, this saves a mov if the base register has
1014 // other uses, since it avoids a two-address sub instruction, however
1015 // it costs an additional mov if the index register has other uses.
1017 // Test if the LHS of the sub can be folded.
1018 X86ISelAddressMode Backup = AM;
1019 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1023 // Test if the index field is free for use.
1024 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1029 SDValue RHS = N.getNode()->getOperand(1);
1030 // If the RHS involves a register with multiple uses, this
1031 // transformation incurs an extra mov, due to the neg instruction
1032 // clobbering its operand.
1033 if (!RHS.getNode()->hasOneUse() ||
1034 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1035 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1036 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1037 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1038 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1040 // If the base is a register with multiple uses, this
1041 // transformation may save a mov.
1042 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1043 AM.Base.Reg.getNode() &&
1044 !AM.Base.Reg.getNode()->hasOneUse()) ||
1045 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1047 // If the folded LHS was interesting, this transformation saves
1048 // address arithmetic.
1049 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1050 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1051 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1053 // If it doesn't look like it may be an overall win, don't do it.
1059 // Ok, the transformation is legal and appears profitable. Go for it.
1060 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
1061 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1065 // Insert the new nodes into the topological ordering.
1066 if (Zero.getNode()->getNodeId() == -1 ||
1067 Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1068 CurDAG->RepositionNode(N.getNode(), Zero.getNode());
1069 Zero.getNode()->setNodeId(N.getNode()->getNodeId());
1071 if (Neg.getNode()->getNodeId() == -1 ||
1072 Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1073 CurDAG->RepositionNode(N.getNode(), Neg.getNode());
1074 Neg.getNode()->setNodeId(N.getNode()->getNodeId());
1080 X86ISelAddressMode Backup = AM;
1081 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1) &&
1082 !MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1))
1085 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1) &&
1086 !MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1))
1090 // If we couldn't fold both operands into the address at the same time,
1091 // see if we can just put each operand into a register and fold at least
1093 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1094 !AM.Base.Reg.getNode() &&
1095 !AM.IndexReg.getNode()) {
1096 AM.Base.Reg = N.getNode()->getOperand(0);
1097 AM.IndexReg = N.getNode()->getOperand(1);
1105 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1106 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1107 X86ISelAddressMode Backup = AM;
1108 uint64_t Offset = CN->getSExtValue();
1109 // Start with the LHS as an addr mode.
1110 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1111 // Address could not have picked a GV address for the displacement.
1113 // On x86-64, the resultant disp must fit in 32-bits.
1115 X86::isOffsetSuitableForCodeModel(AM.Disp + Offset, M,
1116 AM.hasSymbolicDisplacement())) &&
1117 // Check to see if the LHS & C is zero.
1118 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
1127 // Perform some heroic transforms on an and of a constant-count shift
1128 // with a constant to enable use of the scaled offset field.
1130 SDValue Shift = N.getOperand(0);
1131 if (Shift.getNumOperands() != 2) break;
1133 // Scale must not be used already.
1134 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1136 SDValue X = Shift.getOperand(0);
1137 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1138 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1139 if (!C1 || !C2) break;
1141 // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1142 // allows us to convert the shift and and into an h-register extract and
1144 if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1145 unsigned ScaleLog = 8 - C1->getZExtValue();
1146 if (ScaleLog > 0 && ScaleLog < 4 &&
1147 C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1148 SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1149 SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1150 SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1152 SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1154 SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1155 SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1158 // Insert the new nodes into the topological ordering.
1159 if (Eight.getNode()->getNodeId() == -1 ||
1160 Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1161 CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1162 Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1164 if (Mask.getNode()->getNodeId() == -1 ||
1165 Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1166 CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1167 Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1169 if (Srl.getNode()->getNodeId() == -1 ||
1170 Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1171 CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1172 Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1174 if (And.getNode()->getNodeId() == -1 ||
1175 And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1176 CurDAG->RepositionNode(N.getNode(), And.getNode());
1177 And.getNode()->setNodeId(N.getNode()->getNodeId());
1179 if (ShlCount.getNode()->getNodeId() == -1 ||
1180 ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1181 CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1182 ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1184 if (Shl.getNode()->getNodeId() == -1 ||
1185 Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1186 CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1187 Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1189 CurDAG->ReplaceAllUsesWith(N, Shl);
1191 AM.Scale = (1 << ScaleLog);
1196 // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1197 // allows us to fold the shift into this addressing mode.
1198 if (Shift.getOpcode() != ISD::SHL) break;
1200 // Not likely to be profitable if either the AND or SHIFT node has more
1201 // than one use (unless all uses are for address computation). Besides,
1202 // isel mechanism requires their node ids to be reused.
1203 if (!N.hasOneUse() || !Shift.hasOneUse())
1206 // Verify that the shift amount is something we can fold.
1207 unsigned ShiftCst = C1->getZExtValue();
1208 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1211 // Get the new AND mask, this folds to a constant.
1212 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1213 SDValue(C2, 0), SDValue(C1, 0));
1214 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1216 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1217 NewAND, SDValue(C1, 0));
1219 // Insert the new nodes into the topological ordering.
1220 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1221 CurDAG->RepositionNode(X.getNode(), C1);
1222 C1->setNodeId(X.getNode()->getNodeId());
1224 if (NewANDMask.getNode()->getNodeId() == -1 ||
1225 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1226 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1227 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1229 if (NewAND.getNode()->getNodeId() == -1 ||
1230 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1231 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1232 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1234 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1235 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1236 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1237 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1240 CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1242 AM.Scale = 1 << ShiftCst;
1243 AM.IndexReg = NewAND;
1248 return MatchAddressBase(N, AM);
1251 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1252 /// specified addressing mode without any further recursion.
1253 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1254 // Is the base register already occupied?
1255 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1256 // If so, check to see if the scale index register is set.
1257 if (AM.IndexReg.getNode() == 0) {
1263 // Otherwise, we cannot select it.
1267 // Default, generate it as a register.
1268 AM.BaseType = X86ISelAddressMode::RegBase;
1273 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1274 /// It returns the operands which make up the maximal addressing mode it can
1275 /// match by reference.
1276 bool X86DAGToDAGISel::SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
1277 SDValue &Scale, SDValue &Index,
1278 SDValue &Disp, SDValue &Segment) {
1279 X86ISelAddressMode AM;
1280 if (MatchAddress(N, AM))
1283 EVT VT = N.getValueType();
1284 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1285 if (!AM.Base.Reg.getNode())
1286 AM.Base.Reg = CurDAG->getRegister(0, VT);
1289 if (!AM.IndexReg.getNode())
1290 AM.IndexReg = CurDAG->getRegister(0, VT);
1292 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1296 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1297 /// match a load whose top elements are either undef or zeros. The load flavor
1298 /// is derived from the type of N, which is either v4f32 or v2f64.
1299 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Op, SDValue Pred,
1300 SDValue N, SDValue &Base,
1301 SDValue &Scale, SDValue &Index,
1302 SDValue &Disp, SDValue &Segment,
1304 SDValue &OutChain) {
1305 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1306 InChain = N.getOperand(0).getValue(1);
1307 if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1308 InChain.getValue(0).hasOneUse() &&
1310 IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op)) {
1311 LoadSDNode *LD = cast<LoadSDNode>(InChain);
1312 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1314 OutChain = LD->getChain();
1319 // Also handle the case where we explicitly require zeros in the top
1320 // elements. This is a vector shuffle from the zero vector.
1321 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1322 // Check to see if the top elements are all zeros (or bitcast of zeros).
1323 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1324 N.getOperand(0).getNode()->hasOneUse() &&
1325 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1326 N.getOperand(0).getOperand(0).hasOneUse()) {
1327 // Okay, this is a zero extending load. Fold it.
1328 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1329 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1331 OutChain = LD->getChain();
1332 InChain = SDValue(LD, 1);
1339 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1340 /// mode it matches can be cost effectively emitted as an LEA instruction.
1341 bool X86DAGToDAGISel::SelectLEAAddr(SDNode *Op, SDValue N,
1342 SDValue &Base, SDValue &Scale,
1343 SDValue &Index, SDValue &Disp) {
1344 X86ISelAddressMode AM;
1346 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1348 SDValue Copy = AM.Segment;
1349 SDValue T = CurDAG->getRegister(0, MVT::i32);
1351 if (MatchAddress(N, AM))
1353 assert (T == AM.Segment);
1356 EVT VT = N.getValueType();
1357 unsigned Complexity = 0;
1358 if (AM.BaseType == X86ISelAddressMode::RegBase)
1359 if (AM.Base.Reg.getNode())
1362 AM.Base.Reg = CurDAG->getRegister(0, VT);
1363 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1366 if (AM.IndexReg.getNode())
1369 AM.IndexReg = CurDAG->getRegister(0, VT);
1371 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1376 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1377 // to a LEA. This is determined with some expermentation but is by no means
1378 // optimal (especially for code size consideration). LEA is nice because of
1379 // its three-address nature. Tweak the cost function again when we can run
1380 // convertToThreeAddress() at register allocation time.
1381 if (AM.hasSymbolicDisplacement()) {
1382 // For X86-64, we should always use lea to materialize RIP relative
1384 if (Subtarget->is64Bit())
1390 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1393 // If it isn't worth using an LEA, reject it.
1394 if (Complexity <= 2)
1398 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1402 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1403 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
1404 SDValue &Scale, SDValue &Index,
1406 assert(Op->getOpcode() == X86ISD::TLSADDR);
1407 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1408 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1410 X86ISelAddressMode AM;
1411 AM.GV = GA->getGlobal();
1412 AM.Disp += GA->getOffset();
1413 AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1414 AM.SymbolFlags = GA->getTargetFlags();
1416 if (N.getValueType() == MVT::i32) {
1418 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1420 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1424 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1429 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1430 SDValue &Base, SDValue &Scale,
1431 SDValue &Index, SDValue &Disp,
1433 if (ISD::isNON_EXTLoad(N.getNode()) &&
1435 IsLegalAndProfitableToFold(N.getNode(), P, P))
1436 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1440 /// getGlobalBaseReg - Return an SDNode that returns the value of
1441 /// the global base register. Output instructions required to
1442 /// initialize the global base register, if necessary.
1444 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1445 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1446 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1449 static SDNode *FindCallStartFromCall(SDNode *Node) {
1450 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1451 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1452 "Node doesn't have a token chain argument!");
1453 return FindCallStartFromCall(Node->getOperand(0).getNode());
1456 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1457 SDValue Chain = Node->getOperand(0);
1458 SDValue In1 = Node->getOperand(1);
1459 SDValue In2L = Node->getOperand(2);
1460 SDValue In2H = Node->getOperand(3);
1461 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1462 if (!SelectAddr(In1.getNode(), In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1464 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1465 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1466 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, Chain};
1467 SDNode *ResNode = CurDAG->getMachineNode(Opc, Node->getDebugLoc(),
1468 MVT::i32, MVT::i32, MVT::Other, Ops,
1469 array_lengthof(Ops));
1470 cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp + 1);
1474 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, EVT NVT) {
1475 if (Node->hasAnyUseOfValue(0))
1478 // Optimize common patterns for __sync_add_and_fetch and
1479 // __sync_sub_and_fetch where the result is not used. This allows us
1480 // to use "lock" version of add, sub, inc, dec instructions.
1481 // FIXME: Do not use special instructions but instead add the "lock"
1482 // prefix to the target node somehow. The extra information will then be
1483 // transferred to machine instruction and it denotes the prefix.
1484 SDValue Chain = Node->getOperand(0);
1485 SDValue Ptr = Node->getOperand(1);
1486 SDValue Val = Node->getOperand(2);
1487 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1488 if (!SelectAddr(Ptr.getNode(), Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1491 bool isInc = false, isDec = false, isSub = false, isCN = false;
1492 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1495 int64_t CNVal = CN->getSExtValue();
1498 else if (CNVal == -1)
1500 else if (CNVal >= 0)
1501 Val = CurDAG->getTargetConstant(CNVal, NVT);
1504 Val = CurDAG->getTargetConstant(-CNVal, NVT);
1506 } else if (Val.hasOneUse() &&
1507 Val.getOpcode() == ISD::SUB &&
1508 X86::isZeroNode(Val.getOperand(0))) {
1510 Val = Val.getOperand(1);
1514 switch (NVT.getSimpleVT().SimpleTy) {
1518 Opc = X86::LOCK_INC8m;
1520 Opc = X86::LOCK_DEC8m;
1523 Opc = X86::LOCK_SUB8mi;
1525 Opc = X86::LOCK_SUB8mr;
1528 Opc = X86::LOCK_ADD8mi;
1530 Opc = X86::LOCK_ADD8mr;
1535 Opc = X86::LOCK_INC16m;
1537 Opc = X86::LOCK_DEC16m;
1540 if (Predicate_i16immSExt8(Val.getNode()))
1541 Opc = X86::LOCK_SUB16mi8;
1543 Opc = X86::LOCK_SUB16mi;
1545 Opc = X86::LOCK_SUB16mr;
1548 if (Predicate_i16immSExt8(Val.getNode()))
1549 Opc = X86::LOCK_ADD16mi8;
1551 Opc = X86::LOCK_ADD16mi;
1553 Opc = X86::LOCK_ADD16mr;
1558 Opc = X86::LOCK_INC32m;
1560 Opc = X86::LOCK_DEC32m;
1563 if (Predicate_i32immSExt8(Val.getNode()))
1564 Opc = X86::LOCK_SUB32mi8;
1566 Opc = X86::LOCK_SUB32mi;
1568 Opc = X86::LOCK_SUB32mr;
1571 if (Predicate_i32immSExt8(Val.getNode()))
1572 Opc = X86::LOCK_ADD32mi8;
1574 Opc = X86::LOCK_ADD32mi;
1576 Opc = X86::LOCK_ADD32mr;
1581 Opc = X86::LOCK_INC64m;
1583 Opc = X86::LOCK_DEC64m;
1585 Opc = X86::LOCK_SUB64mr;
1587 if (Predicate_i64immSExt8(Val.getNode()))
1588 Opc = X86::LOCK_SUB64mi8;
1589 else if (Predicate_i64immSExt32(Val.getNode()))
1590 Opc = X86::LOCK_SUB64mi32;
1593 Opc = X86::LOCK_ADD64mr;
1595 if (Predicate_i64immSExt8(Val.getNode()))
1596 Opc = X86::LOCK_ADD64mi8;
1597 else if (Predicate_i64immSExt32(Val.getNode()))
1598 Opc = X86::LOCK_ADD64mi32;
1604 DebugLoc dl = Node->getDebugLoc();
1605 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetInstrInfo::IMPLICIT_DEF,
1607 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1608 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1609 if (isInc || isDec) {
1610 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain };
1611 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 6), 0);
1612 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1613 SDValue RetVals[] = { Undef, Ret };
1614 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1616 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, Chain };
1617 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 7), 0);
1618 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1619 SDValue RetVals[] = { Undef, Ret };
1620 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1624 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1625 /// any uses which require the SF or OF bits to be accurate.
1626 static bool HasNoSignedComparisonUses(SDNode *N) {
1627 // Examine each user of the node.
1628 for (SDNode::use_iterator UI = N->use_begin(),
1629 UE = N->use_end(); UI != UE; ++UI) {
1630 // Only examine CopyToReg uses.
1631 if (UI->getOpcode() != ISD::CopyToReg)
1633 // Only examine CopyToReg uses that copy to EFLAGS.
1634 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1637 // Examine each user of the CopyToReg use.
1638 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1639 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1640 // Only examine the Flag result.
1641 if (FlagUI.getUse().getResNo() != 1) continue;
1642 // Anything unusual: assume conservatively.
1643 if (!FlagUI->isMachineOpcode()) return false;
1644 // Examine the opcode of the user.
1645 switch (FlagUI->getMachineOpcode()) {
1646 // These comparisons don't treat the most significant bit specially.
1647 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1648 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1649 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1650 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1651 case X86::JA: case X86::JAE: case X86::JB: case X86::JBE:
1652 case X86::JE: case X86::JNE: case X86::JP: case X86::JNP:
1653 case X86::CMOVA16rr: case X86::CMOVA16rm:
1654 case X86::CMOVA32rr: case X86::CMOVA32rm:
1655 case X86::CMOVA64rr: case X86::CMOVA64rm:
1656 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1657 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1658 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1659 case X86::CMOVB16rr: case X86::CMOVB16rm:
1660 case X86::CMOVB32rr: case X86::CMOVB32rm:
1661 case X86::CMOVB64rr: case X86::CMOVB64rm:
1662 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1663 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1664 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1665 case X86::CMOVE16rr: case X86::CMOVE16rm:
1666 case X86::CMOVE32rr: case X86::CMOVE32rm:
1667 case X86::CMOVE64rr: case X86::CMOVE64rm:
1668 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1669 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1670 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1671 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1672 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1673 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1674 case X86::CMOVP16rr: case X86::CMOVP16rm:
1675 case X86::CMOVP32rr: case X86::CMOVP32rm:
1676 case X86::CMOVP64rr: case X86::CMOVP64rm:
1678 // Anything else: assume conservatively.
1679 default: return false;
1686 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
1687 EVT NVT = Node->getValueType(0);
1689 unsigned Opcode = Node->getOpcode();
1690 DebugLoc dl = Node->getDebugLoc();
1694 dbgs() << std::string(Indent, ' ') << "Selecting: ";
1701 if (Node->isMachineOpcode()) {
1704 dbgs() << std::string(Indent-2, ' ') << "== ";
1710 return NULL; // Already selected.
1715 case X86ISD::GlobalBaseReg:
1716 return getGlobalBaseReg();
1718 case X86ISD::ATOMOR64_DAG:
1719 return SelectAtomic64(Node, X86::ATOMOR6432);
1720 case X86ISD::ATOMXOR64_DAG:
1721 return SelectAtomic64(Node, X86::ATOMXOR6432);
1722 case X86ISD::ATOMADD64_DAG:
1723 return SelectAtomic64(Node, X86::ATOMADD6432);
1724 case X86ISD::ATOMSUB64_DAG:
1725 return SelectAtomic64(Node, X86::ATOMSUB6432);
1726 case X86ISD::ATOMNAND64_DAG:
1727 return SelectAtomic64(Node, X86::ATOMNAND6432);
1728 case X86ISD::ATOMAND64_DAG:
1729 return SelectAtomic64(Node, X86::ATOMAND6432);
1730 case X86ISD::ATOMSWAP64_DAG:
1731 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1733 case ISD::ATOMIC_LOAD_ADD: {
1734 SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1740 case ISD::SMUL_LOHI:
1741 case ISD::UMUL_LOHI: {
1742 SDValue N0 = Node->getOperand(0);
1743 SDValue N1 = Node->getOperand(1);
1745 bool isSigned = Opcode == ISD::SMUL_LOHI;
1747 switch (NVT.getSimpleVT().SimpleTy) {
1748 default: llvm_unreachable("Unsupported VT!");
1749 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1750 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1751 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1752 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1755 switch (NVT.getSimpleVT().SimpleTy) {
1756 default: llvm_unreachable("Unsupported VT!");
1757 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1758 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1759 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1760 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1764 unsigned LoReg, HiReg;
1765 switch (NVT.getSimpleVT().SimpleTy) {
1766 default: llvm_unreachable("Unsupported VT!");
1767 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1768 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1769 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1770 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1773 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1774 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1775 // Multiply is commmutative.
1777 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1782 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1783 N0, SDValue()).getValue(1);
1786 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1789 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1790 array_lengthof(Ops));
1791 InFlag = SDValue(CNode, 1);
1792 // Update the chain.
1793 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1796 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1799 // Copy the low half of the result, if it is needed.
1800 if (!SDValue(Node, 0).use_empty()) {
1801 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1802 LoReg, NVT, InFlag);
1803 InFlag = Result.getValue(2);
1804 ReplaceUses(SDValue(Node, 0), Result);
1807 dbgs() << std::string(Indent-2, ' ') << "=> ";
1808 Result.getNode()->dump(CurDAG);
1813 // Copy the high half of the result, if it is needed.
1814 if (!SDValue(Node, 1).use_empty()) {
1816 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1817 // Prevent use of AH in a REX instruction by referencing AX instead.
1818 // Shift it down 8 bits.
1819 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1820 X86::AX, MVT::i16, InFlag);
1821 InFlag = Result.getValue(2);
1822 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1824 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1825 // Then truncate it down to i8.
1826 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1829 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1830 HiReg, NVT, InFlag);
1831 InFlag = Result.getValue(2);
1833 ReplaceUses(SDValue(Node, 1), Result);
1836 dbgs() << std::string(Indent-2, ' ') << "=> ";
1837 Result.getNode()->dump(CurDAG);
1851 case ISD::UDIVREM: {
1852 SDValue N0 = Node->getOperand(0);
1853 SDValue N1 = Node->getOperand(1);
1855 bool isSigned = Opcode == ISD::SDIVREM;
1857 switch (NVT.getSimpleVT().SimpleTy) {
1858 default: llvm_unreachable("Unsupported VT!");
1859 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1860 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1861 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1862 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1865 switch (NVT.getSimpleVT().SimpleTy) {
1866 default: llvm_unreachable("Unsupported VT!");
1867 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1868 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1869 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1870 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1874 unsigned LoReg, HiReg, ClrReg;
1875 unsigned ClrOpcode, SExtOpcode;
1877 switch (NVT.getSimpleVT().SimpleTy) {
1878 default: llvm_unreachable("Unsupported VT!");
1880 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
1882 SExtOpcode = X86::CBW;
1885 LoReg = X86::AX; HiReg = X86::DX;
1886 ClrOpcode = X86::MOV32r0; ClrReg = X86::EDX; ClrVT = MVT::i32;
1887 SExtOpcode = X86::CWD;
1890 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
1891 ClrOpcode = X86::MOV32r0;
1892 SExtOpcode = X86::CDQ;
1895 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
1896 ClrOpcode = ~0U; // NOT USED.
1897 SExtOpcode = X86::CQO;
1901 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1902 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1903 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1906 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1907 // Special case for div8, just use a move with zero extension to AX to
1908 // clear the upper 8 bits (AH).
1909 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1910 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1911 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1913 SDValue(CurDAG->getMachineNode(X86::MOVZX16rm8, dl, MVT::i16,
1915 array_lengthof(Ops)), 0);
1916 Chain = Move.getValue(1);
1917 ReplaceUses(N0.getValue(1), Chain);
1920 SDValue(CurDAG->getMachineNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1921 Chain = CurDAG->getEntryNode();
1923 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1924 InFlag = Chain.getValue(1);
1927 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1928 LoReg, N0, SDValue()).getValue(1);
1929 if (isSigned && !signBitIsZero) {
1930 // Sign extend the low part into the high part.
1932 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1934 // Zero out the high part, effectively zero extending the input.
1937 if (NVT.getSimpleVT() == MVT::i64) {
1938 ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, MVT::i32),
1940 // We just did a 32-bit clear, insert it into a 64-bit register to
1941 // clear the whole 64-bit reg.
1942 SDValue Zero = CurDAG->getTargetConstant(0, MVT::i64);
1944 CurDAG->getTargetConstant(X86::SUBREG_32BIT, MVT::i32);
1946 SDValue(CurDAG->getMachineNode(TargetInstrInfo::SUBREG_TO_REG, dl,
1947 MVT::i64, Zero, ClrNode, SubRegNo),
1950 ClrNode = SDValue(CurDAG->getMachineNode(ClrOpcode, dl, ClrVT), 0);
1953 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
1954 ClrNode, InFlag).getValue(1);
1959 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1962 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1963 array_lengthof(Ops));
1964 InFlag = SDValue(CNode, 1);
1965 // Update the chain.
1966 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1969 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1972 // Copy the division (low) result, if it is needed.
1973 if (!SDValue(Node, 0).use_empty()) {
1974 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1975 LoReg, NVT, InFlag);
1976 InFlag = Result.getValue(2);
1977 ReplaceUses(SDValue(Node, 0), Result);
1980 dbgs() << std::string(Indent-2, ' ') << "=> ";
1981 Result.getNode()->dump(CurDAG);
1986 // Copy the remainder (high) result, if it is needed.
1987 if (!SDValue(Node, 1).use_empty()) {
1989 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1990 // Prevent use of AH in a REX instruction by referencing AX instead.
1991 // Shift it down 8 bits.
1992 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1993 X86::AX, MVT::i16, InFlag);
1994 InFlag = Result.getValue(2);
1995 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1997 CurDAG->getTargetConstant(8, MVT::i8)),
1999 // Then truncate it down to i8.
2000 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
2003 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2004 HiReg, NVT, InFlag);
2005 InFlag = Result.getValue(2);
2007 ReplaceUses(SDValue(Node, 1), Result);
2010 dbgs() << std::string(Indent-2, ' ') << "=> ";
2011 Result.getNode()->dump(CurDAG);
2025 SDValue N0 = Node->getOperand(0);
2026 SDValue N1 = Node->getOperand(1);
2028 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2029 // use a smaller encoding.
2030 if (N0.getNode()->getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2031 N0.getValueType() != MVT::i8 &&
2032 X86::isZeroNode(N1)) {
2033 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2036 // For example, convert "testl %eax, $8" to "testb %al, $8"
2037 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2038 (!(C->getZExtValue() & 0x80) ||
2039 HasNoSignedComparisonUses(Node))) {
2040 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
2041 SDValue Reg = N0.getNode()->getOperand(0);
2043 // On x86-32, only the ABCD registers have 8-bit subregisters.
2044 if (!Subtarget->is64Bit()) {
2045 TargetRegisterClass *TRC = 0;
2046 switch (N0.getValueType().getSimpleVT().SimpleTy) {
2047 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2048 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2049 default: llvm_unreachable("Unsupported TEST operand type!");
2051 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
2052 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2053 Reg.getValueType(), Reg, RC), 0);
2056 // Extract the l-register.
2057 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
2061 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32, Subreg, Imm);
2064 // For example, "testl %eax, $2048" to "testb %ah, $8".
2065 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2066 (!(C->getZExtValue() & 0x8000) ||
2067 HasNoSignedComparisonUses(Node))) {
2068 // Shift the immediate right by 8 bits.
2069 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2071 SDValue Reg = N0.getNode()->getOperand(0);
2073 // Put the value in an ABCD register.
2074 TargetRegisterClass *TRC = 0;
2075 switch (N0.getValueType().getSimpleVT().SimpleTy) {
2076 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2077 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2078 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2079 default: llvm_unreachable("Unsupported TEST operand type!");
2081 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
2082 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2083 Reg.getValueType(), Reg, RC), 0);
2085 // Extract the h-register.
2086 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT_HI, dl,
2089 // Emit a testb. No special NOREX tricks are needed since there's
2090 // only one GPR operand!
2091 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2092 Subreg, ShiftedImm);
2095 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2096 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2097 N0.getValueType() != MVT::i16 &&
2098 (!(C->getZExtValue() & 0x8000) ||
2099 HasNoSignedComparisonUses(Node))) {
2100 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
2101 SDValue Reg = N0.getNode()->getOperand(0);
2103 // Extract the 16-bit subregister.
2104 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_16BIT, dl,
2108 return CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32, Subreg, Imm);
2111 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2112 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2113 N0.getValueType() == MVT::i64 &&
2114 (!(C->getZExtValue() & 0x80000000) ||
2115 HasNoSignedComparisonUses(Node))) {
2116 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
2117 SDValue Reg = N0.getNode()->getOperand(0);
2119 // Extract the 32-bit subregister.
2120 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_32BIT, dl,
2124 return CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32, Subreg, Imm);
2131 SDNode *ResNode = SelectCode(Node);
2135 dbgs() << std::string(Indent-2, ' ') << "=> ";
2136 if (ResNode == NULL || ResNode == Node)
2139 ResNode->dump(CurDAG);
2148 bool X86DAGToDAGISel::
2149 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
2150 std::vector<SDValue> &OutOps) {
2151 SDValue Op0, Op1, Op2, Op3, Op4;
2152 switch (ConstraintCode) {
2153 case 'o': // offsetable ??
2154 case 'v': // not offsetable ??
2155 default: return true;
2157 if (!SelectAddr(Op.getNode(), Op, Op0, Op1, Op2, Op3, Op4))
2162 OutOps.push_back(Op0);
2163 OutOps.push_back(Op1);
2164 OutOps.push_back(Op2);
2165 OutOps.push_back(Op3);
2166 OutOps.push_back(Op4);
2170 /// createX86ISelDag - This pass converts a legalized DAG into a
2171 /// X86-specific DAG, ready for instruction scheduling.
2173 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2174 llvm::CodeGenOpt::Level OptLevel) {
2175 return new X86DAGToDAGISel(TM, OptLevel);