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 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
42 #define DEBUG_TYPE "x86-isel"
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46 //===----------------------------------------------------------------------===//
47 // Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
51 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52 /// numbers for the leaves of the matched tree.
53 struct X86ISelAddressMode {
59 // This is really a union, discriminated by BaseType!
67 const GlobalValue *GV;
69 const BlockAddress *BlockAddr;
73 unsigned Align; // CP alignment.
74 unsigned char SymbolFlags; // X86II::MO_*
77 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
78 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
79 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
81 bool hasSymbolicDisplacement() const {
82 return GV != nullptr || CP != nullptr || ES != nullptr ||
83 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
86 bool hasBaseOrIndexReg() const {
87 return BaseType == FrameIndexBase ||
88 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
91 /// Return true if this addressing mode is already RIP-relative.
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) {
105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
107 dbgs() << "X86ISelAddressMode " << this << '\n';
108 dbgs() << "Base_Reg ";
109 if (Base_Reg.getNode())
110 Base_Reg.getNode()->dump();
113 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
114 << " Scale" << Scale << '\n'
116 if (IndexReg.getNode())
117 IndexReg.getNode()->dump();
120 dbgs() << " Disp " << Disp << '\n'
142 dbgs() << " JT" << JT << " Align" << Align << '\n';
149 //===--------------------------------------------------------------------===//
150 /// ISel - X86-specific code to select X86 machine instructions for
151 /// SelectionDAG operations.
153 class X86DAGToDAGISel final : public SelectionDAGISel {
154 /// Keep a pointer to the X86Subtarget around so that we can
155 /// make the right decision when generating code for different targets.
156 const X86Subtarget *Subtarget;
158 /// If true, selector should try to optimize for code size instead of
162 /// If true, selector should try to optimize for minimum code size.
166 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
167 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
168 OptForMinSize(false) {}
170 StringRef getPassName() const override {
171 return "X86 DAG->DAG Instruction Selection";
174 bool runOnMachineFunction(MachineFunction &MF) override {
175 // Reset the subtarget each time through.
176 Subtarget = &MF.getSubtarget<X86Subtarget>();
177 SelectionDAGISel::runOnMachineFunction(MF);
181 void EmitFunctionEntryCode() override;
183 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
185 void PreprocessISelDAG() override;
187 // Include the pieces autogenerated from the target description.
188 #include "X86GenDAGISel.inc"
191 void Select(SDNode *N) override;
193 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
194 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
195 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
196 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
197 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
198 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
200 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
202 SDValue &Scale, SDValue &Index, SDValue &Disp,
204 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
205 SDValue &Scale, SDValue &Index, SDValue &Disp,
207 template <class GatherScatterSDNode>
208 bool selectAddrOfGatherScatterNode(GatherScatterSDNode *Parent, SDValue N,
209 SDValue &Base, SDValue &Scale,
210 SDValue &Index, SDValue &Disp,
212 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
213 bool selectLEAAddr(SDValue N, SDValue &Base,
214 SDValue &Scale, SDValue &Index, SDValue &Disp,
216 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
217 SDValue &Scale, SDValue &Index, SDValue &Disp,
219 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
220 SDValue &Scale, SDValue &Index, SDValue &Disp,
222 bool selectScalarSSELoad(SDNode *Root, SDValue N,
223 SDValue &Base, SDValue &Scale,
224 SDValue &Index, SDValue &Disp,
226 SDValue &NodeWithChain);
227 bool selectRelocImm(SDValue N, SDValue &Op);
229 bool tryFoldLoad(SDNode *P, SDValue N,
230 SDValue &Base, SDValue &Scale,
231 SDValue &Index, SDValue &Disp,
234 /// Implement addressing mode selection for inline asm expressions.
235 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
236 unsigned ConstraintID,
237 std::vector<SDValue> &OutOps) override;
239 void emitSpecialCodeForMain();
241 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
242 SDValue &Base, SDValue &Scale,
243 SDValue &Index, SDValue &Disp,
245 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
246 ? CurDAG->getTargetFrameIndex(
248 TLI->getPointerTy(CurDAG->getDataLayout()))
250 Scale = getI8Imm(AM.Scale, DL);
252 // These are 32-bit even in 64-bit mode since RIP-relative offset
255 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
259 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
260 AM.Align, AM.Disp, AM.SymbolFlags);
262 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
263 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
264 } else if (AM.MCSym) {
265 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
266 assert(AM.SymbolFlags == 0 && "oo");
267 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
268 } else if (AM.JT != -1) {
269 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
270 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
271 } else if (AM.BlockAddr)
272 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
275 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
277 if (AM.Segment.getNode())
278 Segment = AM.Segment;
280 Segment = CurDAG->getRegister(0, MVT::i32);
283 // Utility function to determine whether we should avoid selecting
284 // immediate forms of instructions for better code size or not.
285 // At a high level, we'd like to avoid such instructions when
286 // we have similar constants used within the same basic block
287 // that can be kept in a register.
289 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
290 uint32_t UseCount = 0;
292 // Do not want to hoist if we're not optimizing for size.
293 // TODO: We'd like to remove this restriction.
294 // See the comment in X86InstrInfo.td for more info.
298 // Walk all the users of the immediate.
299 for (SDNode::use_iterator UI = N->use_begin(),
300 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
304 // This user is already selected. Count it as a legitimate use and
306 if (User->isMachineOpcode()) {
311 // We want to count stores of immediates as real uses.
312 if (User->getOpcode() == ISD::STORE &&
313 User->getOperand(1).getNode() == N) {
318 // We don't currently match users that have > 2 operands (except
319 // for stores, which are handled above)
320 // Those instruction won't match in ISEL, for now, and would
321 // be counted incorrectly.
322 // This may change in the future as we add additional instruction
324 if (User->getNumOperands() != 2)
327 // Immediates that are used for offsets as part of stack
328 // manipulation should be left alone. These are typically
329 // used to indicate SP offsets for argument passing and
330 // will get pulled into stores/pushes (implicitly).
331 if (User->getOpcode() == X86ISD::ADD ||
332 User->getOpcode() == ISD::ADD ||
333 User->getOpcode() == X86ISD::SUB ||
334 User->getOpcode() == ISD::SUB) {
336 // Find the other operand of the add/sub.
337 SDValue OtherOp = User->getOperand(0);
338 if (OtherOp.getNode() == N)
339 OtherOp = User->getOperand(1);
341 // Don't count if the other operand is SP.
342 RegisterSDNode *RegNode;
343 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
344 (RegNode = dyn_cast_or_null<RegisterSDNode>(
345 OtherOp->getOperand(1).getNode())))
346 if ((RegNode->getReg() == X86::ESP) ||
347 (RegNode->getReg() == X86::RSP))
351 // ... otherwise, count this and move on.
355 // If we have more than 1 use, then recommend for hoisting.
356 return (UseCount > 1);
359 /// Return a target constant with the specified value of type i8.
360 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
361 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
364 /// Return a target constant with the specified value, of type i32.
365 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
366 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
369 /// Return an SDNode that returns the value of the global base register.
370 /// Output instructions required to initialize the global base register,
372 SDNode *getGlobalBaseReg();
374 /// Return a reference to the TargetMachine, casted to the target-specific
376 const X86TargetMachine &getTargetMachine() const {
377 return static_cast<const X86TargetMachine &>(TM);
380 /// Return a reference to the TargetInstrInfo, casted to the target-specific
382 const X86InstrInfo *getInstrInfo() const {
383 return Subtarget->getInstrInfo();
386 /// \brief Address-mode matching performs shift-of-and to and-of-shift
387 /// reassociation in order to expose more scaled addressing
389 bool ComplexPatternFuncMutatesDAG() const override {
393 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
395 /// Returns whether this is a relocatable immediate in the range
396 /// [-2^Width .. 2^Width-1].
397 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
398 if (auto *CN = dyn_cast<ConstantSDNode>(N))
399 return isInt<Width>(CN->getSExtValue());
400 return isSExtAbsoluteSymbolRef(Width, N);
407 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
408 if (OptLevel == CodeGenOpt::None) return false;
413 if (N.getOpcode() != ISD::LOAD)
416 // If N is a load, do additional profitability checks.
418 switch (U->getOpcode()) {
430 SDValue Op1 = U->getOperand(1);
432 // If the other operand is a 8-bit immediate we should fold the immediate
433 // instead. This reduces code size.
435 // movl 4(%esp), %eax
439 // addl 4(%esp), %eax
440 // The former is 2 bytes shorter. In case where the increment is 1, then
441 // the saving can be 4 bytes (by using incl %eax).
442 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
443 if (Imm->getAPIntValue().isSignedIntN(8))
446 // If the other operand is a TLS address, we should fold it instead.
449 // leal i@NTPOFF(%eax), %eax
451 // movl $i@NTPOFF, %eax
453 // if the block also has an access to a second TLS address this will save
455 // FIXME: This is probably also true for non-TLS addresses.
456 if (Op1.getOpcode() == X86ISD::Wrapper) {
457 SDValue Val = Op1.getOperand(0);
458 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
468 /// Replace the original chain operand of the call with
469 /// load's chain operand and move load below the call's chain operand.
470 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
471 SDValue Call, SDValue OrigChain) {
472 SmallVector<SDValue, 8> Ops;
473 SDValue Chain = OrigChain.getOperand(0);
474 if (Chain.getNode() == Load.getNode())
475 Ops.push_back(Load.getOperand(0));
477 assert(Chain.getOpcode() == ISD::TokenFactor &&
478 "Unexpected chain operand");
479 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
480 if (Chain.getOperand(i).getNode() == Load.getNode())
481 Ops.push_back(Load.getOperand(0));
483 Ops.push_back(Chain.getOperand(i));
485 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
487 Ops.push_back(NewChain);
489 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
490 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
491 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
492 Load.getOperand(1), Load.getOperand(2));
495 Ops.push_back(SDValue(Load.getNode(), 1));
496 Ops.append(Call->op_begin() + 1, Call->op_end());
497 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
500 /// Return true if call address is a load and it can be
501 /// moved below CALLSEQ_START and the chains leading up to the call.
502 /// Return the CALLSEQ_START by reference as a second output.
503 /// In the case of a tail call, there isn't a callseq node between the call
504 /// chain and the load.
505 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
506 // The transformation is somewhat dangerous if the call's chain was glued to
507 // the call. After MoveBelowOrigChain the load is moved between the call and
508 // the chain, this can create a cycle if the load is not folded. So it is
509 // *really* important that we are sure the load will be folded.
510 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
512 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
515 LD->getAddressingMode() != ISD::UNINDEXED ||
516 LD->getExtensionType() != ISD::NON_EXTLOAD)
519 // Now let's find the callseq_start.
520 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
521 if (!Chain.hasOneUse())
523 Chain = Chain.getOperand(0);
526 if (!Chain.getNumOperands())
528 // Since we are not checking for AA here, conservatively abort if the chain
529 // writes to memory. It's not safe to move the callee (a load) across a store.
530 if (isa<MemSDNode>(Chain.getNode()) &&
531 cast<MemSDNode>(Chain.getNode())->writeMem())
533 if (Chain.getOperand(0).getNode() == Callee.getNode())
535 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
536 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
537 Callee.getValue(1).hasOneUse())
542 void X86DAGToDAGISel::PreprocessISelDAG() {
543 // OptFor[Min]Size are used in pattern predicates that isel is matching.
544 OptForSize = MF->getFunction()->optForSize();
545 OptForMinSize = MF->getFunction()->optForMinSize();
546 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
548 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
549 E = CurDAG->allnodes_end(); I != E; ) {
550 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
552 if (OptLevel != CodeGenOpt::None &&
553 // Only does this when target favors doesn't favor register indirect
555 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
556 (N->getOpcode() == X86ISD::TC_RETURN &&
557 // Only does this if load can be folded into TC_RETURN.
558 (Subtarget->is64Bit() ||
559 !getTargetMachine().isPositionIndependent())))) {
560 /// Also try moving call address load from outside callseq_start to just
561 /// before the call to allow it to be folded.
579 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
580 SDValue Chain = N->getOperand(0);
581 SDValue Load = N->getOperand(1);
582 if (!isCalleeLoad(Load, Chain, HasCallSeq))
584 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
589 // Lower fpround and fpextend nodes that target the FP stack to be store and
590 // load to the stack. This is a gross hack. We would like to simply mark
591 // these as being illegal, but when we do that, legalize produces these when
592 // it expands calls, then expands these in the same legalize pass. We would
593 // like dag combine to be able to hack on these between the call expansion
594 // and the node legalization. As such this pass basically does "really
595 // late" legalization of these inline with the X86 isel pass.
596 // FIXME: This should only happen when not compiled with -O0.
597 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
600 MVT SrcVT = N->getOperand(0).getSimpleValueType();
601 MVT DstVT = N->getSimpleValueType(0);
603 // If any of the sources are vectors, no fp stack involved.
604 if (SrcVT.isVector() || DstVT.isVector())
607 // If the source and destination are SSE registers, then this is a legal
608 // conversion that should not be lowered.
609 const X86TargetLowering *X86Lowering =
610 static_cast<const X86TargetLowering *>(TLI);
611 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
612 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
613 if (SrcIsSSE && DstIsSSE)
616 if (!SrcIsSSE && !DstIsSSE) {
617 // If this is an FPStack extension, it is a noop.
618 if (N->getOpcode() == ISD::FP_EXTEND)
620 // If this is a value-preserving FPStack truncation, it is a noop.
621 if (N->getConstantOperandVal(1))
625 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
626 // FPStack has extload and truncstore. SSE can fold direct loads into other
627 // operations. Based on this, decide what we want to do.
629 if (N->getOpcode() == ISD::FP_ROUND)
630 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
632 MemVT = SrcIsSSE ? SrcVT : DstVT;
634 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
637 // FIXME: optimize the case where the src/dest is a load or store?
639 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
640 MemTmp, MachinePointerInfo(), MemVT);
641 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
642 MachinePointerInfo(), MemVT);
644 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
645 // extload we created. This will cause general havok on the dag because
646 // anything below the conversion could be folded into other existing nodes.
647 // To avoid invalidating 'I', back it up to the convert node.
649 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
651 // Now that we did that, the node is dead. Increment the iterator to the
652 // next node to process, then delete N.
654 CurDAG->DeleteNode(N);
659 /// Emit any code that needs to be executed only in the main function.
660 void X86DAGToDAGISel::emitSpecialCodeForMain() {
661 if (Subtarget->isTargetCygMing()) {
662 TargetLowering::ArgListTy Args;
663 auto &DL = CurDAG->getDataLayout();
665 TargetLowering::CallLoweringInfo CLI(*CurDAG);
666 CLI.setChain(CurDAG->getRoot())
667 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
668 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
670 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
671 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
672 CurDAG->setRoot(Result.second);
676 void X86DAGToDAGISel::EmitFunctionEntryCode() {
677 // If this is main, emit special code for main.
678 if (const Function *Fn = MF->getFunction())
679 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
680 emitSpecialCodeForMain();
683 static bool isDispSafeForFrameIndex(int64_t Val) {
684 // On 64-bit platforms, we can run into an issue where a frame index
685 // includes a displacement that, when added to the explicit displacement,
686 // will overflow the displacement field. Assuming that the frame index
687 // displacement fits into a 31-bit integer (which is only slightly more
688 // aggressive than the current fundamental assumption that it fits into
689 // a 32-bit integer), a 31-bit disp should always be safe.
690 return isInt<31>(Val);
693 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
694 X86ISelAddressMode &AM) {
695 // Cannot combine ExternalSymbol displacements with integer offsets.
696 if (Offset != 0 && (AM.ES || AM.MCSym))
698 int64_t Val = AM.Disp + Offset;
699 CodeModel::Model M = TM.getCodeModel();
700 if (Subtarget->is64Bit()) {
701 if (!X86::isOffsetSuitableForCodeModel(Val, M,
702 AM.hasSymbolicDisplacement()))
704 // In addition to the checks required for a register base, check that
705 // we do not try to use an unsafe Disp with a frame index.
706 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
707 !isDispSafeForFrameIndex(Val))
715 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
716 SDValue Address = N->getOperand(1);
718 // load gs:0 -> GS segment register.
719 // load fs:0 -> FS segment register.
721 // This optimization is valid because the GNU TLS model defines that
722 // gs:0 (or fs:0 on X86-64) contains its own address.
723 // For more information see http://people.redhat.com/drepper/tls.pdf
724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
725 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
726 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
727 Subtarget->isTargetFuchsia()))
728 switch (N->getPointerInfo().getAddrSpace()) {
730 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
733 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
735 // Address space 258 is not handled here, because it is not used to
736 // address TLS areas.
742 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
743 /// mode. These wrap things that will resolve down into a symbol reference.
744 /// If no match is possible, this returns true, otherwise it returns false.
745 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
746 // If the addressing mode already has a symbol as the displacement, we can
747 // never match another symbol.
748 if (AM.hasSymbolicDisplacement())
751 SDValue N0 = N.getOperand(0);
752 CodeModel::Model M = TM.getCodeModel();
754 // Handle X86-64 rip-relative addresses. We check this before checking direct
755 // folding because RIP is preferable to non-RIP accesses.
756 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
757 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
758 // they cannot be folded into immediate fields.
759 // FIXME: This can be improved for kernel and other models?
760 (M == CodeModel::Small || M == CodeModel::Kernel)) {
761 // Base and index reg must be 0 in order to use %rip as base.
762 if (AM.hasBaseOrIndexReg())
764 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
765 X86ISelAddressMode Backup = AM;
766 AM.GV = G->getGlobal();
767 AM.SymbolFlags = G->getTargetFlags();
768 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
772 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
773 X86ISelAddressMode Backup = AM;
774 AM.CP = CP->getConstVal();
775 AM.Align = CP->getAlignment();
776 AM.SymbolFlags = CP->getTargetFlags();
777 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
781 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
782 AM.ES = S->getSymbol();
783 AM.SymbolFlags = S->getTargetFlags();
784 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
785 AM.MCSym = S->getMCSymbol();
786 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
787 AM.JT = J->getIndex();
788 AM.SymbolFlags = J->getTargetFlags();
789 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
790 X86ISelAddressMode Backup = AM;
791 AM.BlockAddr = BA->getBlockAddress();
792 AM.SymbolFlags = BA->getTargetFlags();
793 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
798 llvm_unreachable("Unhandled symbol reference node.");
800 if (N.getOpcode() == X86ISD::WrapperRIP)
801 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
805 // Handle the case when globals fit in our immediate field: This is true for
806 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
807 // mode, this only applies to a non-RIP-relative computation.
808 if (!Subtarget->is64Bit() ||
809 M == CodeModel::Small || M == CodeModel::Kernel) {
810 assert(N.getOpcode() != X86ISD::WrapperRIP &&
811 "RIP-relative addressing already handled");
812 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
813 AM.GV = G->getGlobal();
814 AM.Disp += G->getOffset();
815 AM.SymbolFlags = G->getTargetFlags();
816 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
817 AM.CP = CP->getConstVal();
818 AM.Align = CP->getAlignment();
819 AM.Disp += CP->getOffset();
820 AM.SymbolFlags = CP->getTargetFlags();
821 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
822 AM.ES = S->getSymbol();
823 AM.SymbolFlags = S->getTargetFlags();
824 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
825 AM.MCSym = S->getMCSymbol();
826 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
827 AM.JT = J->getIndex();
828 AM.SymbolFlags = J->getTargetFlags();
829 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
830 AM.BlockAddr = BA->getBlockAddress();
831 AM.Disp += BA->getOffset();
832 AM.SymbolFlags = BA->getTargetFlags();
834 llvm_unreachable("Unhandled symbol reference node.");
841 /// Add the specified node to the specified addressing mode, returning true if
842 /// it cannot be done. This just pattern matches for the addressing mode.
843 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
844 if (matchAddressRecursively(N, AM, 0))
847 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
848 // a smaller encoding and avoids a scaled-index.
850 AM.BaseType == X86ISelAddressMode::RegBase &&
851 AM.Base_Reg.getNode() == nullptr) {
852 AM.Base_Reg = AM.IndexReg;
856 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
857 // because it has a smaller encoding.
858 // TODO: Which other code models can use this?
859 if (TM.getCodeModel() == CodeModel::Small &&
860 Subtarget->is64Bit() &&
862 AM.BaseType == X86ISelAddressMode::RegBase &&
863 AM.Base_Reg.getNode() == nullptr &&
864 AM.IndexReg.getNode() == nullptr &&
865 AM.SymbolFlags == X86II::MO_NO_FLAG &&
866 AM.hasSymbolicDisplacement())
867 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
872 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
874 // Add an artificial use to this node so that we can keep track of
875 // it if it gets CSE'd with a different node.
876 HandleSDNode Handle(N);
878 X86ISelAddressMode Backup = AM;
879 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
880 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
884 // Try again after commuting the operands.
885 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
886 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
890 // If we couldn't fold both operands into the address at the same time,
891 // see if we can just put each operand into a register and fold at least
893 if (AM.BaseType == X86ISelAddressMode::RegBase &&
894 !AM.Base_Reg.getNode() &&
895 !AM.IndexReg.getNode()) {
896 N = Handle.getValue();
897 AM.Base_Reg = N.getOperand(0);
898 AM.IndexReg = N.getOperand(1);
902 N = Handle.getValue();
906 // Insert a node into the DAG at least before the Pos node's position. This
907 // will reposition the node as needed, and will assign it a node ID that is <=
908 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
909 // IDs! The selection DAG must no longer depend on their uniqueness when this
911 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
912 if (N.getNode()->getNodeId() == -1 ||
913 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
914 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
915 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
919 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
920 // safe. This allows us to convert the shift and and into an h-register
921 // extract and a scaled index. Returns false if the simplification is
923 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
925 SDValue Shift, SDValue X,
926 X86ISelAddressMode &AM) {
927 if (Shift.getOpcode() != ISD::SRL ||
928 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
932 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
933 if (ScaleLog <= 0 || ScaleLog >= 4 ||
934 Mask != (0xffu << ScaleLog))
937 MVT VT = N.getSimpleValueType();
939 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
940 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
941 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
942 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
943 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
944 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
946 // Insert the new nodes into the topological ordering. We must do this in
947 // a valid topological ordering as nothing is going to go back and re-sort
948 // these nodes. We continually insert before 'N' in sequence as this is
949 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
950 // hierarchy left to express.
951 insertDAGNode(DAG, N, Eight);
952 insertDAGNode(DAG, N, Srl);
953 insertDAGNode(DAG, N, NewMask);
954 insertDAGNode(DAG, N, And);
955 insertDAGNode(DAG, N, ShlCount);
956 insertDAGNode(DAG, N, Shl);
957 DAG.ReplaceAllUsesWith(N, Shl);
959 AM.Scale = (1 << ScaleLog);
963 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
964 // allows us to fold the shift into this addressing mode. Returns false if the
965 // transform succeeded.
966 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
968 SDValue Shift, SDValue X,
969 X86ISelAddressMode &AM) {
970 if (Shift.getOpcode() != ISD::SHL ||
971 !isa<ConstantSDNode>(Shift.getOperand(1)))
974 // Not likely to be profitable if either the AND or SHIFT node has more
975 // than one use (unless all uses are for address computation). Besides,
976 // isel mechanism requires their node ids to be reused.
977 if (!N.hasOneUse() || !Shift.hasOneUse())
980 // Verify that the shift amount is something we can fold.
981 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
982 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
985 MVT VT = N.getSimpleValueType();
987 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
988 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
989 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
991 // Insert the new nodes into the topological ordering. We must do this in
992 // a valid topological ordering as nothing is going to go back and re-sort
993 // these nodes. We continually insert before 'N' in sequence as this is
994 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
995 // hierarchy left to express.
996 insertDAGNode(DAG, N, NewMask);
997 insertDAGNode(DAG, N, NewAnd);
998 insertDAGNode(DAG, N, NewShift);
999 DAG.ReplaceAllUsesWith(N, NewShift);
1001 AM.Scale = 1 << ShiftAmt;
1002 AM.IndexReg = NewAnd;
1006 // Implement some heroics to detect shifts of masked values where the mask can
1007 // be replaced by extending the shift and undoing that in the addressing mode
1008 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1009 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1010 // the addressing mode. This results in code such as:
1012 // int f(short *y, int *lookup_table) {
1014 // return *y + lookup_table[*y >> 11];
1018 // movzwl (%rdi), %eax
1021 // addl (%rsi,%rcx,4), %eax
1024 // movzwl (%rdi), %eax
1028 // addl (%rsi,%rcx), %eax
1030 // Note that this function assumes the mask is provided as a mask *after* the
1031 // value is shifted. The input chain may or may not match that, but computing
1032 // such a mask is trivial.
1033 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1035 SDValue Shift, SDValue X,
1036 X86ISelAddressMode &AM) {
1037 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1038 !isa<ConstantSDNode>(Shift.getOperand(1)))
1041 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1042 unsigned MaskLZ = countLeadingZeros(Mask);
1043 unsigned MaskTZ = countTrailingZeros(Mask);
1045 // The amount of shift we're trying to fit into the addressing mode is taken
1046 // from the trailing zeros of the mask.
1047 unsigned AMShiftAmt = MaskTZ;
1049 // There is nothing we can do here unless the mask is removing some bits.
1050 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1051 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1053 // We also need to ensure that mask is a continuous run of bits.
1054 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1056 // Scale the leading zero count down based on the actual size of the value.
1057 // Also scale it down based on the size of the shift.
1058 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1060 // The final check is to ensure that any masked out high bits of X are
1061 // already known to be zero. Otherwise, the mask has a semantic impact
1062 // other than masking out a couple of low bits. Unfortunately, because of
1063 // the mask, zero extensions will be removed from operands in some cases.
1064 // This code works extra hard to look through extensions because we can
1065 // replace them with zero extensions cheaply if necessary.
1066 bool ReplacingAnyExtend = false;
1067 if (X.getOpcode() == ISD::ANY_EXTEND) {
1068 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1069 X.getOperand(0).getSimpleValueType().getSizeInBits();
1070 // Assume that we'll replace the any-extend with a zero-extend, and
1071 // narrow the search to the extended value.
1072 X = X.getOperand(0);
1073 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1074 ReplacingAnyExtend = true;
1076 APInt MaskedHighBits =
1077 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1079 DAG.computeKnownBits(X, Known);
1080 if (MaskedHighBits != Known.Zero) return true;
1082 // We've identified a pattern that can be transformed into a single shift
1083 // and an addressing mode. Make it so.
1084 MVT VT = N.getSimpleValueType();
1085 if (ReplacingAnyExtend) {
1086 assert(X.getValueType() != VT);
1087 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1088 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1089 insertDAGNode(DAG, N, NewX);
1093 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1094 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1095 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1096 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1098 // Insert the new nodes into the topological ordering. We must do this in
1099 // a valid topological ordering as nothing is going to go back and re-sort
1100 // these nodes. We continually insert before 'N' in sequence as this is
1101 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1102 // hierarchy left to express.
1103 insertDAGNode(DAG, N, NewSRLAmt);
1104 insertDAGNode(DAG, N, NewSRL);
1105 insertDAGNode(DAG, N, NewSHLAmt);
1106 insertDAGNode(DAG, N, NewSHL);
1107 DAG.ReplaceAllUsesWith(N, NewSHL);
1109 AM.Scale = 1 << AMShiftAmt;
1110 AM.IndexReg = NewSRL;
1114 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1118 dbgs() << "MatchAddress: ";
1123 return matchAddressBase(N, AM);
1125 // If this is already a %rip relative address, we can only merge immediates
1126 // into it. Instead of handling this in every case, we handle it here.
1127 // RIP relative addressing: %rip + 32-bit displacement!
1128 if (AM.isRIPRelative()) {
1129 // FIXME: JumpTable and ExternalSymbol address currently don't like
1130 // displacements. It isn't very important, but this should be fixed for
1132 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1135 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1136 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1141 switch (N.getOpcode()) {
1143 case ISD::LOCAL_RECOVER: {
1144 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1145 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1146 // Use the symbol and don't prefix it.
1147 AM.MCSym = ESNode->getMCSymbol();
1152 case ISD::Constant: {
1153 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1154 if (!foldOffsetIntoAddress(Val, AM))
1159 case X86ISD::Wrapper:
1160 case X86ISD::WrapperRIP:
1161 if (!matchWrapper(N, AM))
1166 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1170 case ISD::FrameIndex:
1171 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1172 AM.Base_Reg.getNode() == nullptr &&
1173 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1174 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1175 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1181 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1184 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1185 unsigned Val = CN->getZExtValue();
1186 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1187 // that the base operand remains free for further matching. If
1188 // the base doesn't end up getting used, a post-processing step
1189 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1190 if (Val == 1 || Val == 2 || Val == 3) {
1191 AM.Scale = 1 << Val;
1192 SDValue ShVal = N.getOperand(0);
1194 // Okay, we know that we have a scale by now. However, if the scaled
1195 // value is an add of something and a constant, we can fold the
1196 // constant into the disp field here.
1197 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1198 AM.IndexReg = ShVal.getOperand(0);
1199 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
1200 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1201 if (!foldOffsetIntoAddress(Disp, AM))
1205 AM.IndexReg = ShVal;
1212 // Scale must not be used already.
1213 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1215 SDValue And = N.getOperand(0);
1216 if (And.getOpcode() != ISD::AND) break;
1217 SDValue X = And.getOperand(0);
1219 // We only handle up to 64-bit values here as those are what matter for
1220 // addressing mode optimizations.
1221 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1223 // The mask used for the transform is expected to be post-shift, but we
1224 // found the shift first so just apply the shift to the mask before passing
1226 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1227 !isa<ConstantSDNode>(And.getOperand(1)))
1229 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1231 // Try to fold the mask and shift into the scale, and return false if we
1233 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1238 case ISD::SMUL_LOHI:
1239 case ISD::UMUL_LOHI:
1240 // A mul_lohi where we need the low part can be folded as a plain multiply.
1241 if (N.getResNo() != 0) break;
1244 case X86ISD::MUL_IMM:
1245 // X*[3,5,9] -> X+X*[2,4,8]
1246 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1247 AM.Base_Reg.getNode() == nullptr &&
1248 AM.IndexReg.getNode() == nullptr) {
1249 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1250 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1251 CN->getZExtValue() == 9) {
1252 AM.Scale = unsigned(CN->getZExtValue())-1;
1254 SDValue MulVal = N.getOperand(0);
1257 // Okay, we know that we have a scale by now. However, if the scaled
1258 // value is an add of something and a constant, we can fold the
1259 // constant into the disp field here.
1260 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1261 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1262 Reg = MulVal.getOperand(0);
1263 ConstantSDNode *AddVal =
1264 cast<ConstantSDNode>(MulVal.getOperand(1));
1265 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1266 if (foldOffsetIntoAddress(Disp, AM))
1267 Reg = N.getOperand(0);
1269 Reg = N.getOperand(0);
1272 AM.IndexReg = AM.Base_Reg = Reg;
1279 // Given A-B, if A can be completely folded into the address and
1280 // the index field with the index field unused, use -B as the index.
1281 // This is a win if a has multiple parts that can be folded into
1282 // the address. Also, this saves a mov if the base register has
1283 // other uses, since it avoids a two-address sub instruction, however
1284 // it costs an additional mov if the index register has other uses.
1286 // Add an artificial use to this node so that we can keep track of
1287 // it if it gets CSE'd with a different node.
1288 HandleSDNode Handle(N);
1290 // Test if the LHS of the sub can be folded.
1291 X86ISelAddressMode Backup = AM;
1292 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
1296 // Test if the index field is free for use.
1297 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1303 SDValue RHS = Handle.getValue().getOperand(1);
1304 // If the RHS involves a register with multiple uses, this
1305 // transformation incurs an extra mov, due to the neg instruction
1306 // clobbering its operand.
1307 if (!RHS.getNode()->hasOneUse() ||
1308 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1309 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1310 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1311 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1312 RHS.getOperand(0).getValueType() == MVT::i32))
1314 // If the base is a register with multiple uses, this
1315 // transformation may save a mov.
1316 // FIXME: Don't rely on DELETED_NODEs.
1317 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1318 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
1319 !AM.Base_Reg.getNode()->hasOneUse()) ||
1320 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1322 // If the folded LHS was interesting, this transformation saves
1323 // address arithmetic.
1324 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1325 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1326 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1328 // If it doesn't look like it may be an overall win, don't do it.
1334 // Ok, the transformation is legal and appears profitable. Go for it.
1335 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1336 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1340 // Insert the new nodes into the topological ordering.
1341 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1342 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
1347 if (!matchAdd(N, AM, Depth))
1352 // We want to look through a transform in InstCombine and DAGCombiner that
1353 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1354 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1355 // An 'lea' can then be used to match the shift (multiply) and add:
1357 // lea (%rsi, %rdi, 8), %rax
1358 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1359 !matchAdd(N, AM, Depth))
1364 // Perform some heroic transforms on an and of a constant-count shift
1365 // with a constant to enable use of the scaled offset field.
1367 // Scale must not be used already.
1368 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1370 SDValue Shift = N.getOperand(0);
1371 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1372 SDValue X = Shift.getOperand(0);
1374 // We only handle up to 64-bit values here as those are what matter for
1375 // addressing mode optimizations.
1376 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1378 if (!isa<ConstantSDNode>(N.getOperand(1)))
1380 uint64_t Mask = N.getConstantOperandVal(1);
1382 // Try to fold the mask and shift into an extract and scale.
1383 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1386 // Try to fold the mask and shift directly into the scale.
1387 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1390 // Try to swap the mask and shift to place shifts which can be done as
1391 // a scale on the outside of the mask.
1392 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1398 return matchAddressBase(N, AM);
1401 /// Helper for MatchAddress. Add the specified node to the
1402 /// specified addressing mode without any further recursion.
1403 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1404 // Is the base register already occupied?
1405 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1406 // If so, check to see if the scale index register is set.
1407 if (!AM.IndexReg.getNode()) {
1413 // Otherwise, we cannot select it.
1417 // Default, generate it as a register.
1418 AM.BaseType = X86ISelAddressMode::RegBase;
1423 template <class GatherScatterSDNode>
1424 bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1425 GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1426 SDValue &Index, SDValue &Disp, SDValue &Segment) {
1427 X86ISelAddressMode AM;
1428 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1429 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1430 if (AddrSpace == 256)
1431 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1432 if (AddrSpace == 257)
1433 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1434 if (AddrSpace == 258)
1435 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1438 Base = Mgs->getBasePtr();
1439 Index = Mgs->getIndex();
1440 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
1441 Scale = getI8Imm(ScalarSize/8, DL);
1443 // If Base is 0, the whole address is in index and the Scale is 1
1444 if (isa<ConstantSDNode>(Base)) {
1445 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
1446 "Unexpected base in gather/scatter");
1447 Scale = getI8Imm(1, DL);
1448 Base = CurDAG->getRegister(0, MVT::i32);
1450 if (AM.Segment.getNode())
1451 Segment = AM.Segment;
1453 Segment = CurDAG->getRegister(0, MVT::i32);
1454 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1458 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1459 SDValue &Scale, SDValue &Index,
1460 SDValue &Disp, SDValue &Segment) {
1461 if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1462 return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1463 Mgs, N, Base, Scale, Index, Disp, Segment);
1464 if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1465 return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1466 X86Gather, N, Base, Scale, Index, Disp, Segment);
1470 /// Returns true if it is able to pattern match an addressing mode.
1471 /// It returns the operands which make up the maximal addressing mode it can
1472 /// match by reference.
1474 /// Parent is the parent node of the addr operand that is being matched. It
1475 /// is always a load, store, atomic node, or null. It is only null when
1476 /// checking memory operands for inline asm nodes.
1477 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1478 SDValue &Scale, SDValue &Index,
1479 SDValue &Disp, SDValue &Segment) {
1480 X86ISelAddressMode AM;
1483 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1484 // that are not a MemSDNode, and thus don't have proper addrspace info.
1485 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1486 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1487 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1488 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1489 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1490 unsigned AddrSpace =
1491 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1492 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1493 if (AddrSpace == 256)
1494 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1495 if (AddrSpace == 257)
1496 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1497 if (AddrSpace == 258)
1498 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1501 if (matchAddress(N, AM))
1504 MVT VT = N.getSimpleValueType();
1505 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1506 if (!AM.Base_Reg.getNode())
1507 AM.Base_Reg = CurDAG->getRegister(0, VT);
1510 if (!AM.IndexReg.getNode())
1511 AM.IndexReg = CurDAG->getRegister(0, VT);
1513 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1517 /// Match a scalar SSE load. In particular, we want to match a load whose top
1518 /// elements are either undef or zeros. The load flavor is derived from the
1519 /// type of N, which is either v4f32 or v2f64.
1522 /// PatternChainNode: this is the matched node that has a chain input and
1524 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
1525 SDValue N, SDValue &Base,
1526 SDValue &Scale, SDValue &Index,
1527 SDValue &Disp, SDValue &Segment,
1528 SDValue &PatternNodeWithChain) {
1529 // We can allow a full vector load here since narrowing a load is ok.
1530 if (ISD::isNON_EXTLoad(N.getNode())) {
1531 PatternNodeWithChain = N;
1532 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1533 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1534 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1535 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1540 // We can also match the special zero extended load opcode.
1541 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1542 PatternNodeWithChain = N;
1543 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1544 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1545 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1546 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1551 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1552 // once. Otherwise the load might get duplicated and the chain output of the
1553 // duplicate load will not be observed by all dependencies.
1554 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
1555 PatternNodeWithChain = N.getOperand(0);
1556 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1557 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1558 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1559 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1560 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1565 // Also handle the case where we explicitly require zeros in the top
1566 // elements. This is a vector shuffle from the zero vector.
1567 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1568 // Check to see if the top elements are all zeros (or bitcast of zeros).
1569 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1570 N.getOperand(0).getNode()->hasOneUse()) {
1571 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1572 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1573 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1574 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1575 // Okay, this is a zero extending load. Fold it.
1576 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1577 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1586 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
1587 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1588 uint64_t ImmVal = CN->getZExtValue();
1589 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1592 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1596 // In static codegen with small code model, we can get the address of a label
1597 // into a register with 'movl'. TableGen has already made sure we're looking
1598 // at a label of some kind.
1599 assert(N->getOpcode() == X86ISD::Wrapper &&
1600 "Unexpected node type for MOV32ri64");
1601 N = N.getOperand(0);
1603 // At least GNU as does not accept 'movl' for TPOFF relocations.
1604 // FIXME: We could use 'movl' when we know we are targeting MC.
1605 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
1609 if (N->getOpcode() != ISD::TargetGlobalAddress)
1610 return TM.getCodeModel() == CodeModel::Small;
1612 Optional<ConstantRange> CR =
1613 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1615 return TM.getCodeModel() == CodeModel::Small;
1617 return CR->getUnsignedMax().ult(1ull << 32);
1620 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
1621 SDValue &Scale, SDValue &Index,
1622 SDValue &Disp, SDValue &Segment) {
1623 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1626 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1629 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1630 if (RN && RN->getReg() == 0)
1631 Base = CurDAG->getRegister(0, MVT::i64);
1632 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1633 // Base could already be %rip, particularly in the x32 ABI.
1634 Base = SDValue(CurDAG->getMachineNode(
1635 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1636 CurDAG->getTargetConstant(0, DL, MVT::i64),
1638 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1642 RN = dyn_cast<RegisterSDNode>(Index);
1643 if (RN && RN->getReg() == 0)
1644 Index = CurDAG->getRegister(0, MVT::i64);
1646 assert(Index.getValueType() == MVT::i32 &&
1647 "Expect to be extending 32-bit registers for use in LEA");
1648 Index = SDValue(CurDAG->getMachineNode(
1649 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1650 CurDAG->getTargetConstant(0, DL, MVT::i64),
1652 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1660 /// Calls SelectAddr and determines if the maximal addressing
1661 /// mode it matches can be cost effectively emitted as an LEA instruction.
1662 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
1663 SDValue &Base, SDValue &Scale,
1664 SDValue &Index, SDValue &Disp,
1666 X86ISelAddressMode AM;
1668 // Save the DL and VT before calling matchAddress, it can invalidate N.
1670 MVT VT = N.getSimpleValueType();
1672 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1674 SDValue Copy = AM.Segment;
1675 SDValue T = CurDAG->getRegister(0, MVT::i32);
1677 if (matchAddress(N, AM))
1679 assert (T == AM.Segment);
1682 unsigned Complexity = 0;
1683 if (AM.BaseType == X86ISelAddressMode::RegBase)
1684 if (AM.Base_Reg.getNode())
1687 AM.Base_Reg = CurDAG->getRegister(0, VT);
1688 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1691 if (AM.IndexReg.getNode())
1694 AM.IndexReg = CurDAG->getRegister(0, VT);
1696 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1701 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1702 // to a LEA. This is determined with some experimentation but is by no means
1703 // optimal (especially for code size consideration). LEA is nice because of
1704 // its three-address nature. Tweak the cost function again when we can run
1705 // convertToThreeAddress() at register allocation time.
1706 if (AM.hasSymbolicDisplacement()) {
1707 // For X86-64, always use LEA to materialize RIP-relative addresses.
1708 if (Subtarget->is64Bit())
1714 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1717 // If it isn't worth using an LEA, reject it.
1718 if (Complexity <= 2)
1721 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
1725 /// This is only run on TargetGlobalTLSAddress nodes.
1726 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
1727 SDValue &Scale, SDValue &Index,
1728 SDValue &Disp, SDValue &Segment) {
1729 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1730 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1732 X86ISelAddressMode AM;
1733 AM.GV = GA->getGlobal();
1734 AM.Disp += GA->getOffset();
1735 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1736 AM.SymbolFlags = GA->getTargetFlags();
1738 if (N.getValueType() == MVT::i32) {
1740 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1742 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1745 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1749 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1750 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1751 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1756 // Keep track of the original value type and whether this value was
1757 // truncated. If we see a truncation from pointer type to VT that truncates
1758 // bits that are known to be zero, we can use a narrow reference.
1759 EVT VT = N.getValueType();
1760 bool WasTruncated = false;
1761 if (N.getOpcode() == ISD::TRUNCATE) {
1762 WasTruncated = true;
1763 N = N.getOperand(0);
1766 if (N.getOpcode() != X86ISD::Wrapper)
1769 // We can only use non-GlobalValues as immediates if they were not truncated,
1770 // as we do not have any range information. If we have a GlobalValue and the
1771 // address was not truncated, we can select it as an operand directly.
1772 unsigned Opc = N.getOperand(0)->getOpcode();
1773 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1774 Op = N.getOperand(0);
1775 // We can only select the operand directly if we didn't have to look past a
1777 return !WasTruncated;
1780 // Check that the global's range fits into VT.
1781 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1782 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1783 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1786 // Okay, we can use a narrow reference.
1787 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1788 GA->getOffset(), GA->getTargetFlags());
1792 bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
1793 SDValue &Base, SDValue &Scale,
1794 SDValue &Index, SDValue &Disp,
1796 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1797 !IsProfitableToFold(N, P, P) ||
1798 !IsLegalToFold(N, P, P, OptLevel))
1801 return selectAddr(N.getNode(),
1802 N.getOperand(1), Base, Scale, Index, Disp, Segment);
1805 /// Return an SDNode that returns the value of the global base register.
1806 /// Output instructions required to initialize the global base register,
1808 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1809 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1810 auto &DL = MF->getDataLayout();
1811 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1814 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1815 if (N->getOpcode() == ISD::TRUNCATE)
1816 N = N->getOperand(0).getNode();
1817 if (N->getOpcode() != X86ISD::Wrapper)
1820 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1824 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1825 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1826 CR->getSignedMax().slt(1ull << Width);
1829 /// Test whether the given X86ISD::CMP node has any uses which require the SF
1830 /// or OF bits to be accurate.
1831 static bool hasNoSignedComparisonUses(SDNode *N) {
1832 // Examine each user of the node.
1833 for (SDNode::use_iterator UI = N->use_begin(),
1834 UE = N->use_end(); UI != UE; ++UI) {
1835 // Only examine CopyToReg uses.
1836 if (UI->getOpcode() != ISD::CopyToReg)
1838 // Only examine CopyToReg uses that copy to EFLAGS.
1839 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1842 // Examine each user of the CopyToReg use.
1843 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1844 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1845 // Only examine the Flag result.
1846 if (FlagUI.getUse().getResNo() != 1) continue;
1847 // Anything unusual: assume conservatively.
1848 if (!FlagUI->isMachineOpcode()) return false;
1849 // Examine the opcode of the user.
1850 switch (FlagUI->getMachineOpcode()) {
1851 // These comparisons don't treat the most significant bit specially.
1852 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1853 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1854 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1855 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1856 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1857 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1858 case X86::CMOVA16rr: case X86::CMOVA16rm:
1859 case X86::CMOVA32rr: case X86::CMOVA32rm:
1860 case X86::CMOVA64rr: case X86::CMOVA64rm:
1861 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1862 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1863 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1864 case X86::CMOVB16rr: case X86::CMOVB16rm:
1865 case X86::CMOVB32rr: case X86::CMOVB32rm:
1866 case X86::CMOVB64rr: case X86::CMOVB64rm:
1867 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1868 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1869 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1870 case X86::CMOVE16rr: case X86::CMOVE16rm:
1871 case X86::CMOVE32rr: case X86::CMOVE32rm:
1872 case X86::CMOVE64rr: case X86::CMOVE64rm:
1873 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1874 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1875 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1876 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1877 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1878 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1879 case X86::CMOVP16rr: case X86::CMOVP16rm:
1880 case X86::CMOVP32rr: case X86::CMOVP32rm:
1881 case X86::CMOVP64rr: case X86::CMOVP64rm:
1883 // Anything else: assume conservatively.
1884 default: return false;
1891 /// Check whether or not the chain ending in StoreNode is suitable for doing
1892 /// the {load; increment or decrement; store} to modify transformation.
1893 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1894 SDValue StoredVal, SelectionDAG *CurDAG,
1895 LoadSDNode* &LoadNode, SDValue &InputChain) {
1897 // is the value stored the result of a DEC or INC?
1898 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1900 // is the stored value result 0 of the load?
1901 if (StoredVal.getResNo() != 0) return false;
1903 // are there other uses of the loaded value than the inc or dec?
1904 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1906 // is the store non-extending and non-indexed?
1907 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
1910 SDValue Load = StoredVal->getOperand(0);
1911 // Is the stored value a non-extending and non-indexed load?
1912 if (!ISD::isNormalLoad(Load.getNode())) return false;
1914 // Return LoadNode by reference.
1915 LoadNode = cast<LoadSDNode>(Load);
1916 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
1917 EVT LdVT = LoadNode->getMemoryVT();
1918 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
1922 // Is store the only read of the loaded value?
1923 if (!Load.hasOneUse())
1926 // Is the address of the store the same as the load?
1927 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1928 LoadNode->getOffset() != StoreNode->getOffset())
1931 // Check if the chain is produced by the load or is a TokenFactor with
1932 // the load output chain as an operand. Return InputChain by reference.
1933 SDValue Chain = StoreNode->getChain();
1935 bool ChainCheck = false;
1936 if (Chain == Load.getValue(1)) {
1938 InputChain = LoadNode->getChain();
1939 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1940 SmallVector<SDValue, 4> ChainOps;
1941 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1942 SDValue Op = Chain.getOperand(i);
1943 if (Op == Load.getValue(1)) {
1945 // Drop Load, but keep its chain. No cycle check necessary.
1946 ChainOps.push_back(Load.getOperand(0));
1950 // Make sure using Op as part of the chain would not cause a cycle here.
1951 // In theory, we could check whether the chain node is a predecessor of
1952 // the load. But that can be very expensive. Instead visit the uses and
1953 // make sure they all have smaller node id than the load.
1954 int LoadId = LoadNode->getNodeId();
1955 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1956 UE = UI->use_end(); UI != UE; ++UI) {
1957 if (UI.getUse().getResNo() != 0)
1959 if (UI->getNodeId() > LoadId)
1963 ChainOps.push_back(Op);
1967 // Make a new TokenFactor with all the other input chains except
1969 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
1970 MVT::Other, ChainOps);
1978 /// Get the appropriate X86 opcode for an in-memory increment or decrement.
1979 /// Opc should be X86ISD::DEC or X86ISD::INC.
1980 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
1981 if (Opc == X86ISD::DEC) {
1982 if (LdVT == MVT::i64) return X86::DEC64m;
1983 if (LdVT == MVT::i32) return X86::DEC32m;
1984 if (LdVT == MVT::i16) return X86::DEC16m;
1985 if (LdVT == MVT::i8) return X86::DEC8m;
1987 assert(Opc == X86ISD::INC && "unrecognized opcode");
1988 if (LdVT == MVT::i64) return X86::INC64m;
1989 if (LdVT == MVT::i32) return X86::INC32m;
1990 if (LdVT == MVT::i16) return X86::INC16m;
1991 if (LdVT == MVT::i8) return X86::INC8m;
1993 llvm_unreachable("unrecognized size for LdVT");
1996 void X86DAGToDAGISel::Select(SDNode *Node) {
1997 MVT NVT = Node->getSimpleValueType(0);
1999 unsigned Opcode = Node->getOpcode();
2002 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2004 if (Node->isMachineOpcode()) {
2005 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
2006 Node->setNodeId(-1);
2007 return; // Already selected.
2013 if (Subtarget->isTargetNaCl())
2014 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2015 // leave the instruction alone.
2017 if (Subtarget->isTarget64BitILP32()) {
2018 // Converts a 32-bit register to a 64-bit, zero-extended version of
2019 // it. This is needed because x86-64 can do many things, but jmp %r32
2020 // ain't one of them.
2021 const SDValue &Target = Node->getOperand(1);
2022 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2023 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2024 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2025 Node->getOperand(0), ZextTarget);
2026 ReplaceNode(Node, Brind.getNode());
2027 SelectCode(ZextTarget.getNode());
2028 SelectCode(Brind.getNode());
2033 case X86ISD::GlobalBaseReg:
2034 ReplaceNode(Node, getGlobalBaseReg());
2037 case X86ISD::SHRUNKBLEND: {
2038 // SHRUNKBLEND selects like a regular VSELECT.
2039 SDValue VSelect = CurDAG->getNode(
2040 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2041 Node->getOperand(1), Node->getOperand(2));
2042 ReplaceUses(SDValue(Node, 0), VSelect);
2043 SelectCode(VSelect.getNode());
2044 // We already called ReplaceUses.
2051 // For operations of the form (x << C1) op C2, check if we can use a smaller
2052 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2053 SDValue N0 = Node->getOperand(0);
2054 SDValue N1 = Node->getOperand(1);
2056 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2059 // i8 is unshrinkable, i16 should be promoted to i32.
2060 if (NVT != MVT::i32 && NVT != MVT::i64)
2063 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2064 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2065 if (!Cst || !ShlCst)
2068 int64_t Val = Cst->getSExtValue();
2069 uint64_t ShlVal = ShlCst->getZExtValue();
2071 // Make sure that we don't change the operation by removing bits.
2072 // This only matters for OR and XOR, AND is unaffected.
2073 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2074 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2077 unsigned ShlOp, AddOp, Op;
2080 // Check the minimum bitwidth for the new constant.
2081 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2082 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2083 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2084 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2086 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2089 // Bail if there is no smaller encoding.
2093 switch (NVT.SimpleTy) {
2094 default: llvm_unreachable("Unsupported VT!");
2096 assert(CstVT == MVT::i8);
2097 ShlOp = X86::SHL32ri;
2098 AddOp = X86::ADD32rr;
2101 default: llvm_unreachable("Impossible opcode");
2102 case ISD::AND: Op = X86::AND32ri8; break;
2103 case ISD::OR: Op = X86::OR32ri8; break;
2104 case ISD::XOR: Op = X86::XOR32ri8; break;
2108 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2109 ShlOp = X86::SHL64ri;
2110 AddOp = X86::ADD64rr;
2113 default: llvm_unreachable("Impossible opcode");
2114 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2115 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2116 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2121 // Emit the smaller op and the shift.
2122 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2123 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2125 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2128 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2129 getI8Imm(ShlVal, dl));
2133 case X86ISD::SMUL8: {
2134 SDValue N0 = Node->getOperand(0);
2135 SDValue N1 = Node->getOperand(1);
2137 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2139 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2140 N0, SDValue()).getValue(1);
2142 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2143 SDValue Ops[] = {N1, InFlag};
2144 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2146 ReplaceNode(Node, CNode);
2150 case X86ISD::UMUL: {
2151 SDValue N0 = Node->getOperand(0);
2152 SDValue N1 = Node->getOperand(1);
2155 switch (NVT.SimpleTy) {
2156 default: llvm_unreachable("Unsupported VT!");
2157 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2158 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2159 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2160 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2163 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2164 N0, SDValue()).getValue(1);
2166 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2167 SDValue Ops[] = {N1, InFlag};
2168 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2170 ReplaceNode(Node, CNode);
2174 case ISD::SMUL_LOHI:
2175 case ISD::UMUL_LOHI: {
2176 SDValue N0 = Node->getOperand(0);
2177 SDValue N1 = Node->getOperand(1);
2179 bool isSigned = Opcode == ISD::SMUL_LOHI;
2180 bool hasBMI2 = Subtarget->hasBMI2();
2182 switch (NVT.SimpleTy) {
2183 default: llvm_unreachable("Unsupported VT!");
2184 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2185 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2186 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2187 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2188 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2189 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2192 switch (NVT.SimpleTy) {
2193 default: llvm_unreachable("Unsupported VT!");
2194 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2195 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2196 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2197 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2201 unsigned SrcReg, LoReg, HiReg;
2203 default: llvm_unreachable("Unknown MUL opcode!");
2206 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2210 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2214 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2218 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2221 SrcReg = X86::EDX; LoReg = HiReg = 0;
2224 SrcReg = X86::RDX; LoReg = HiReg = 0;
2228 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2229 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2230 // Multiply is commmutative.
2232 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2237 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2238 N0, SDValue()).getValue(1);
2239 SDValue ResHi, ResLo;
2243 MachineSDNode *CNode = nullptr;
2244 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2246 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2247 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2248 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2249 ResHi = SDValue(CNode, 0);
2250 ResLo = SDValue(CNode, 1);
2251 Chain = SDValue(CNode, 2);
2252 InFlag = SDValue(CNode, 3);
2254 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2255 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2256 Chain = SDValue(CNode, 0);
2257 InFlag = SDValue(CNode, 1);
2260 // Update the chain.
2261 ReplaceUses(N1.getValue(1), Chain);
2262 // Record the mem-refs
2263 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2265 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2266 MemOp[0] = LoadNode->getMemOperand();
2267 CNode->setMemRefs(MemOp, MemOp + 1);
2270 SDValue Ops[] = { N1, InFlag };
2271 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2272 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2273 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2274 ResHi = SDValue(CNode, 0);
2275 ResLo = SDValue(CNode, 1);
2276 InFlag = SDValue(CNode, 2);
2278 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2279 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2280 InFlag = SDValue(CNode, 0);
2284 // Prevent use of AH in a REX instruction by referencing AX instead.
2285 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2286 !SDValue(Node, 1).use_empty()) {
2287 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2288 X86::AX, MVT::i16, InFlag);
2289 InFlag = Result.getValue(2);
2290 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2292 if (!SDValue(Node, 0).use_empty())
2293 ReplaceUses(SDValue(Node, 1),
2294 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2296 // Shift AX down 8 bits.
2297 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2299 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2301 // Then truncate it down to i8.
2302 ReplaceUses(SDValue(Node, 1),
2303 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2305 // Copy the low half of the result, if it is needed.
2306 if (!SDValue(Node, 0).use_empty()) {
2307 if (!ResLo.getNode()) {
2308 assert(LoReg && "Register for low half is not defined!");
2309 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2311 InFlag = ResLo.getValue(2);
2313 ReplaceUses(SDValue(Node, 0), ResLo);
2314 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2316 // Copy the high half of the result, if it is needed.
2317 if (!SDValue(Node, 1).use_empty()) {
2318 if (!ResHi.getNode()) {
2319 assert(HiReg && "Register for high half is not defined!");
2320 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2322 InFlag = ResHi.getValue(2);
2324 ReplaceUses(SDValue(Node, 1), ResHi);
2325 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2333 case X86ISD::SDIVREM8_SEXT_HREG:
2334 case X86ISD::UDIVREM8_ZEXT_HREG: {
2335 SDValue N0 = Node->getOperand(0);
2336 SDValue N1 = Node->getOperand(1);
2338 bool isSigned = (Opcode == ISD::SDIVREM ||
2339 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2341 switch (NVT.SimpleTy) {
2342 default: llvm_unreachable("Unsupported VT!");
2343 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2344 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2345 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2346 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2349 switch (NVT.SimpleTy) {
2350 default: llvm_unreachable("Unsupported VT!");
2351 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2352 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2353 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2354 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2358 unsigned LoReg, HiReg, ClrReg;
2359 unsigned SExtOpcode;
2360 switch (NVT.SimpleTy) {
2361 default: llvm_unreachable("Unsupported VT!");
2363 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2364 SExtOpcode = X86::CBW;
2367 LoReg = X86::AX; HiReg = X86::DX;
2369 SExtOpcode = X86::CWD;
2372 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2373 SExtOpcode = X86::CDQ;
2376 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2377 SExtOpcode = X86::CQO;
2381 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2382 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2383 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2386 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2387 // Special case for div8, just use a move with zero extension to AX to
2388 // clear the upper 8 bits (AH).
2389 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2390 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2391 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2393 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2394 MVT::Other, Ops), 0);
2395 Chain = Move.getValue(1);
2396 ReplaceUses(N0.getValue(1), Chain);
2399 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2400 Chain = CurDAG->getEntryNode();
2402 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2403 InFlag = Chain.getValue(1);
2406 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2407 LoReg, N0, SDValue()).getValue(1);
2408 if (isSigned && !signBitIsZero) {
2409 // Sign extend the low part into the high part.
2411 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2413 // Zero out the high part, effectively zero extending the input.
2414 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2415 switch (NVT.SimpleTy) {
2418 SDValue(CurDAG->getMachineNode(
2419 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2420 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2428 SDValue(CurDAG->getMachineNode(
2429 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2430 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2431 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2436 llvm_unreachable("Unexpected division source");
2439 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2440 ClrNode, InFlag).getValue(1);
2445 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2448 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2449 InFlag = SDValue(CNode, 1);
2450 // Update the chain.
2451 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2454 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2457 // Prevent use of AH in a REX instruction by explicitly copying it to
2458 // an ABCD_L register.
2460 // The current assumption of the register allocator is that isel
2461 // won't generate explicit references to the GR8_ABCD_H registers. If
2462 // the allocator and/or the backend get enhanced to be more robust in
2463 // that regard, this can be, and should be, removed.
2464 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2465 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2466 unsigned AHExtOpcode =
2467 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2469 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2470 MVT::Glue, AHCopy, InFlag);
2471 SDValue Result(RNode, 0);
2472 InFlag = SDValue(RNode, 1);
2474 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2475 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2476 if (Node->getValueType(1) == MVT::i64) {
2477 // It's not possible to directly movsx AH to a 64bit register, because
2478 // the latter needs the REX prefix, but the former can't have it.
2479 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2480 "Unexpected i64 sext of h-register");
2482 SDValue(CurDAG->getMachineNode(
2483 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2484 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2485 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2491 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2493 ReplaceUses(SDValue(Node, 1), Result);
2494 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2496 // Copy the division (low) result, if it is needed.
2497 if (!SDValue(Node, 0).use_empty()) {
2498 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2499 LoReg, NVT, InFlag);
2500 InFlag = Result.getValue(2);
2501 ReplaceUses(SDValue(Node, 0), Result);
2502 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2504 // Copy the remainder (high) result, if it is needed.
2505 if (!SDValue(Node, 1).use_empty()) {
2506 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2507 HiReg, NVT, InFlag);
2508 InFlag = Result.getValue(2);
2509 ReplaceUses(SDValue(Node, 1), Result);
2510 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2517 // Sometimes a SUB is used to perform comparison.
2518 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2519 // This node is not a CMP.
2521 SDValue N0 = Node->getOperand(0);
2522 SDValue N1 = Node->getOperand(1);
2524 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2525 hasNoSignedComparisonUses(Node))
2526 N0 = N0.getOperand(0);
2528 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2529 // use a smaller encoding.
2530 // Look past the truncate if CMP is the only use of it.
2531 if ((N0.getNode()->getOpcode() == ISD::AND ||
2532 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2533 N0.getNode()->hasOneUse() &&
2534 N0.getValueType() != MVT::i8 &&
2535 X86::isZeroNode(N1)) {
2536 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2539 // For example, convert "testl %eax, $8" to "testb %al, $8"
2540 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2541 (!(C->getZExtValue() & 0x80) ||
2542 hasNoSignedComparisonUses(Node))) {
2543 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2544 SDValue Reg = N0.getOperand(0);
2546 // On x86-32, only the ABCD registers have 8-bit subregisters.
2547 if (!Subtarget->is64Bit()) {
2548 const TargetRegisterClass *TRC;
2549 switch (N0.getSimpleValueType().SimpleTy) {
2550 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2551 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2552 default: llvm_unreachable("Unsupported TEST operand type!");
2554 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2555 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2556 Reg.getValueType(), Reg, RC), 0);
2559 // Extract the l-register.
2560 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2564 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2566 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2567 // one, do not call ReplaceAllUsesWith.
2568 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2569 SDValue(NewNode, 0));
2573 // For example, "testl %eax, $2048" to "testb %ah, $8".
2574 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2575 (!(C->getZExtValue() & 0x8000) ||
2576 hasNoSignedComparisonUses(Node))) {
2577 // Shift the immediate right by 8 bits.
2578 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2580 SDValue Reg = N0.getOperand(0);
2582 // Put the value in an ABCD register.
2583 const TargetRegisterClass *TRC;
2584 switch (N0.getSimpleValueType().SimpleTy) {
2585 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2586 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2587 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2588 default: llvm_unreachable("Unsupported TEST operand type!");
2590 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2591 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2592 Reg.getValueType(), Reg, RC), 0);
2594 // Extract the h-register.
2595 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2598 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2599 // target GR8_NOREX registers, so make sure the register class is
2601 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2602 MVT::i32, Subreg, ShiftedImm);
2603 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2604 // one, do not call ReplaceAllUsesWith.
2605 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2606 SDValue(NewNode, 0));
2610 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2611 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2612 N0.getValueType() != MVT::i16 &&
2613 (!(C->getZExtValue() & 0x8000) ||
2614 hasNoSignedComparisonUses(Node))) {
2615 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2617 SDValue Reg = N0.getOperand(0);
2619 // Extract the 16-bit subregister.
2620 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2624 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2626 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2627 // one, do not call ReplaceAllUsesWith.
2628 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2629 SDValue(NewNode, 0));
2633 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2634 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2635 N0.getValueType() == MVT::i64 &&
2636 (!(C->getZExtValue() & 0x80000000) ||
2637 hasNoSignedComparisonUses(Node))) {
2638 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2640 SDValue Reg = N0.getOperand(0);
2642 // Extract the 32-bit subregister.
2643 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2647 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2649 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2650 // one, do not call ReplaceAllUsesWith.
2651 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2652 SDValue(NewNode, 0));
2659 // Change a chain of {load; incr or dec; store} of the same value into
2660 // a simple increment or decrement through memory of that value, if the
2661 // uses of the modified value and its address are suitable.
2662 // The DEC64m tablegen pattern is currently not able to match the case where
2663 // the EFLAGS on the original DEC are used. (This also applies to
2664 // {INC,DEC}X{64,32,16,8}.)
2665 // We'll need to improve tablegen to allow flags to be transferred from a
2666 // node in the pattern to the result node. probably with a new keyword
2667 // for example, we have this
2668 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2669 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2670 // (implicit EFLAGS)]>;
2671 // but maybe need something like this
2672 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2673 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2674 // (transferrable EFLAGS)]>;
2676 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2677 SDValue StoredVal = StoreNode->getOperand(1);
2678 unsigned Opc = StoredVal->getOpcode();
2680 LoadSDNode *LoadNode = nullptr;
2682 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2683 LoadNode, InputChain))
2686 SDValue Base, Scale, Index, Disp, Segment;
2687 if (!selectAddr(LoadNode, LoadNode->getBasePtr(),
2688 Base, Scale, Index, Disp, Segment))
2691 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2692 MemOp[0] = StoreNode->getMemOperand();
2693 MemOp[1] = LoadNode->getMemOperand();
2694 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2695 EVT LdVT = LoadNode->getMemoryVT();
2696 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2697 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2699 MVT::i32, MVT::Other, Ops);
2700 Result->setMemRefs(MemOp, MemOp + 2);
2702 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2703 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2704 CurDAG->RemoveDeadNode(Node);
2712 bool X86DAGToDAGISel::
2713 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2714 std::vector<SDValue> &OutOps) {
2715 SDValue Op0, Op1, Op2, Op3, Op4;
2716 switch (ConstraintID) {
2718 llvm_unreachable("Unexpected asm memory constraint");
2719 case InlineAsm::Constraint_i:
2720 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2721 // be an immediate and not a memory constraint.
2723 case InlineAsm::Constraint_o: // offsetable ??
2724 case InlineAsm::Constraint_v: // not offsetable ??
2725 case InlineAsm::Constraint_m: // memory
2726 case InlineAsm::Constraint_X:
2727 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2732 OutOps.push_back(Op0);
2733 OutOps.push_back(Op1);
2734 OutOps.push_back(Op2);
2735 OutOps.push_back(Op3);
2736 OutOps.push_back(Op4);
2740 /// This pass converts a legalized DAG into a X86-specific DAG,
2741 /// ready for instruction scheduling.
2742 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2743 CodeGenOpt::Level OptLevel) {
2744 return new X86DAGToDAGISel(TM, OptLevel);