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/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
43 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45 //===----------------------------------------------------------------------===//
46 // Pattern Matcher Implementation
47 //===----------------------------------------------------------------------===//
50 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
51 /// SDValue's instead of register numbers for the leaves of the matched
53 struct X86ISelAddressMode {
59 struct { // This is really a union, discriminated by BaseType!
68 const GlobalValue *GV;
70 const BlockAddress *BlockAddr;
73 unsigned Align; // CP alignment.
74 unsigned char SymbolFlags; // X86II::MO_*
77 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
78 Segment(), GV(0), CP(0), BlockAddr(0), ES(0), JT(-1), Align(0),
79 SymbolFlags(X86II::MO_NO_FLAG) {
82 bool hasSymbolicDisplacement() const {
83 return GV != 0 || CP != 0 || ES != 0 || JT != -1 || BlockAddr != 0;
86 bool hasBaseOrIndexReg() const {
87 return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
90 /// isRIPRelative - Return true if this addressing mode is already RIP
92 bool isRIPRelative() const {
93 if (BaseType != RegBase) return false;
94 if (RegisterSDNode *RegNode =
95 dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
96 return RegNode->getReg() == X86::RIP;
100 void setBaseReg(SDValue Reg) {
106 dbgs() << "X86ISelAddressMode " << this << '\n';
107 dbgs() << "Base.Reg ";
108 if (Base.Reg.getNode() != 0)
109 Base.Reg.getNode()->dump();
112 dbgs() << " Base.FrameIndex " << Base.FrameIndex << '\n'
113 << " Scale" << Scale << '\n'
115 if (IndexReg.getNode() != 0)
116 IndexReg.getNode()->dump();
119 dbgs() << " Disp " << Disp << '\n'
136 dbgs() << " JT" << JT << " Align" << Align << '\n';
142 class X86ISelListener : public SelectionDAG::DAGUpdateListener {
143 SmallSet<SDNode*, 4> Deletes;
145 explicit X86ISelListener() {}
146 virtual void NodeDeleted(SDNode *N, SDNode *E) {
149 virtual void NodeUpdated(SDNode *N) {
152 bool IsDeleted(SDNode *N) {
153 return Deletes.count(N);
157 //===--------------------------------------------------------------------===//
158 /// ISel - X86 specific code to select X86 machine instructions for
159 /// SelectionDAG operations.
161 class X86DAGToDAGISel : public SelectionDAGISel {
162 /// X86Lowering - This object fully describes how to lower LLVM code to an
163 /// X86-specific SelectionDAG.
164 X86TargetLowering &X86Lowering;
166 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
167 /// make the right decision when generating code for different targets.
168 const X86Subtarget *Subtarget;
170 /// OptForSize - If true, selector should try to optimize for code size
171 /// instead of performance.
175 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
176 : SelectionDAGISel(tm, OptLevel),
177 X86Lowering(*tm.getTargetLowering()),
178 Subtarget(&tm.getSubtarget<X86Subtarget>()),
181 virtual const char *getPassName() const {
182 return "X86 DAG->DAG Instruction Selection";
185 virtual void EmitFunctionEntryCode();
187 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
189 virtual void PreprocessISelDAG();
191 // Include the pieces autogenerated from the target description.
192 #include "X86GenDAGISel.inc"
195 SDNode *Select(SDNode *N);
196 SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
197 SDNode *SelectAtomicLoadAdd(SDNode *Node, EVT NVT);
199 bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
200 bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
201 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
202 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
203 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
204 X86ISelListener &DeadNodes,
206 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
207 bool SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
208 SDValue &Scale, SDValue &Index, SDValue &Disp,
210 bool SelectLEAAddr(SDNode *Op, SDValue N, SDValue &Base,
211 SDValue &Scale, SDValue &Index, SDValue &Disp);
212 bool SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
213 SDValue &Scale, SDValue &Index, SDValue &Disp);
214 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
215 SDValue &Base, SDValue &Scale,
216 SDValue &Index, SDValue &Disp,
218 SDValue &NodeWithChain);
220 bool TryFoldLoad(SDNode *P, SDValue N,
221 SDValue &Base, SDValue &Scale,
222 SDValue &Index, SDValue &Disp,
225 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
226 /// inline asm expressions.
227 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
229 std::vector<SDValue> &OutOps);
231 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
233 inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base,
234 SDValue &Scale, SDValue &Index,
235 SDValue &Disp, SDValue &Segment) {
236 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
237 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
239 Scale = getI8Imm(AM.Scale);
241 // These are 32-bit even in 64-bit mode since RIP relative offset
244 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
247 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
248 AM.Align, AM.Disp, AM.SymbolFlags);
250 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
251 else if (AM.JT != -1)
252 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
253 else if (AM.BlockAddr)
254 Disp = CurDAG->getBlockAddress(AM.BlockAddr, MVT::i32,
255 true, AM.SymbolFlags);
257 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
259 if (AM.Segment.getNode())
260 Segment = AM.Segment;
262 Segment = CurDAG->getRegister(0, MVT::i32);
265 /// getI8Imm - Return a target constant with the specified value, of type
267 inline SDValue getI8Imm(unsigned Imm) {
268 return CurDAG->getTargetConstant(Imm, MVT::i8);
271 /// getI16Imm - Return a target constant with the specified value, of type
273 inline SDValue getI16Imm(unsigned Imm) {
274 return CurDAG->getTargetConstant(Imm, MVT::i16);
277 /// getI32Imm - Return a target constant with the specified value, of type
279 inline SDValue getI32Imm(unsigned Imm) {
280 return CurDAG->getTargetConstant(Imm, MVT::i32);
283 /// getGlobalBaseReg - Return an SDNode that returns the value of
284 /// the global base register. Output instructions required to
285 /// initialize the global base register, if necessary.
287 SDNode *getGlobalBaseReg();
289 /// getTargetMachine - Return a reference to the TargetMachine, casted
290 /// to the target-specific type.
291 const X86TargetMachine &getTargetMachine() {
292 return static_cast<const X86TargetMachine &>(TM);
295 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
296 /// to the target-specific type.
297 const X86InstrInfo *getInstrInfo() {
298 return getTargetMachine().getInstrInfo();
305 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
306 if (OptLevel == CodeGenOpt::None) return false;
311 if (N.getOpcode() != ISD::LOAD)
314 // If N is a load, do additional profitability checks.
316 switch (U->getOpcode()) {
329 SDValue Op1 = U->getOperand(1);
331 // If the other operand is a 8-bit immediate we should fold the immediate
332 // instead. This reduces code size.
334 // movl 4(%esp), %eax
338 // addl 4(%esp), %eax
339 // The former is 2 bytes shorter. In case where the increment is 1, then
340 // the saving can be 4 bytes (by using incl %eax).
341 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
342 if (Imm->getAPIntValue().isSignedIntN(8))
345 // If the other operand is a TLS address, we should fold it instead.
348 // leal i@NTPOFF(%eax), %eax
350 // movl $i@NTPOFF, %eax
352 // if the block also has an access to a second TLS address this will save
354 // FIXME: This is probably also true for non TLS addresses.
355 if (Op1.getOpcode() == X86ISD::Wrapper) {
356 SDValue Val = Op1.getOperand(0);
357 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
367 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
368 /// load's chain operand and move load below the call's chain operand.
369 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
370 SDValue Call, SDValue OrigChain) {
371 SmallVector<SDValue, 8> Ops;
372 SDValue Chain = OrigChain.getOperand(0);
373 if (Chain.getNode() == Load.getNode())
374 Ops.push_back(Load.getOperand(0));
376 assert(Chain.getOpcode() == ISD::TokenFactor &&
377 "Unexpected chain operand");
378 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
379 if (Chain.getOperand(i).getNode() == Load.getNode())
380 Ops.push_back(Load.getOperand(0));
382 Ops.push_back(Chain.getOperand(i));
384 CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
385 MVT::Other, &Ops[0], Ops.size());
387 Ops.push_back(NewChain);
389 for (unsigned i = 1, e = OrigChain.getNumOperands(); i != e; ++i)
390 Ops.push_back(OrigChain.getOperand(i));
391 CurDAG->UpdateNodeOperands(OrigChain, &Ops[0], Ops.size());
392 CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
393 Load.getOperand(1), Load.getOperand(2));
395 Ops.push_back(SDValue(Load.getNode(), 1));
396 for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
397 Ops.push_back(Call.getOperand(i));
398 CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
401 /// isCalleeLoad - Return true if call address is a load and it can be
402 /// moved below CALLSEQ_START and the chains leading up to the call.
403 /// Return the CALLSEQ_START by reference as a second output.
404 /// In the case of a tail call, there isn't a callseq node between the call
405 /// chain and the load.
406 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
407 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
409 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
412 LD->getAddressingMode() != ISD::UNINDEXED ||
413 LD->getExtensionType() != ISD::NON_EXTLOAD)
416 // Now let's find the callseq_start.
417 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
418 if (!Chain.hasOneUse())
420 Chain = Chain.getOperand(0);
423 if (!Chain.getNumOperands())
425 if (Chain.getOperand(0).getNode() == Callee.getNode())
427 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
428 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
429 Callee.getValue(1).hasOneUse())
434 void X86DAGToDAGISel::PreprocessISelDAG() {
435 // OptForSize is used in pattern predicates that isel is matching.
436 OptForSize = MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize);
438 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
439 E = CurDAG->allnodes_end(); I != E; ) {
440 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
442 if (OptLevel != CodeGenOpt::None &&
443 (N->getOpcode() == X86ISD::CALL ||
444 N->getOpcode() == X86ISD::TC_RETURN)) {
445 /// Also try moving call address load from outside callseq_start to just
446 /// before the call to allow it to be folded.
464 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
465 SDValue Chain = N->getOperand(0);
466 SDValue Load = N->getOperand(1);
467 if (!isCalleeLoad(Load, Chain, HasCallSeq))
469 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
474 // Lower fpround and fpextend nodes that target the FP stack to be store and
475 // load to the stack. This is a gross hack. We would like to simply mark
476 // these as being illegal, but when we do that, legalize produces these when
477 // it expands calls, then expands these in the same legalize pass. We would
478 // like dag combine to be able to hack on these between the call expansion
479 // and the node legalization. As such this pass basically does "really
480 // late" legalization of these inline with the X86 isel pass.
481 // FIXME: This should only happen when not compiled with -O0.
482 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
485 // If the source and destination are SSE registers, then this is a legal
486 // conversion that should not be lowered.
487 EVT SrcVT = N->getOperand(0).getValueType();
488 EVT DstVT = N->getValueType(0);
489 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
490 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
491 if (SrcIsSSE && DstIsSSE)
494 if (!SrcIsSSE && !DstIsSSE) {
495 // If this is an FPStack extension, it is a noop.
496 if (N->getOpcode() == ISD::FP_EXTEND)
498 // If this is a value-preserving FPStack truncation, it is a noop.
499 if (N->getConstantOperandVal(1))
503 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
504 // FPStack has extload and truncstore. SSE can fold direct loads into other
505 // operations. Based on this, decide what we want to do.
507 if (N->getOpcode() == ISD::FP_ROUND)
508 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
510 MemVT = SrcIsSSE ? SrcVT : DstVT;
512 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
513 DebugLoc dl = N->getDebugLoc();
515 // FIXME: optimize the case where the src/dest is a load or store?
516 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
518 MemTmp, NULL, 0, MemVT,
520 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
521 NULL, 0, MemVT, false, false, 0);
523 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
524 // extload we created. This will cause general havok on the dag because
525 // anything below the conversion could be folded into other existing nodes.
526 // To avoid invalidating 'I', back it up to the convert node.
528 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
530 // Now that we did that, the node is dead. Increment the iterator to the
531 // next node to process, then delete N.
533 CurDAG->DeleteNode(N);
538 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
539 /// the main function.
540 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
541 MachineFrameInfo *MFI) {
542 const TargetInstrInfo *TII = TM.getInstrInfo();
543 if (Subtarget->isTargetCygMing())
544 BuildMI(BB, DebugLoc(),
545 TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
548 void X86DAGToDAGISel::EmitFunctionEntryCode() {
549 // If this is main, emit special code for main.
550 if (const Function *Fn = MF->getFunction())
551 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
552 EmitSpecialCodeForMain(MF->begin(), MF->getFrameInfo());
556 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
557 X86ISelAddressMode &AM) {
558 assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
559 SDValue Segment = N.getOperand(0);
561 if (AM.Segment.getNode() == 0) {
562 AM.Segment = Segment;
569 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
570 // This optimization is valid because the GNU TLS model defines that
571 // gs:0 (or fs:0 on X86-64) contains its own address.
572 // For more information see http://people.redhat.com/drepper/tls.pdf
574 SDValue Address = N.getOperand(1);
575 if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
576 !MatchSegmentBaseAddress (Address, AM))
582 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
583 /// into an addressing mode. These wrap things that will resolve down into a
584 /// symbol reference. If no match is possible, this returns true, otherwise it
586 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
587 // If the addressing mode already has a symbol as the displacement, we can
588 // never match another symbol.
589 if (AM.hasSymbolicDisplacement())
592 SDValue N0 = N.getOperand(0);
593 CodeModel::Model M = TM.getCodeModel();
595 // Handle X86-64 rip-relative addresses. We check this before checking direct
596 // folding because RIP is preferable to non-RIP accesses.
597 if (Subtarget->is64Bit() &&
598 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
599 // they cannot be folded into immediate fields.
600 // FIXME: This can be improved for kernel and other models?
601 (M == CodeModel::Small || M == CodeModel::Kernel) &&
602 // Base and index reg must be 0 in order to use %rip as base and lowering
604 !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
605 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
606 int64_t Offset = AM.Disp + G->getOffset();
607 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
608 AM.GV = G->getGlobal();
610 AM.SymbolFlags = G->getTargetFlags();
611 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
612 int64_t Offset = AM.Disp + CP->getOffset();
613 if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
614 AM.CP = CP->getConstVal();
615 AM.Align = CP->getAlignment();
617 AM.SymbolFlags = CP->getTargetFlags();
618 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
619 AM.ES = S->getSymbol();
620 AM.SymbolFlags = S->getTargetFlags();
621 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
622 AM.JT = J->getIndex();
623 AM.SymbolFlags = J->getTargetFlags();
625 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
626 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
629 if (N.getOpcode() == X86ISD::WrapperRIP)
630 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
634 // Handle the case when globals fit in our immediate field: This is true for
635 // X86-32 always and X86-64 when in -static -mcmodel=small mode. In 64-bit
636 // mode, this results in a non-RIP-relative computation.
637 if (!Subtarget->is64Bit() ||
638 ((M == CodeModel::Small || M == CodeModel::Kernel) &&
639 TM.getRelocationModel() == Reloc::Static)) {
640 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
641 AM.GV = G->getGlobal();
642 AM.Disp += G->getOffset();
643 AM.SymbolFlags = G->getTargetFlags();
644 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
645 AM.CP = CP->getConstVal();
646 AM.Align = CP->getAlignment();
647 AM.Disp += CP->getOffset();
648 AM.SymbolFlags = CP->getTargetFlags();
649 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
650 AM.ES = S->getSymbol();
651 AM.SymbolFlags = S->getTargetFlags();
652 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
653 AM.JT = J->getIndex();
654 AM.SymbolFlags = J->getTargetFlags();
656 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
657 AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
665 /// MatchAddress - Add the specified node to the specified addressing mode,
666 /// returning true if it cannot be done. This just pattern matches for the
668 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
669 X86ISelListener DeadNodes;
670 if (MatchAddressRecursively(N, AM, DeadNodes, 0))
673 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
674 // a smaller encoding and avoids a scaled-index.
676 AM.BaseType == X86ISelAddressMode::RegBase &&
677 AM.Base.Reg.getNode() == 0) {
678 AM.Base.Reg = AM.IndexReg;
682 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
683 // because it has a smaller encoding.
684 // TODO: Which other code models can use this?
685 if (TM.getCodeModel() == CodeModel::Small &&
686 Subtarget->is64Bit() &&
688 AM.BaseType == X86ISelAddressMode::RegBase &&
689 AM.Base.Reg.getNode() == 0 &&
690 AM.IndexReg.getNode() == 0 &&
691 AM.SymbolFlags == X86II::MO_NO_FLAG &&
692 AM.hasSymbolicDisplacement())
693 AM.Base.Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
698 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
699 X86ISelListener &DeadNodes,
701 bool is64Bit = Subtarget->is64Bit();
702 DebugLoc dl = N.getDebugLoc();
704 dbgs() << "MatchAddress: ";
709 return MatchAddressBase(N, AM);
711 CodeModel::Model M = TM.getCodeModel();
713 // If this is already a %rip relative address, we can only merge immediates
714 // into it. Instead of handling this in every case, we handle it here.
715 // RIP relative addressing: %rip + 32-bit displacement!
716 if (AM.isRIPRelative()) {
717 // FIXME: JumpTable and ExternalSymbol address currently don't like
718 // displacements. It isn't very important, but this should be fixed for
720 if (!AM.ES && AM.JT != -1) return true;
722 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
723 int64_t Val = AM.Disp + Cst->getSExtValue();
724 if (X86::isOffsetSuitableForCodeModel(Val, M,
725 AM.hasSymbolicDisplacement())) {
733 switch (N.getOpcode()) {
735 case ISD::Constant: {
736 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
738 X86::isOffsetSuitableForCodeModel(AM.Disp + Val, M,
739 AM.hasSymbolicDisplacement())) {
746 case X86ISD::SegmentBaseAddress:
747 if (!MatchSegmentBaseAddress(N, AM))
751 case X86ISD::Wrapper:
752 case X86ISD::WrapperRIP:
753 if (!MatchWrapper(N, AM))
758 if (!MatchLoad(N, AM))
762 case ISD::FrameIndex:
763 if (AM.BaseType == X86ISelAddressMode::RegBase
764 && AM.Base.Reg.getNode() == 0) {
765 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
766 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
772 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
776 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
777 unsigned Val = CN->getZExtValue();
778 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
779 // that the base operand remains free for further matching. If
780 // the base doesn't end up getting used, a post-processing step
781 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
782 if (Val == 1 || Val == 2 || Val == 3) {
784 SDValue ShVal = N.getNode()->getOperand(0);
786 // Okay, we know that we have a scale by now. However, if the scaled
787 // value is an add of something and a constant, we can fold the
788 // constant into the disp field here.
789 if (ShVal.getNode()->getOpcode() == ISD::ADD &&
790 isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
791 AM.IndexReg = ShVal.getNode()->getOperand(0);
792 ConstantSDNode *AddVal =
793 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
794 uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
796 X86::isOffsetSuitableForCodeModel(Disp, M,
797 AM.hasSymbolicDisplacement()))
811 // A mul_lohi where we need the low part can be folded as a plain multiply.
812 if (N.getResNo() != 0) break;
815 case X86ISD::MUL_IMM:
816 // X*[3,5,9] -> X+X*[2,4,8]
817 if (AM.BaseType == X86ISelAddressMode::RegBase &&
818 AM.Base.Reg.getNode() == 0 &&
819 AM.IndexReg.getNode() == 0) {
821 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
822 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
823 CN->getZExtValue() == 9) {
824 AM.Scale = unsigned(CN->getZExtValue())-1;
826 SDValue MulVal = N.getNode()->getOperand(0);
829 // Okay, we know that we have a scale by now. However, if the scaled
830 // value is an add of something and a constant, we can fold the
831 // constant into the disp field here.
832 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
833 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
834 Reg = MulVal.getNode()->getOperand(0);
835 ConstantSDNode *AddVal =
836 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
837 uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
840 X86::isOffsetSuitableForCodeModel(Disp, M,
841 AM.hasSymbolicDisplacement()))
844 Reg = N.getNode()->getOperand(0);
846 Reg = N.getNode()->getOperand(0);
849 AM.IndexReg = AM.Base.Reg = Reg;
856 // Given A-B, if A can be completely folded into the address and
857 // the index field with the index field unused, use -B as the index.
858 // This is a win if a has multiple parts that can be folded into
859 // the address. Also, this saves a mov if the base register has
860 // other uses, since it avoids a two-address sub instruction, however
861 // it costs an additional mov if the index register has other uses.
863 // Test if the LHS of the sub can be folded.
864 X86ISelAddressMode Backup = AM;
865 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM,
866 DeadNodes, Depth+1) ||
867 // If it is successful but the recursive update causes N to be deleted,
868 // then it's not safe to continue.
869 DeadNodes.IsDeleted(N.getNode())) {
873 // Test if the index field is free for use.
874 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
880 SDValue RHS = N.getNode()->getOperand(1);
881 // If the RHS involves a register with multiple uses, this
882 // transformation incurs an extra mov, due to the neg instruction
883 // clobbering its operand.
884 if (!RHS.getNode()->hasOneUse() ||
885 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
886 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
887 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
888 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
889 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
891 // If the base is a register with multiple uses, this
892 // transformation may save a mov.
893 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
894 AM.Base.Reg.getNode() &&
895 !AM.Base.Reg.getNode()->hasOneUse()) ||
896 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
898 // If the folded LHS was interesting, this transformation saves
899 // address arithmetic.
900 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
901 ((AM.Disp != 0) && (Backup.Disp == 0)) +
902 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
904 // If it doesn't look like it may be an overall win, don't do it.
910 // Ok, the transformation is legal and appears profitable. Go for it.
911 SDValue Zero = CurDAG->getConstant(0, N.getValueType());
912 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
916 // Insert the new nodes into the topological ordering.
917 if (Zero.getNode()->getNodeId() == -1 ||
918 Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
919 CurDAG->RepositionNode(N.getNode(), Zero.getNode());
920 Zero.getNode()->setNodeId(N.getNode()->getNodeId());
922 if (Neg.getNode()->getNodeId() == -1 ||
923 Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
924 CurDAG->RepositionNode(N.getNode(), Neg.getNode());
925 Neg.getNode()->setNodeId(N.getNode()->getNodeId());
931 X86ISelAddressMode Backup = AM;
932 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM,
933 DeadNodes, Depth+1)) {
934 if (DeadNodes.IsDeleted(N.getNode()))
935 // If it is successful but the recursive update causes N to be deleted,
936 // then it's not safe to continue.
938 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM,
940 // If it is successful but the recursive update causes N to be deleted,
941 // then it's not safe to continue.
942 return DeadNodes.IsDeleted(N.getNode());
945 // Try again after commuting the operands.
947 if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM,
948 DeadNodes, Depth+1)) {
949 if (DeadNodes.IsDeleted(N.getNode()))
950 // If it is successful but the recursive update causes N to be deleted,
951 // then it's not safe to continue.
953 if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM,
955 // If it is successful but the recursive update causes N to be deleted,
956 // then it's not safe to continue.
957 return DeadNodes.IsDeleted(N.getNode());
961 // If we couldn't fold both operands into the address at the same time,
962 // see if we can just put each operand into a register and fold at least
964 if (AM.BaseType == X86ISelAddressMode::RegBase &&
965 !AM.Base.Reg.getNode() &&
966 !AM.IndexReg.getNode()) {
967 AM.Base.Reg = N.getNode()->getOperand(0);
968 AM.IndexReg = N.getNode()->getOperand(1);
976 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
977 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
978 X86ISelAddressMode Backup = AM;
979 uint64_t Offset = CN->getSExtValue();
981 // Check to see if the LHS & C is zero.
982 if (!CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue()))
985 // Start with the LHS as an addr mode.
986 if (!MatchAddressRecursively(N.getOperand(0), AM, DeadNodes, Depth+1) &&
987 // Address could not have picked a GV address for the displacement.
989 // On x86-64, the resultant disp must fit in 32-bits.
991 X86::isOffsetSuitableForCodeModel(AM.Disp + Offset, M,
992 AM.hasSymbolicDisplacement()))) {
1001 // Perform some heroic transforms on an and of a constant-count shift
1002 // with a constant to enable use of the scaled offset field.
1004 SDValue Shift = N.getOperand(0);
1005 if (Shift.getNumOperands() != 2) break;
1007 // Scale must not be used already.
1008 if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1010 SDValue X = Shift.getOperand(0);
1011 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1012 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1013 if (!C1 || !C2) break;
1015 // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1016 // allows us to convert the shift and and into an h-register extract and
1018 if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1019 unsigned ScaleLog = 8 - C1->getZExtValue();
1020 if (ScaleLog > 0 && ScaleLog < 4 &&
1021 C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1022 SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1023 SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1024 SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1026 SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1028 SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1029 SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1032 // Insert the new nodes into the topological ordering.
1033 if (Eight.getNode()->getNodeId() == -1 ||
1034 Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1035 CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1036 Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1038 if (Mask.getNode()->getNodeId() == -1 ||
1039 Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1040 CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1041 Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1043 if (Srl.getNode()->getNodeId() == -1 ||
1044 Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1045 CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1046 Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1048 if (And.getNode()->getNodeId() == -1 ||
1049 And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1050 CurDAG->RepositionNode(N.getNode(), And.getNode());
1051 And.getNode()->setNodeId(N.getNode()->getNodeId());
1053 if (ShlCount.getNode()->getNodeId() == -1 ||
1054 ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1055 CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1056 ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1058 if (Shl.getNode()->getNodeId() == -1 ||
1059 Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1060 CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1061 Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1063 CurDAG->ReplaceAllUsesWith(N, Shl, &DeadNodes);
1065 AM.Scale = (1 << ScaleLog);
1070 // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1071 // allows us to fold the shift into this addressing mode.
1072 if (Shift.getOpcode() != ISD::SHL) break;
1074 // Not likely to be profitable if either the AND or SHIFT node has more
1075 // than one use (unless all uses are for address computation). Besides,
1076 // isel mechanism requires their node ids to be reused.
1077 if (!N.hasOneUse() || !Shift.hasOneUse())
1080 // Verify that the shift amount is something we can fold.
1081 unsigned ShiftCst = C1->getZExtValue();
1082 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1085 // Get the new AND mask, this folds to a constant.
1086 SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1087 SDValue(C2, 0), SDValue(C1, 0));
1088 SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,
1090 SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1091 NewAND, SDValue(C1, 0));
1093 // Insert the new nodes into the topological ordering.
1094 if (C1->getNodeId() > X.getNode()->getNodeId()) {
1095 CurDAG->RepositionNode(X.getNode(), C1);
1096 C1->setNodeId(X.getNode()->getNodeId());
1098 if (NewANDMask.getNode()->getNodeId() == -1 ||
1099 NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1100 CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1101 NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1103 if (NewAND.getNode()->getNodeId() == -1 ||
1104 NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1105 CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1106 NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1108 if (NewSHIFT.getNode()->getNodeId() == -1 ||
1109 NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1110 CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1111 NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1114 CurDAG->ReplaceAllUsesWith(N, NewSHIFT, &DeadNodes);
1116 AM.Scale = 1 << ShiftCst;
1117 AM.IndexReg = NewAND;
1122 return MatchAddressBase(N, AM);
1125 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1126 /// specified addressing mode without any further recursion.
1127 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1128 // Is the base register already occupied?
1129 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1130 // If so, check to see if the scale index register is set.
1131 if (AM.IndexReg.getNode() == 0) {
1137 // Otherwise, we cannot select it.
1141 // Default, generate it as a register.
1142 AM.BaseType = X86ISelAddressMode::RegBase;
1147 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1148 /// It returns the operands which make up the maximal addressing mode it can
1149 /// match by reference.
1150 bool X86DAGToDAGISel::SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
1151 SDValue &Scale, SDValue &Index,
1152 SDValue &Disp, SDValue &Segment) {
1153 X86ISelAddressMode AM;
1154 if (MatchAddress(N, AM))
1157 EVT VT = N.getValueType();
1158 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1159 if (!AM.Base.Reg.getNode())
1160 AM.Base.Reg = CurDAG->getRegister(0, VT);
1163 if (!AM.IndexReg.getNode())
1164 AM.IndexReg = CurDAG->getRegister(0, VT);
1166 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1170 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1171 /// match a load whose top elements are either undef or zeros. The load flavor
1172 /// is derived from the type of N, which is either v4f32 or v2f64.
1175 /// PatternChainNode: this is the matched node that has a chain input and
1177 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1178 SDValue N, SDValue &Base,
1179 SDValue &Scale, SDValue &Index,
1180 SDValue &Disp, SDValue &Segment,
1181 SDValue &PatternNodeWithChain) {
1182 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1183 PatternNodeWithChain = N.getOperand(0);
1184 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1185 PatternNodeWithChain.hasOneUse() &&
1186 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1187 IsLegalToFold(N.getOperand(0), N.getNode(), Root)) {
1188 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1189 if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp,Segment))
1195 // Also handle the case where we explicitly require zeros in the top
1196 // elements. This is a vector shuffle from the zero vector.
1197 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1198 // Check to see if the top elements are all zeros (or bitcast of zeros).
1199 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1200 N.getOperand(0).getNode()->hasOneUse() &&
1201 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1202 N.getOperand(0).getOperand(0).hasOneUse() &&
1203 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1204 IsLegalToFold(N.getOperand(0), N.getNode(), Root)) {
1205 // Okay, this is a zero extending load. Fold it.
1206 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1207 if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1209 PatternNodeWithChain = SDValue(LD, 0);
1216 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1217 /// mode it matches can be cost effectively emitted as an LEA instruction.
1218 bool X86DAGToDAGISel::SelectLEAAddr(SDNode *Op, SDValue N,
1219 SDValue &Base, SDValue &Scale,
1220 SDValue &Index, SDValue &Disp) {
1221 X86ISelAddressMode AM;
1223 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1225 SDValue Copy = AM.Segment;
1226 SDValue T = CurDAG->getRegister(0, MVT::i32);
1228 if (MatchAddress(N, AM))
1230 assert (T == AM.Segment);
1233 EVT VT = N.getValueType();
1234 unsigned Complexity = 0;
1235 if (AM.BaseType == X86ISelAddressMode::RegBase)
1236 if (AM.Base.Reg.getNode())
1239 AM.Base.Reg = CurDAG->getRegister(0, VT);
1240 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1243 if (AM.IndexReg.getNode())
1246 AM.IndexReg = CurDAG->getRegister(0, VT);
1248 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1253 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1254 // to a LEA. This is determined with some expermentation but is by no means
1255 // optimal (especially for code size consideration). LEA is nice because of
1256 // its three-address nature. Tweak the cost function again when we can run
1257 // convertToThreeAddress() at register allocation time.
1258 if (AM.hasSymbolicDisplacement()) {
1259 // For X86-64, we should always use lea to materialize RIP relative
1261 if (Subtarget->is64Bit())
1267 if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1270 // If it isn't worth using an LEA, reject it.
1271 if (Complexity <= 2)
1275 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1279 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1280 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
1281 SDValue &Scale, SDValue &Index,
1283 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1284 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1286 X86ISelAddressMode AM;
1287 AM.GV = GA->getGlobal();
1288 AM.Disp += GA->getOffset();
1289 AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1290 AM.SymbolFlags = GA->getTargetFlags();
1292 if (N.getValueType() == MVT::i32) {
1294 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1296 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1300 getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1305 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1306 SDValue &Base, SDValue &Scale,
1307 SDValue &Index, SDValue &Disp,
1309 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1310 !IsProfitableToFold(N, P, P) ||
1311 !IsLegalToFold(N, P, P))
1314 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1317 /// getGlobalBaseReg - Return an SDNode that returns the value of
1318 /// the global base register. Output instructions required to
1319 /// initialize the global base register, if necessary.
1321 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1322 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1323 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1326 static SDNode *FindCallStartFromCall(SDNode *Node) {
1327 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1328 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1329 "Node doesn't have a token chain argument!");
1330 return FindCallStartFromCall(Node->getOperand(0).getNode());
1333 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1334 SDValue Chain = Node->getOperand(0);
1335 SDValue In1 = Node->getOperand(1);
1336 SDValue In2L = Node->getOperand(2);
1337 SDValue In2H = Node->getOperand(3);
1338 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1339 if (!SelectAddr(In1.getNode(), In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1341 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1342 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1343 const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, Chain};
1344 SDNode *ResNode = CurDAG->getMachineNode(Opc, Node->getDebugLoc(),
1345 MVT::i32, MVT::i32, MVT::Other, Ops,
1346 array_lengthof(Ops));
1347 cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp + 1);
1351 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, EVT NVT) {
1352 if (Node->hasAnyUseOfValue(0))
1355 // Optimize common patterns for __sync_add_and_fetch and
1356 // __sync_sub_and_fetch where the result is not used. This allows us
1357 // to use "lock" version of add, sub, inc, dec instructions.
1358 // FIXME: Do not use special instructions but instead add the "lock"
1359 // prefix to the target node somehow. The extra information will then be
1360 // transferred to machine instruction and it denotes the prefix.
1361 SDValue Chain = Node->getOperand(0);
1362 SDValue Ptr = Node->getOperand(1);
1363 SDValue Val = Node->getOperand(2);
1364 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1365 if (!SelectAddr(Ptr.getNode(), Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1368 bool isInc = false, isDec = false, isSub = false, isCN = false;
1369 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1372 int64_t CNVal = CN->getSExtValue();
1375 else if (CNVal == -1)
1377 else if (CNVal >= 0)
1378 Val = CurDAG->getTargetConstant(CNVal, NVT);
1381 Val = CurDAG->getTargetConstant(-CNVal, NVT);
1383 } else if (Val.hasOneUse() &&
1384 Val.getOpcode() == ISD::SUB &&
1385 X86::isZeroNode(Val.getOperand(0))) {
1387 Val = Val.getOperand(1);
1391 switch (NVT.getSimpleVT().SimpleTy) {
1395 Opc = X86::LOCK_INC8m;
1397 Opc = X86::LOCK_DEC8m;
1400 Opc = X86::LOCK_SUB8mi;
1402 Opc = X86::LOCK_SUB8mr;
1405 Opc = X86::LOCK_ADD8mi;
1407 Opc = X86::LOCK_ADD8mr;
1412 Opc = X86::LOCK_INC16m;
1414 Opc = X86::LOCK_DEC16m;
1417 if (Predicate_immSext8(Val.getNode()))
1418 Opc = X86::LOCK_SUB16mi8;
1420 Opc = X86::LOCK_SUB16mi;
1422 Opc = X86::LOCK_SUB16mr;
1425 if (Predicate_immSext8(Val.getNode()))
1426 Opc = X86::LOCK_ADD16mi8;
1428 Opc = X86::LOCK_ADD16mi;
1430 Opc = X86::LOCK_ADD16mr;
1435 Opc = X86::LOCK_INC32m;
1437 Opc = X86::LOCK_DEC32m;
1440 if (Predicate_immSext8(Val.getNode()))
1441 Opc = X86::LOCK_SUB32mi8;
1443 Opc = X86::LOCK_SUB32mi;
1445 Opc = X86::LOCK_SUB32mr;
1448 if (Predicate_immSext8(Val.getNode()))
1449 Opc = X86::LOCK_ADD32mi8;
1451 Opc = X86::LOCK_ADD32mi;
1453 Opc = X86::LOCK_ADD32mr;
1458 Opc = X86::LOCK_INC64m;
1460 Opc = X86::LOCK_DEC64m;
1462 Opc = X86::LOCK_SUB64mr;
1464 if (Predicate_immSext8(Val.getNode()))
1465 Opc = X86::LOCK_SUB64mi8;
1466 else if (Predicate_i64immSExt32(Val.getNode()))
1467 Opc = X86::LOCK_SUB64mi32;
1470 Opc = X86::LOCK_ADD64mr;
1472 if (Predicate_immSext8(Val.getNode()))
1473 Opc = X86::LOCK_ADD64mi8;
1474 else if (Predicate_i64immSExt32(Val.getNode()))
1475 Opc = X86::LOCK_ADD64mi32;
1481 DebugLoc dl = Node->getDebugLoc();
1482 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1484 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1485 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1486 if (isInc || isDec) {
1487 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain };
1488 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 6), 0);
1489 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1490 SDValue RetVals[] = { Undef, Ret };
1491 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1493 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, Chain };
1494 SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 7), 0);
1495 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1496 SDValue RetVals[] = { Undef, Ret };
1497 return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1501 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1502 /// any uses which require the SF or OF bits to be accurate.
1503 static bool HasNoSignedComparisonUses(SDNode *N) {
1504 // Examine each user of the node.
1505 for (SDNode::use_iterator UI = N->use_begin(),
1506 UE = N->use_end(); UI != UE; ++UI) {
1507 // Only examine CopyToReg uses.
1508 if (UI->getOpcode() != ISD::CopyToReg)
1510 // Only examine CopyToReg uses that copy to EFLAGS.
1511 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1514 // Examine each user of the CopyToReg use.
1515 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1516 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1517 // Only examine the Flag result.
1518 if (FlagUI.getUse().getResNo() != 1) continue;
1519 // Anything unusual: assume conservatively.
1520 if (!FlagUI->isMachineOpcode()) return false;
1521 // Examine the opcode of the user.
1522 switch (FlagUI->getMachineOpcode()) {
1523 // These comparisons don't treat the most significant bit specially.
1524 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1525 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1526 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1527 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1528 case X86::JA_4: case X86::JAE_4: case X86::JB_4: case X86::JBE_4:
1529 case X86::JE_4: case X86::JNE_4: case X86::JP_4: case X86::JNP_4:
1530 case X86::CMOVA16rr: case X86::CMOVA16rm:
1531 case X86::CMOVA32rr: case X86::CMOVA32rm:
1532 case X86::CMOVA64rr: case X86::CMOVA64rm:
1533 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1534 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1535 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1536 case X86::CMOVB16rr: case X86::CMOVB16rm:
1537 case X86::CMOVB32rr: case X86::CMOVB32rm:
1538 case X86::CMOVB64rr: case X86::CMOVB64rm:
1539 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1540 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1541 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1542 case X86::CMOVE16rr: case X86::CMOVE16rm:
1543 case X86::CMOVE32rr: case X86::CMOVE32rm:
1544 case X86::CMOVE64rr: case X86::CMOVE64rm:
1545 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1546 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1547 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1548 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1549 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1550 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1551 case X86::CMOVP16rr: case X86::CMOVP16rm:
1552 case X86::CMOVP32rr: case X86::CMOVP32rm:
1553 case X86::CMOVP64rr: case X86::CMOVP64rm:
1555 // Anything else: assume conservatively.
1556 default: return false;
1563 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
1564 EVT NVT = Node->getValueType(0);
1566 unsigned Opcode = Node->getOpcode();
1567 DebugLoc dl = Node->getDebugLoc();
1569 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1571 if (Node->isMachineOpcode()) {
1572 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
1573 return NULL; // Already selected.
1578 case X86ISD::GlobalBaseReg:
1579 return getGlobalBaseReg();
1581 case X86ISD::ATOMOR64_DAG:
1582 return SelectAtomic64(Node, X86::ATOMOR6432);
1583 case X86ISD::ATOMXOR64_DAG:
1584 return SelectAtomic64(Node, X86::ATOMXOR6432);
1585 case X86ISD::ATOMADD64_DAG:
1586 return SelectAtomic64(Node, X86::ATOMADD6432);
1587 case X86ISD::ATOMSUB64_DAG:
1588 return SelectAtomic64(Node, X86::ATOMSUB6432);
1589 case X86ISD::ATOMNAND64_DAG:
1590 return SelectAtomic64(Node, X86::ATOMNAND6432);
1591 case X86ISD::ATOMAND64_DAG:
1592 return SelectAtomic64(Node, X86::ATOMAND6432);
1593 case X86ISD::ATOMSWAP64_DAG:
1594 return SelectAtomic64(Node, X86::ATOMSWAP6432);
1596 case ISD::ATOMIC_LOAD_ADD: {
1597 SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1603 case ISD::SMUL_LOHI:
1604 case ISD::UMUL_LOHI: {
1605 SDValue N0 = Node->getOperand(0);
1606 SDValue N1 = Node->getOperand(1);
1608 bool isSigned = Opcode == ISD::SMUL_LOHI;
1610 switch (NVT.getSimpleVT().SimpleTy) {
1611 default: llvm_unreachable("Unsupported VT!");
1612 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1613 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1614 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1615 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1618 switch (NVT.getSimpleVT().SimpleTy) {
1619 default: llvm_unreachable("Unsupported VT!");
1620 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1621 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1622 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1623 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1627 unsigned LoReg, HiReg;
1628 switch (NVT.getSimpleVT().SimpleTy) {
1629 default: llvm_unreachable("Unsupported VT!");
1630 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1631 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1632 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1633 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1636 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1637 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1638 // Multiply is commmutative.
1640 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1645 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1646 N0, SDValue()).getValue(1);
1649 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1652 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1653 array_lengthof(Ops));
1654 InFlag = SDValue(CNode, 1);
1655 // Update the chain.
1656 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1659 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1662 // Copy the low half of the result, if it is needed.
1663 if (!SDValue(Node, 0).use_empty()) {
1664 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1665 LoReg, NVT, InFlag);
1666 InFlag = Result.getValue(2);
1667 ReplaceUses(SDValue(Node, 0), Result);
1668 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1670 // Copy the high half of the result, if it is needed.
1671 if (!SDValue(Node, 1).use_empty()) {
1673 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1674 // Prevent use of AH in a REX instruction by referencing AX instead.
1675 // Shift it down 8 bits.
1676 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1677 X86::AX, MVT::i16, InFlag);
1678 InFlag = Result.getValue(2);
1679 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1681 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1682 // Then truncate it down to i8.
1683 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1686 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1687 HiReg, NVT, InFlag);
1688 InFlag = Result.getValue(2);
1690 ReplaceUses(SDValue(Node, 1), Result);
1691 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1698 case ISD::UDIVREM: {
1699 SDValue N0 = Node->getOperand(0);
1700 SDValue N1 = Node->getOperand(1);
1702 bool isSigned = Opcode == ISD::SDIVREM;
1704 switch (NVT.getSimpleVT().SimpleTy) {
1705 default: llvm_unreachable("Unsupported VT!");
1706 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1707 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1708 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1709 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1712 switch (NVT.getSimpleVT().SimpleTy) {
1713 default: llvm_unreachable("Unsupported VT!");
1714 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1715 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1716 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1717 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1721 unsigned LoReg, HiReg, ClrReg;
1722 unsigned ClrOpcode, SExtOpcode;
1723 switch (NVT.getSimpleVT().SimpleTy) {
1724 default: llvm_unreachable("Unsupported VT!");
1726 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
1728 SExtOpcode = X86::CBW;
1731 LoReg = X86::AX; HiReg = X86::DX;
1732 ClrOpcode = X86::MOV16r0; ClrReg = X86::DX;
1733 SExtOpcode = X86::CWD;
1736 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
1737 ClrOpcode = X86::MOV32r0;
1738 SExtOpcode = X86::CDQ;
1741 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
1742 ClrOpcode = X86::MOV64r0;
1743 SExtOpcode = X86::CQO;
1747 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1748 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1749 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1752 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1753 // Special case for div8, just use a move with zero extension to AX to
1754 // clear the upper 8 bits (AH).
1755 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1756 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1757 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1759 SDValue(CurDAG->getMachineNode(X86::MOVZX16rm8, dl, MVT::i16,
1761 array_lengthof(Ops)), 0);
1762 Chain = Move.getValue(1);
1763 ReplaceUses(N0.getValue(1), Chain);
1766 SDValue(CurDAG->getMachineNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1767 Chain = CurDAG->getEntryNode();
1769 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1770 InFlag = Chain.getValue(1);
1773 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1774 LoReg, N0, SDValue()).getValue(1);
1775 if (isSigned && !signBitIsZero) {
1776 // Sign extend the low part into the high part.
1778 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1780 // Zero out the high part, effectively zero extending the input.
1782 SDValue(CurDAG->getMachineNode(ClrOpcode, dl, NVT), 0);
1783 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
1784 ClrNode, InFlag).getValue(1);
1789 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1792 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1793 array_lengthof(Ops));
1794 InFlag = SDValue(CNode, 1);
1795 // Update the chain.
1796 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1799 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1802 // Copy the division (low) result, if it is needed.
1803 if (!SDValue(Node, 0).use_empty()) {
1804 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1805 LoReg, NVT, InFlag);
1806 InFlag = Result.getValue(2);
1807 ReplaceUses(SDValue(Node, 0), Result);
1808 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1810 // Copy the remainder (high) result, if it is needed.
1811 if (!SDValue(Node, 1).use_empty()) {
1813 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1814 // Prevent use of AH in a REX instruction by referencing AX instead.
1815 // Shift it down 8 bits.
1816 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1817 X86::AX, MVT::i16, InFlag);
1818 InFlag = Result.getValue(2);
1819 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1821 CurDAG->getTargetConstant(8, MVT::i8)),
1823 // Then truncate it down to i8.
1824 Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1827 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1828 HiReg, NVT, InFlag);
1829 InFlag = Result.getValue(2);
1831 ReplaceUses(SDValue(Node, 1), Result);
1832 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1838 SDValue N0 = Node->getOperand(0);
1839 SDValue N1 = Node->getOperand(1);
1841 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
1842 // use a smaller encoding.
1843 if (N0.getNode()->getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1844 N0.getValueType() != MVT::i8 &&
1845 X86::isZeroNode(N1)) {
1846 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
1849 // For example, convert "testl %eax, $8" to "testb %al, $8"
1850 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
1851 (!(C->getZExtValue() & 0x80) ||
1852 HasNoSignedComparisonUses(Node))) {
1853 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
1854 SDValue Reg = N0.getNode()->getOperand(0);
1856 // On x86-32, only the ABCD registers have 8-bit subregisters.
1857 if (!Subtarget->is64Bit()) {
1858 TargetRegisterClass *TRC = 0;
1859 switch (N0.getValueType().getSimpleVT().SimpleTy) {
1860 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1861 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1862 default: llvm_unreachable("Unsupported TEST operand type!");
1864 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1865 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1866 Reg.getValueType(), Reg, RC), 0);
1869 // Extract the l-register.
1870 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1874 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32, Subreg, Imm);
1877 // For example, "testl %eax, $2048" to "testb %ah, $8".
1878 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
1879 (!(C->getZExtValue() & 0x8000) ||
1880 HasNoSignedComparisonUses(Node))) {
1881 // Shift the immediate right by 8 bits.
1882 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
1884 SDValue Reg = N0.getNode()->getOperand(0);
1886 // Put the value in an ABCD register.
1887 TargetRegisterClass *TRC = 0;
1888 switch (N0.getValueType().getSimpleVT().SimpleTy) {
1889 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
1890 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1891 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1892 default: llvm_unreachable("Unsupported TEST operand type!");
1894 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1895 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1896 Reg.getValueType(), Reg, RC), 0);
1898 // Extract the h-register.
1899 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT_HI, dl,
1902 // Emit a testb. No special NOREX tricks are needed since there's
1903 // only one GPR operand!
1904 return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
1905 Subreg, ShiftedImm);
1908 // For example, "testl %eax, $32776" to "testw %ax, $32776".
1909 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
1910 N0.getValueType() != MVT::i16 &&
1911 (!(C->getZExtValue() & 0x8000) ||
1912 HasNoSignedComparisonUses(Node))) {
1913 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
1914 SDValue Reg = N0.getNode()->getOperand(0);
1916 // Extract the 16-bit subregister.
1917 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_16BIT, dl,
1921 return CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32, Subreg, Imm);
1924 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
1925 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
1926 N0.getValueType() == MVT::i64 &&
1927 (!(C->getZExtValue() & 0x80000000) ||
1928 HasNoSignedComparisonUses(Node))) {
1929 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
1930 SDValue Reg = N0.getNode()->getOperand(0);
1932 // Extract the 32-bit subregister.
1933 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_32BIT, dl,
1937 return CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32, Subreg, Imm);
1944 SDNode *ResNode = SelectCode(Node);
1946 DEBUG(dbgs() << "=> ";
1947 if (ResNode == NULL || ResNode == Node)
1950 ResNode->dump(CurDAG);
1956 bool X86DAGToDAGISel::
1957 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1958 std::vector<SDValue> &OutOps) {
1959 SDValue Op0, Op1, Op2, Op3, Op4;
1960 switch (ConstraintCode) {
1961 case 'o': // offsetable ??
1962 case 'v': // not offsetable ??
1963 default: return true;
1965 if (!SelectAddr(Op.getNode(), Op, Op0, Op1, Op2, Op3, Op4))
1970 OutOps.push_back(Op0);
1971 OutOps.push_back(Op1);
1972 OutOps.push_back(Op2);
1973 OutOps.push_back(Op3);
1974 OutOps.push_back(Op4);
1978 /// createX86ISelDag - This pass converts a legalized DAG into a
1979 /// X86-specific DAG, ready for instruction scheduling.
1981 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1982 llvm::CodeGenOpt::Level OptLevel) {
1983 return new X86DAGToDAGISel(TM, OptLevel);