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/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
40 #define DEBUG_TYPE "x86-isel"
42 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
44 //===----------------------------------------------------------------------===//
45 // Pattern Matcher Implementation
46 //===----------------------------------------------------------------------===//
49 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
50 /// SDValue's instead of register numbers for the leaves of the matched
52 struct X86ISelAddressMode {
58 // This is really a union, discriminated by BaseType!
66 const GlobalValue *GV;
68 const BlockAddress *BlockAddr;
72 unsigned Align; // CP alignment.
73 unsigned char SymbolFlags; // X86II::MO_*
76 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
77 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
78 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
80 bool hasSymbolicDisplacement() const {
81 return GV != nullptr || CP != nullptr || ES != nullptr ||
82 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
85 bool hasBaseOrIndexReg() const {
86 return BaseType == FrameIndexBase ||
87 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
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) {
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 /// Subtarget - 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 /// OptForSize - If true, selector should try to optimize for code size
159 /// instead of performance.
163 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
164 : SelectionDAGISel(tm, OptLevel), OptForSize(false) {}
166 const char *getPassName() const override {
167 return "X86 DAG->DAG Instruction Selection";
170 bool runOnMachineFunction(MachineFunction &MF) override {
171 // Reset the subtarget each time through.
172 Subtarget = &MF.getSubtarget<X86Subtarget>();
173 SelectionDAGISel::runOnMachineFunction(MF);
177 void EmitFunctionEntryCode() override;
179 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
181 void PreprocessISelDAG() override;
183 inline bool immSext8(SDNode *N) const {
184 return isInt<8>(cast<ConstantSDNode>(N)->getSExtValue());
187 // i64immSExt32 predicate - True if the 64-bit immediate fits in a 32-bit
188 // sign extended field.
189 inline bool i64immSExt32(SDNode *N) const {
190 uint64_t v = cast<ConstantSDNode>(N)->getZExtValue();
191 return (int64_t)v == (int32_t)v;
194 // Include the pieces autogenerated from the target description.
195 #include "X86GenDAGISel.inc"
198 SDNode *Select(SDNode *N) override;
199 SDNode *SelectGather(SDNode *N, unsigned Opc);
200 SDNode *SelectAtomicLoadArith(SDNode *Node, MVT NVT);
202 bool FoldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
203 bool MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
204 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
205 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
206 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
208 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
209 bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
210 SDValue &Scale, SDValue &Index, SDValue &Disp,
212 bool SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
213 SDValue &Scale, SDValue &Index, SDValue &Disp,
215 bool SelectMOV64Imm32(SDValue N, SDValue &Imm);
216 bool SelectLEAAddr(SDValue N, SDValue &Base,
217 SDValue &Scale, SDValue &Index, SDValue &Disp,
219 bool SelectLEA64_32Addr(SDValue N, SDValue &Base,
220 SDValue &Scale, SDValue &Index, SDValue &Disp,
222 bool SelectTLSADDRAddr(SDValue N, SDValue &Base,
223 SDValue &Scale, SDValue &Index, SDValue &Disp,
225 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
226 SDValue &Base, SDValue &Scale,
227 SDValue &Index, SDValue &Disp,
229 SDValue &NodeWithChain);
231 bool TryFoldLoad(SDNode *P, SDValue N,
232 SDValue &Base, SDValue &Scale,
233 SDValue &Index, SDValue &Disp,
236 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
237 /// inline asm expressions.
238 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
239 unsigned ConstraintID,
240 std::vector<SDValue> &OutOps) override;
242 void EmitSpecialCodeForMain();
244 inline void getAddressOperands(X86ISelAddressMode &AM, SDLoc DL,
245 SDValue &Base, SDValue &Scale,
246 SDValue &Index, SDValue &Disp,
248 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
249 ? CurDAG->getTargetFrameIndex(AM.Base_FrameIndex,
252 Scale = getI8Imm(AM.Scale, DL);
254 // These are 32-bit even in 64-bit mode since RIP relative offset
257 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
261 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
262 AM.Align, AM.Disp, AM.SymbolFlags);
264 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
265 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
266 } else if (AM.MCSym) {
267 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
268 assert(AM.SymbolFlags == 0 && "oo");
269 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
270 } else if (AM.JT != -1) {
271 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
272 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
273 } else if (AM.BlockAddr)
274 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
277 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
279 if (AM.Segment.getNode())
280 Segment = AM.Segment;
282 Segment = CurDAG->getRegister(0, MVT::i32);
285 /// getI8Imm - Return a target constant with the specified value, of type
287 inline SDValue getI8Imm(unsigned Imm, SDLoc DL) {
288 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
291 /// getI32Imm - Return a target constant with the specified value, of type
293 inline SDValue getI32Imm(unsigned Imm, SDLoc DL) {
294 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
297 /// getGlobalBaseReg - Return an SDNode that returns the value of
298 /// the global base register. Output instructions required to
299 /// initialize the global base register, if necessary.
301 SDNode *getGlobalBaseReg();
303 /// getTargetMachine - Return a reference to the TargetMachine, casted
304 /// to the target-specific type.
305 const X86TargetMachine &getTargetMachine() const {
306 return static_cast<const X86TargetMachine &>(TM);
309 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
310 /// to the target-specific type.
311 const X86InstrInfo *getInstrInfo() const {
312 return Subtarget->getInstrInfo();
315 /// \brief Address-mode matching performs shift-of-and to and-of-shift
316 /// reassociation in order to expose more scaled addressing
318 bool ComplexPatternFuncMutatesDAG() const override {
326 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
327 if (OptLevel == CodeGenOpt::None) return false;
332 if (N.getOpcode() != ISD::LOAD)
335 // If N is a load, do additional profitability checks.
337 switch (U->getOpcode()) {
350 SDValue Op1 = U->getOperand(1);
352 // If the other operand is a 8-bit immediate we should fold the immediate
353 // instead. This reduces code size.
355 // movl 4(%esp), %eax
359 // addl 4(%esp), %eax
360 // The former is 2 bytes shorter. In case where the increment is 1, then
361 // the saving can be 4 bytes (by using incl %eax).
362 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
363 if (Imm->getAPIntValue().isSignedIntN(8))
366 // If the other operand is a TLS address, we should fold it instead.
369 // leal i@NTPOFF(%eax), %eax
371 // movl $i@NTPOFF, %eax
373 // if the block also has an access to a second TLS address this will save
375 // FIXME: This is probably also true for non-TLS addresses.
376 if (Op1.getOpcode() == X86ISD::Wrapper) {
377 SDValue Val = Op1.getOperand(0);
378 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
388 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
389 /// load's chain operand and move load below the call's chain operand.
390 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
391 SDValue Call, SDValue OrigChain) {
392 SmallVector<SDValue, 8> Ops;
393 SDValue Chain = OrigChain.getOperand(0);
394 if (Chain.getNode() == Load.getNode())
395 Ops.push_back(Load.getOperand(0));
397 assert(Chain.getOpcode() == ISD::TokenFactor &&
398 "Unexpected chain operand");
399 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
400 if (Chain.getOperand(i).getNode() == Load.getNode())
401 Ops.push_back(Load.getOperand(0));
403 Ops.push_back(Chain.getOperand(i));
405 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
407 Ops.push_back(NewChain);
409 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
410 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
411 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
412 Load.getOperand(1), Load.getOperand(2));
415 Ops.push_back(SDValue(Load.getNode(), 1));
416 Ops.append(Call->op_begin() + 1, Call->op_end());
417 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
420 /// isCalleeLoad - Return true if call address is a load and it can be
421 /// moved below CALLSEQ_START and the chains leading up to the call.
422 /// Return the CALLSEQ_START by reference as a second output.
423 /// In the case of a tail call, there isn't a callseq node between the call
424 /// chain and the load.
425 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
426 // The transformation is somewhat dangerous if the call's chain was glued to
427 // the call. After MoveBelowOrigChain the load is moved between the call and
428 // the chain, this can create a cycle if the load is not folded. So it is
429 // *really* important that we are sure the load will be folded.
430 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
432 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
435 LD->getAddressingMode() != ISD::UNINDEXED ||
436 LD->getExtensionType() != ISD::NON_EXTLOAD)
439 // Now let's find the callseq_start.
440 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
441 if (!Chain.hasOneUse())
443 Chain = Chain.getOperand(0);
446 if (!Chain.getNumOperands())
448 // Since we are not checking for AA here, conservatively abort if the chain
449 // writes to memory. It's not safe to move the callee (a load) across a store.
450 if (isa<MemSDNode>(Chain.getNode()) &&
451 cast<MemSDNode>(Chain.getNode())->writeMem())
453 if (Chain.getOperand(0).getNode() == Callee.getNode())
455 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
456 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
457 Callee.getValue(1).hasOneUse())
462 void X86DAGToDAGISel::PreprocessISelDAG() {
463 // OptForSize is used in pattern predicates that isel is matching.
464 OptForSize = MF->getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
466 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
467 E = CurDAG->allnodes_end(); I != E; ) {
468 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
470 if (OptLevel != CodeGenOpt::None &&
471 // Only does this when target favors doesn't favor register indirect
473 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
474 (N->getOpcode() == X86ISD::TC_RETURN &&
475 // Only does this if load can be folded into TC_RETURN.
476 (Subtarget->is64Bit() ||
477 getTargetMachine().getRelocationModel() != Reloc::PIC_)))) {
478 /// Also try moving call address load from outside callseq_start to just
479 /// before the call to allow it to be folded.
497 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
498 SDValue Chain = N->getOperand(0);
499 SDValue Load = N->getOperand(1);
500 if (!isCalleeLoad(Load, Chain, HasCallSeq))
502 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
507 // Lower fpround and fpextend nodes that target the FP stack to be store and
508 // load to the stack. This is a gross hack. We would like to simply mark
509 // these as being illegal, but when we do that, legalize produces these when
510 // it expands calls, then expands these in the same legalize pass. We would
511 // like dag combine to be able to hack on these between the call expansion
512 // and the node legalization. As such this pass basically does "really
513 // late" legalization of these inline with the X86 isel pass.
514 // FIXME: This should only happen when not compiled with -O0.
515 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
518 MVT SrcVT = N->getOperand(0).getSimpleValueType();
519 MVT DstVT = N->getSimpleValueType(0);
521 // If any of the sources are vectors, no fp stack involved.
522 if (SrcVT.isVector() || DstVT.isVector())
525 // If the source and destination are SSE registers, then this is a legal
526 // conversion that should not be lowered.
527 const X86TargetLowering *X86Lowering =
528 static_cast<const X86TargetLowering *>(TLI);
529 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
530 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
531 if (SrcIsSSE && DstIsSSE)
534 if (!SrcIsSSE && !DstIsSSE) {
535 // If this is an FPStack extension, it is a noop.
536 if (N->getOpcode() == ISD::FP_EXTEND)
538 // If this is a value-preserving FPStack truncation, it is a noop.
539 if (N->getConstantOperandVal(1))
543 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
544 // FPStack has extload and truncstore. SSE can fold direct loads into other
545 // operations. Based on this, decide what we want to do.
547 if (N->getOpcode() == ISD::FP_ROUND)
548 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
550 MemVT = SrcIsSSE ? SrcVT : DstVT;
552 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
555 // FIXME: optimize the case where the src/dest is a load or store?
556 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
558 MemTmp, MachinePointerInfo(), MemVT,
560 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
561 MachinePointerInfo(),
562 MemVT, false, false, false, 0);
564 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
565 // extload we created. This will cause general havok on the dag because
566 // anything below the conversion could be folded into other existing nodes.
567 // To avoid invalidating 'I', back it up to the convert node.
569 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
571 // Now that we did that, the node is dead. Increment the iterator to the
572 // next node to process, then delete N.
574 CurDAG->DeleteNode(N);
579 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
580 /// the main function.
581 void X86DAGToDAGISel::EmitSpecialCodeForMain() {
582 if (Subtarget->isTargetCygMing()) {
583 TargetLowering::ArgListTy Args;
585 TargetLowering::CallLoweringInfo CLI(*CurDAG);
586 CLI.setChain(CurDAG->getRoot())
587 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
588 CurDAG->getExternalSymbol("__main", TLI->getPointerTy()),
590 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
591 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
592 CurDAG->setRoot(Result.second);
596 void X86DAGToDAGISel::EmitFunctionEntryCode() {
597 // If this is main, emit special code for main.
598 if (const Function *Fn = MF->getFunction())
599 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
600 EmitSpecialCodeForMain();
603 static bool isDispSafeForFrameIndex(int64_t Val) {
604 // On 64-bit platforms, we can run into an issue where a frame index
605 // includes a displacement that, when added to the explicit displacement,
606 // will overflow the displacement field. Assuming that the frame index
607 // displacement fits into a 31-bit integer (which is only slightly more
608 // aggressive than the current fundamental assumption that it fits into
609 // a 32-bit integer), a 31-bit disp should always be safe.
610 return isInt<31>(Val);
613 bool X86DAGToDAGISel::FoldOffsetIntoAddress(uint64_t Offset,
614 X86ISelAddressMode &AM) {
615 // Cannot combine ExternalSymbol displacements with integer offsets.
616 if (Offset != 0 && (AM.ES || AM.MCSym))
618 int64_t Val = AM.Disp + Offset;
619 CodeModel::Model M = TM.getCodeModel();
620 if (Subtarget->is64Bit()) {
621 if (!X86::isOffsetSuitableForCodeModel(Val, M,
622 AM.hasSymbolicDisplacement()))
624 // In addition to the checks required for a register base, check that
625 // we do not try to use an unsafe Disp with a frame index.
626 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
627 !isDispSafeForFrameIndex(Val))
635 bool X86DAGToDAGISel::MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
636 SDValue Address = N->getOperand(1);
638 // load gs:0 -> GS segment register.
639 // load fs:0 -> FS segment register.
641 // This optimization is valid because the GNU TLS model defines that
642 // gs:0 (or fs:0 on X86-64) contains its own address.
643 // For more information see http://people.redhat.com/drepper/tls.pdf
644 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
645 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
646 Subtarget->isTargetLinux())
647 switch (N->getPointerInfo().getAddrSpace()) {
649 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
652 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
659 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
660 /// into an addressing mode. These wrap things that will resolve down into a
661 /// symbol reference. If no match is possible, this returns true, otherwise it
663 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
664 // If the addressing mode already has a symbol as the displacement, we can
665 // never match another symbol.
666 if (AM.hasSymbolicDisplacement())
669 SDValue N0 = N.getOperand(0);
670 CodeModel::Model M = TM.getCodeModel();
672 // Handle X86-64 rip-relative addresses. We check this before checking direct
673 // folding because RIP is preferable to non-RIP accesses.
674 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
675 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
676 // they cannot be folded into immediate fields.
677 // FIXME: This can be improved for kernel and other models?
678 (M == CodeModel::Small || M == CodeModel::Kernel)) {
679 // Base and index reg must be 0 in order to use %rip as base.
680 if (AM.hasBaseOrIndexReg())
682 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
683 X86ISelAddressMode Backup = AM;
684 AM.GV = G->getGlobal();
685 AM.SymbolFlags = G->getTargetFlags();
686 if (FoldOffsetIntoAddress(G->getOffset(), AM)) {
690 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
691 X86ISelAddressMode Backup = AM;
692 AM.CP = CP->getConstVal();
693 AM.Align = CP->getAlignment();
694 AM.SymbolFlags = CP->getTargetFlags();
695 if (FoldOffsetIntoAddress(CP->getOffset(), AM)) {
699 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
700 AM.ES = S->getSymbol();
701 AM.SymbolFlags = S->getTargetFlags();
702 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
703 AM.MCSym = S->getMCSymbol();
704 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
705 AM.JT = J->getIndex();
706 AM.SymbolFlags = J->getTargetFlags();
707 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
708 X86ISelAddressMode Backup = AM;
709 AM.BlockAddr = BA->getBlockAddress();
710 AM.SymbolFlags = BA->getTargetFlags();
711 if (FoldOffsetIntoAddress(BA->getOffset(), AM)) {
716 llvm_unreachable("Unhandled symbol reference node.");
718 if (N.getOpcode() == X86ISD::WrapperRIP)
719 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
723 // Handle the case when globals fit in our immediate field: This is true for
724 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
725 // mode, this only applies to a non-RIP-relative computation.
726 if (!Subtarget->is64Bit() ||
727 M == CodeModel::Small || M == CodeModel::Kernel) {
728 assert(N.getOpcode() != X86ISD::WrapperRIP &&
729 "RIP-relative addressing already handled");
730 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
731 AM.GV = G->getGlobal();
732 AM.Disp += G->getOffset();
733 AM.SymbolFlags = G->getTargetFlags();
734 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
735 AM.CP = CP->getConstVal();
736 AM.Align = CP->getAlignment();
737 AM.Disp += CP->getOffset();
738 AM.SymbolFlags = CP->getTargetFlags();
739 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
740 AM.ES = S->getSymbol();
741 AM.SymbolFlags = S->getTargetFlags();
742 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
743 AM.MCSym = S->getMCSymbol();
744 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
745 AM.JT = J->getIndex();
746 AM.SymbolFlags = J->getTargetFlags();
747 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
748 AM.BlockAddr = BA->getBlockAddress();
749 AM.Disp += BA->getOffset();
750 AM.SymbolFlags = BA->getTargetFlags();
752 llvm_unreachable("Unhandled symbol reference node.");
759 /// MatchAddress - Add the specified node to the specified addressing mode,
760 /// returning true if it cannot be done. This just pattern matches for the
762 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
763 if (MatchAddressRecursively(N, AM, 0))
766 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
767 // a smaller encoding and avoids a scaled-index.
769 AM.BaseType == X86ISelAddressMode::RegBase &&
770 AM.Base_Reg.getNode() == nullptr) {
771 AM.Base_Reg = AM.IndexReg;
775 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
776 // because it has a smaller encoding.
777 // TODO: Which other code models can use this?
778 if (TM.getCodeModel() == CodeModel::Small &&
779 Subtarget->is64Bit() &&
781 AM.BaseType == X86ISelAddressMode::RegBase &&
782 AM.Base_Reg.getNode() == nullptr &&
783 AM.IndexReg.getNode() == nullptr &&
784 AM.SymbolFlags == X86II::MO_NO_FLAG &&
785 AM.hasSymbolicDisplacement())
786 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
791 // Insert a node into the DAG at least before the Pos node's position. This
792 // will reposition the node as needed, and will assign it a node ID that is <=
793 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
794 // IDs! The selection DAG must no longer depend on their uniqueness when this
796 static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
797 if (N.getNode()->getNodeId() == -1 ||
798 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
799 DAG.RepositionNode(Pos.getNode(), N.getNode());
800 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
804 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
805 // safe. This allows us to convert the shift and and into an h-register
806 // extract and a scaled index. Returns false if the simplification is
808 static bool FoldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
810 SDValue Shift, SDValue X,
811 X86ISelAddressMode &AM) {
812 if (Shift.getOpcode() != ISD::SRL ||
813 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
817 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
818 if (ScaleLog <= 0 || ScaleLog >= 4 ||
819 Mask != (0xffu << ScaleLog))
822 MVT VT = N.getSimpleValueType();
824 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
825 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
826 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
827 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
828 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
829 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
831 // Insert the new nodes into the topological ordering. We must do this in
832 // a valid topological ordering as nothing is going to go back and re-sort
833 // these nodes. We continually insert before 'N' in sequence as this is
834 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
835 // hierarchy left to express.
836 InsertDAGNode(DAG, N, Eight);
837 InsertDAGNode(DAG, N, Srl);
838 InsertDAGNode(DAG, N, NewMask);
839 InsertDAGNode(DAG, N, And);
840 InsertDAGNode(DAG, N, ShlCount);
841 InsertDAGNode(DAG, N, Shl);
842 DAG.ReplaceAllUsesWith(N, Shl);
844 AM.Scale = (1 << ScaleLog);
848 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
849 // allows us to fold the shift into this addressing mode. Returns false if the
850 // transform succeeded.
851 static bool FoldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
853 SDValue Shift, SDValue X,
854 X86ISelAddressMode &AM) {
855 if (Shift.getOpcode() != ISD::SHL ||
856 !isa<ConstantSDNode>(Shift.getOperand(1)))
859 // Not likely to be profitable if either the AND or SHIFT node has more
860 // than one use (unless all uses are for address computation). Besides,
861 // isel mechanism requires their node ids to be reused.
862 if (!N.hasOneUse() || !Shift.hasOneUse())
865 // Verify that the shift amount is something we can fold.
866 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
867 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
870 MVT VT = N.getSimpleValueType();
872 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
873 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
874 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
876 // Insert the new nodes into the topological ordering. We must do this in
877 // a valid topological ordering as nothing is going to go back and re-sort
878 // these nodes. We continually insert before 'N' in sequence as this is
879 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
880 // hierarchy left to express.
881 InsertDAGNode(DAG, N, NewMask);
882 InsertDAGNode(DAG, N, NewAnd);
883 InsertDAGNode(DAG, N, NewShift);
884 DAG.ReplaceAllUsesWith(N, NewShift);
886 AM.Scale = 1 << ShiftAmt;
887 AM.IndexReg = NewAnd;
891 // Implement some heroics to detect shifts of masked values where the mask can
892 // be replaced by extending the shift and undoing that in the addressing mode
893 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
894 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
895 // the addressing mode. This results in code such as:
897 // int f(short *y, int *lookup_table) {
899 // return *y + lookup_table[*y >> 11];
903 // movzwl (%rdi), %eax
906 // addl (%rsi,%rcx,4), %eax
909 // movzwl (%rdi), %eax
913 // addl (%rsi,%rcx), %eax
915 // Note that this function assumes the mask is provided as a mask *after* the
916 // value is shifted. The input chain may or may not match that, but computing
917 // such a mask is trivial.
918 static bool FoldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
920 SDValue Shift, SDValue X,
921 X86ISelAddressMode &AM) {
922 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
923 !isa<ConstantSDNode>(Shift.getOperand(1)))
926 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
927 unsigned MaskLZ = countLeadingZeros(Mask);
928 unsigned MaskTZ = countTrailingZeros(Mask);
930 // The amount of shift we're trying to fit into the addressing mode is taken
931 // from the trailing zeros of the mask.
932 unsigned AMShiftAmt = MaskTZ;
934 // There is nothing we can do here unless the mask is removing some bits.
935 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
936 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
938 // We also need to ensure that mask is a continuous run of bits.
939 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
941 // Scale the leading zero count down based on the actual size of the value.
942 // Also scale it down based on the size of the shift.
943 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
945 // The final check is to ensure that any masked out high bits of X are
946 // already known to be zero. Otherwise, the mask has a semantic impact
947 // other than masking out a couple of low bits. Unfortunately, because of
948 // the mask, zero extensions will be removed from operands in some cases.
949 // This code works extra hard to look through extensions because we can
950 // replace them with zero extensions cheaply if necessary.
951 bool ReplacingAnyExtend = false;
952 if (X.getOpcode() == ISD::ANY_EXTEND) {
953 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
954 X.getOperand(0).getSimpleValueType().getSizeInBits();
955 // Assume that we'll replace the any-extend with a zero-extend, and
956 // narrow the search to the extended value.
958 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
959 ReplacingAnyExtend = true;
961 APInt MaskedHighBits =
962 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
963 APInt KnownZero, KnownOne;
964 DAG.computeKnownBits(X, KnownZero, KnownOne);
965 if (MaskedHighBits != KnownZero) return true;
967 // We've identified a pattern that can be transformed into a single shift
968 // and an addressing mode. Make it so.
969 MVT VT = N.getSimpleValueType();
970 if (ReplacingAnyExtend) {
971 assert(X.getValueType() != VT);
972 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
973 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
974 InsertDAGNode(DAG, N, NewX);
978 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
979 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
980 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
981 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
983 // Insert the new nodes into the topological ordering. We must do this in
984 // a valid topological ordering as nothing is going to go back and re-sort
985 // these nodes. We continually insert before 'N' in sequence as this is
986 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
987 // hierarchy left to express.
988 InsertDAGNode(DAG, N, NewSRLAmt);
989 InsertDAGNode(DAG, N, NewSRL);
990 InsertDAGNode(DAG, N, NewSHLAmt);
991 InsertDAGNode(DAG, N, NewSHL);
992 DAG.ReplaceAllUsesWith(N, NewSHL);
994 AM.Scale = 1 << AMShiftAmt;
995 AM.IndexReg = NewSRL;
999 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1003 dbgs() << "MatchAddress: ";
1008 return MatchAddressBase(N, AM);
1010 // If this is already a %rip relative address, we can only merge immediates
1011 // into it. Instead of handling this in every case, we handle it here.
1012 // RIP relative addressing: %rip + 32-bit displacement!
1013 if (AM.isRIPRelative()) {
1014 // FIXME: JumpTable and ExternalSymbol address currently don't like
1015 // displacements. It isn't very important, but this should be fixed for
1017 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1020 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1021 if (!FoldOffsetIntoAddress(Cst->getSExtValue(), AM))
1026 switch (N.getOpcode()) {
1028 case ISD::FRAME_ALLOC_RECOVER: {
1029 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1030 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1031 // Use the symbol and don't prefix it.
1032 AM.MCSym = ESNode->getMCSymbol();
1037 case ISD::Constant: {
1038 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1039 if (!FoldOffsetIntoAddress(Val, AM))
1044 case X86ISD::Wrapper:
1045 case X86ISD::WrapperRIP:
1046 if (!MatchWrapper(N, AM))
1051 if (!MatchLoadInAddress(cast<LoadSDNode>(N), AM))
1055 case ISD::FrameIndex:
1056 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1057 AM.Base_Reg.getNode() == nullptr &&
1058 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1059 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1060 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1066 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1070 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
1071 unsigned Val = CN->getZExtValue();
1072 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1073 // that the base operand remains free for further matching. If
1074 // the base doesn't end up getting used, a post-processing step
1075 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1076 if (Val == 1 || Val == 2 || Val == 3) {
1077 AM.Scale = 1 << Val;
1078 SDValue ShVal = N.getNode()->getOperand(0);
1080 // Okay, we know that we have a scale by now. However, if the scaled
1081 // value is an add of something and a constant, we can fold the
1082 // constant into the disp field here.
1083 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1084 AM.IndexReg = ShVal.getNode()->getOperand(0);
1085 ConstantSDNode *AddVal =
1086 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
1087 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1088 if (!FoldOffsetIntoAddress(Disp, AM))
1092 AM.IndexReg = ShVal;
1099 // Scale must not be used already.
1100 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1102 SDValue And = N.getOperand(0);
1103 if (And.getOpcode() != ISD::AND) break;
1104 SDValue X = And.getOperand(0);
1106 // We only handle up to 64-bit values here as those are what matter for
1107 // addressing mode optimizations.
1108 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1110 // The mask used for the transform is expected to be post-shift, but we
1111 // found the shift first so just apply the shift to the mask before passing
1113 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1114 !isa<ConstantSDNode>(And.getOperand(1)))
1116 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1118 // Try to fold the mask and shift into the scale, and return false if we
1120 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1125 case ISD::SMUL_LOHI:
1126 case ISD::UMUL_LOHI:
1127 // A mul_lohi where we need the low part can be folded as a plain multiply.
1128 if (N.getResNo() != 0) break;
1131 case X86ISD::MUL_IMM:
1132 // X*[3,5,9] -> X+X*[2,4,8]
1133 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1134 AM.Base_Reg.getNode() == nullptr &&
1135 AM.IndexReg.getNode() == nullptr) {
1137 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
1138 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1139 CN->getZExtValue() == 9) {
1140 AM.Scale = unsigned(CN->getZExtValue())-1;
1142 SDValue MulVal = N.getNode()->getOperand(0);
1145 // Okay, we know that we have a scale by now. However, if the scaled
1146 // value is an add of something and a constant, we can fold the
1147 // constant into the disp field here.
1148 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1149 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1150 Reg = MulVal.getNode()->getOperand(0);
1151 ConstantSDNode *AddVal =
1152 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
1153 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1154 if (FoldOffsetIntoAddress(Disp, AM))
1155 Reg = N.getNode()->getOperand(0);
1157 Reg = N.getNode()->getOperand(0);
1160 AM.IndexReg = AM.Base_Reg = Reg;
1167 // Given A-B, if A can be completely folded into the address and
1168 // the index field with the index field unused, use -B as the index.
1169 // This is a win if a has multiple parts that can be folded into
1170 // the address. Also, this saves a mov if the base register has
1171 // other uses, since it avoids a two-address sub instruction, however
1172 // it costs an additional mov if the index register has other uses.
1174 // Add an artificial use to this node so that we can keep track of
1175 // it if it gets CSE'd with a different node.
1176 HandleSDNode Handle(N);
1178 // Test if the LHS of the sub can be folded.
1179 X86ISelAddressMode Backup = AM;
1180 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1184 // Test if the index field is free for use.
1185 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1191 SDValue RHS = Handle.getValue().getNode()->getOperand(1);
1192 // If the RHS involves a register with multiple uses, this
1193 // transformation incurs an extra mov, due to the neg instruction
1194 // clobbering its operand.
1195 if (!RHS.getNode()->hasOneUse() ||
1196 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1197 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1198 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1199 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1200 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1202 // If the base is a register with multiple uses, this
1203 // transformation may save a mov.
1204 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1205 AM.Base_Reg.getNode() &&
1206 !AM.Base_Reg.getNode()->hasOneUse()) ||
1207 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1209 // If the folded LHS was interesting, this transformation saves
1210 // address arithmetic.
1211 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1212 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1213 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1215 // If it doesn't look like it may be an overall win, don't do it.
1221 // Ok, the transformation is legal and appears profitable. Go for it.
1222 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1223 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1227 // Insert the new nodes into the topological ordering.
1228 InsertDAGNode(*CurDAG, N, Zero);
1229 InsertDAGNode(*CurDAG, N, Neg);
1234 // Add an artificial use to this node so that we can keep track of
1235 // it if it gets CSE'd with a different node.
1236 HandleSDNode Handle(N);
1238 X86ISelAddressMode Backup = AM;
1239 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1240 !MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1244 // Try again after commuting the operands.
1245 if (!MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)&&
1246 !MatchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1250 // If we couldn't fold both operands into the address at the same time,
1251 // see if we can just put each operand into a register and fold at least
1253 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1254 !AM.Base_Reg.getNode() &&
1255 !AM.IndexReg.getNode()) {
1256 N = Handle.getValue();
1257 AM.Base_Reg = N.getOperand(0);
1258 AM.IndexReg = N.getOperand(1);
1262 N = Handle.getValue();
1267 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1268 if (CurDAG->isBaseWithConstantOffset(N)) {
1269 X86ISelAddressMode Backup = AM;
1270 ConstantSDNode *CN = cast<ConstantSDNode>(N.getOperand(1));
1272 // Start with the LHS as an addr mode.
1273 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1274 !FoldOffsetIntoAddress(CN->getSExtValue(), AM))
1281 // Perform some heroic transforms on an and of a constant-count shift
1282 // with a constant to enable use of the scaled offset field.
1284 // Scale must not be used already.
1285 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1287 SDValue Shift = N.getOperand(0);
1288 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1289 SDValue X = Shift.getOperand(0);
1291 // We only handle up to 64-bit values here as those are what matter for
1292 // addressing mode optimizations.
1293 if (X.getSimpleValueType().getSizeInBits() > 64) break;
1295 if (!isa<ConstantSDNode>(N.getOperand(1)))
1297 uint64_t Mask = N.getConstantOperandVal(1);
1299 // Try to fold the mask and shift into an extract and scale.
1300 if (!FoldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1303 // Try to fold the mask and shift directly into the scale.
1304 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1307 // Try to swap the mask and shift to place shifts which can be done as
1308 // a scale on the outside of the mask.
1309 if (!FoldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1315 return MatchAddressBase(N, AM);
1318 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1319 /// specified addressing mode without any further recursion.
1320 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1321 // Is the base register already occupied?
1322 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1323 // If so, check to see if the scale index register is set.
1324 if (!AM.IndexReg.getNode()) {
1330 // Otherwise, we cannot select it.
1334 // Default, generate it as a register.
1335 AM.BaseType = X86ISelAddressMode::RegBase;
1340 bool X86DAGToDAGISel::SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1341 SDValue &Scale, SDValue &Index,
1342 SDValue &Disp, SDValue &Segment) {
1344 MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1347 X86ISelAddressMode AM;
1348 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1349 // AddrSpace 256 -> GS, 257 -> FS.
1350 if (AddrSpace == 256)
1351 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1352 if (AddrSpace == 257)
1353 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1356 Base = Mgs->getBasePtr();
1357 Index = Mgs->getIndex();
1358 unsigned ScalarSize = Mgs->getValue().getValueType().getScalarSizeInBits();
1359 Scale = getI8Imm(ScalarSize/8, DL);
1361 // If Base is 0, the whole address is in index and the Scale is 1
1362 if (isa<ConstantSDNode>(Base)) {
1363 assert(dyn_cast<ConstantSDNode>(Base)->isNullValue() &&
1364 "Unexpected base in gather/scatter");
1365 Scale = getI8Imm(1, DL);
1366 Base = CurDAG->getRegister(0, MVT::i32);
1368 if (AM.Segment.getNode())
1369 Segment = AM.Segment;
1371 Segment = CurDAG->getRegister(0, MVT::i32);
1372 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1376 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1377 /// It returns the operands which make up the maximal addressing mode it can
1378 /// match by reference.
1380 /// Parent is the parent node of the addr operand that is being matched. It
1381 /// is always a load, store, atomic node, or null. It is only null when
1382 /// checking memory operands for inline asm nodes.
1383 bool X86DAGToDAGISel::SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1384 SDValue &Scale, SDValue &Index,
1385 SDValue &Disp, SDValue &Segment) {
1386 X86ISelAddressMode AM;
1389 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1390 // that are not a MemSDNode, and thus don't have proper addrspace info.
1391 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1392 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1393 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1394 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1395 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1396 unsigned AddrSpace =
1397 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1398 // AddrSpace 256 -> GS, 257 -> FS.
1399 if (AddrSpace == 256)
1400 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1401 if (AddrSpace == 257)
1402 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1405 if (MatchAddress(N, AM))
1408 MVT VT = N.getSimpleValueType();
1409 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1410 if (!AM.Base_Reg.getNode())
1411 AM.Base_Reg = CurDAG->getRegister(0, VT);
1414 if (!AM.IndexReg.getNode())
1415 AM.IndexReg = CurDAG->getRegister(0, VT);
1417 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1421 /// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1422 /// match a load whose top elements are either undef or zeros. The load flavor
1423 /// is derived from the type of N, which is either v4f32 or v2f64.
1426 /// PatternChainNode: this is the matched node that has a chain input and
1428 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1429 SDValue N, SDValue &Base,
1430 SDValue &Scale, SDValue &Index,
1431 SDValue &Disp, SDValue &Segment,
1432 SDValue &PatternNodeWithChain) {
1433 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1434 PatternNodeWithChain = N.getOperand(0);
1435 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1436 PatternNodeWithChain.hasOneUse() &&
1437 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1438 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1439 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1440 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1446 // Also handle the case where we explicitly require zeros in the top
1447 // elements. This is a vector shuffle from the zero vector.
1448 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1449 // Check to see if the top elements are all zeros (or bitcast of zeros).
1450 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1451 N.getOperand(0).getNode()->hasOneUse() &&
1452 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1453 N.getOperand(0).getOperand(0).hasOneUse() &&
1454 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1455 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1456 // Okay, this is a zero extending load. Fold it.
1457 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1458 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1460 PatternNodeWithChain = SDValue(LD, 0);
1467 bool X86DAGToDAGISel::SelectMOV64Imm32(SDValue N, SDValue &Imm) {
1468 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1469 uint64_t ImmVal = CN->getZExtValue();
1470 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1473 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1477 // In static codegen with small code model, we can get the address of a label
1478 // into a register with 'movl'. TableGen has already made sure we're looking
1479 // at a label of some kind.
1480 assert(N->getOpcode() == X86ISD::Wrapper &&
1481 "Unexpected node type for MOV32ri64");
1482 N = N.getOperand(0);
1484 if (N->getOpcode() != ISD::TargetConstantPool &&
1485 N->getOpcode() != ISD::TargetJumpTable &&
1486 N->getOpcode() != ISD::TargetGlobalAddress &&
1487 N->getOpcode() != ISD::TargetExternalSymbol &&
1488 N->getOpcode() != ISD::MCSymbol &&
1489 N->getOpcode() != ISD::TargetBlockAddress)
1493 return TM.getCodeModel() == CodeModel::Small;
1496 bool X86DAGToDAGISel::SelectLEA64_32Addr(SDValue N, SDValue &Base,
1497 SDValue &Scale, SDValue &Index,
1498 SDValue &Disp, SDValue &Segment) {
1499 if (!SelectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1503 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1504 if (RN && RN->getReg() == 0)
1505 Base = CurDAG->getRegister(0, MVT::i64);
1506 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1507 // Base could already be %rip, particularly in the x32 ABI.
1508 Base = SDValue(CurDAG->getMachineNode(
1509 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1510 CurDAG->getTargetConstant(0, DL, MVT::i64),
1512 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1516 RN = dyn_cast<RegisterSDNode>(Index);
1517 if (RN && RN->getReg() == 0)
1518 Index = CurDAG->getRegister(0, MVT::i64);
1520 assert(Index.getValueType() == MVT::i32 &&
1521 "Expect to be extending 32-bit registers for use in LEA");
1522 Index = SDValue(CurDAG->getMachineNode(
1523 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1524 CurDAG->getTargetConstant(0, DL, MVT::i64),
1526 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1534 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1535 /// mode it matches can be cost effectively emitted as an LEA instruction.
1536 bool X86DAGToDAGISel::SelectLEAAddr(SDValue N,
1537 SDValue &Base, SDValue &Scale,
1538 SDValue &Index, SDValue &Disp,
1540 X86ISelAddressMode AM;
1542 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1544 SDValue Copy = AM.Segment;
1545 SDValue T = CurDAG->getRegister(0, MVT::i32);
1547 if (MatchAddress(N, AM))
1549 assert (T == AM.Segment);
1552 MVT VT = N.getSimpleValueType();
1553 unsigned Complexity = 0;
1554 if (AM.BaseType == X86ISelAddressMode::RegBase)
1555 if (AM.Base_Reg.getNode())
1558 AM.Base_Reg = CurDAG->getRegister(0, VT);
1559 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1562 if (AM.IndexReg.getNode())
1565 AM.IndexReg = CurDAG->getRegister(0, VT);
1567 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1572 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1573 // to a LEA. This is determined with some expermentation but is by no means
1574 // optimal (especially for code size consideration). LEA is nice because of
1575 // its three-address nature. Tweak the cost function again when we can run
1576 // convertToThreeAddress() at register allocation time.
1577 if (AM.hasSymbolicDisplacement()) {
1578 // For X86-64, we should always use lea to materialize RIP relative
1580 if (Subtarget->is64Bit())
1586 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1589 // If it isn't worth using an LEA, reject it.
1590 if (Complexity <= 2)
1593 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1597 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1598 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue N, SDValue &Base,
1599 SDValue &Scale, SDValue &Index,
1600 SDValue &Disp, SDValue &Segment) {
1601 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1602 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1604 X86ISelAddressMode AM;
1605 AM.GV = GA->getGlobal();
1606 AM.Disp += GA->getOffset();
1607 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1608 AM.SymbolFlags = GA->getTargetFlags();
1610 if (N.getValueType() == MVT::i32) {
1612 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1614 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1617 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1622 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1623 SDValue &Base, SDValue &Scale,
1624 SDValue &Index, SDValue &Disp,
1626 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1627 !IsProfitableToFold(N, P, P) ||
1628 !IsLegalToFold(N, P, P, OptLevel))
1631 return SelectAddr(N.getNode(),
1632 N.getOperand(1), Base, Scale, Index, Disp, Segment);
1635 /// getGlobalBaseReg - Return an SDNode that returns the value of
1636 /// the global base register. Output instructions required to
1637 /// initialize the global base register, if necessary.
1639 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1640 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1641 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy()).getNode();
1644 /// Atomic opcode table
1672 static const uint16_t AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] = {
1683 X86::LOCK_ADD64mi32,
1696 X86::LOCK_SUB64mi32,
1748 X86::LOCK_AND64mi32,
1761 X86::LOCK_XOR64mi32,
1766 // Return the target constant operand for atomic-load-op and do simple
1767 // translations, such as from atomic-load-add to lock-sub. The return value is
1768 // one of the following 3 cases:
1769 // + target-constant, the operand could be supported as a target constant.
1770 // + empty, the operand is not needed any more with the new op selected.
1771 // + non-empty, otherwise.
1772 static SDValue getAtomicLoadArithTargetConstant(SelectionDAG *CurDAG,
1774 enum AtomicOpc &Op, MVT NVT,
1776 const X86Subtarget *Subtarget) {
1777 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val)) {
1778 int64_t CNVal = CN->getSExtValue();
1779 // Quit if not 32-bit imm.
1780 if ((int32_t)CNVal != CNVal)
1782 // Quit if INT32_MIN: it would be negated as it is negative and overflow,
1783 // producing an immediate that does not fit in the 32 bits available for
1784 // an immediate operand to sub. However, it still fits in 32 bits for the
1785 // add (since it is not negated) so we can return target-constant.
1786 if (CNVal == INT32_MIN)
1787 return CurDAG->getTargetConstant(CNVal, dl, NVT);
1788 // For atomic-load-add, we could do some optimizations.
1790 // Translate to INC/DEC if ADD by 1 or -1.
1791 if (((CNVal == 1) || (CNVal == -1)) && !Subtarget->slowIncDec()) {
1792 Op = (CNVal == 1) ? INC : DEC;
1793 // No more constant operand after being translated into INC/DEC.
1796 // Translate to SUB if ADD by negative value.
1802 return CurDAG->getTargetConstant(CNVal, dl, NVT);
1805 // If the value operand is single-used, try to optimize it.
1806 if (Op == ADD && Val.hasOneUse()) {
1807 // Translate (atomic-load-add ptr (sub 0 x)) back to (lock-sub x).
1808 if (Val.getOpcode() == ISD::SUB && X86::isZeroNode(Val.getOperand(0))) {
1810 return Val.getOperand(1);
1812 // A special case for i16, which needs truncating as, in most cases, it's
1813 // promoted to i32. We will translate
1814 // (atomic-load-add (truncate (sub 0 x))) to (lock-sub (EXTRACT_SUBREG x))
1815 if (Val.getOpcode() == ISD::TRUNCATE && NVT == MVT::i16 &&
1816 Val.getOperand(0).getOpcode() == ISD::SUB &&
1817 X86::isZeroNode(Val.getOperand(0).getOperand(0))) {
1819 Val = Val.getOperand(0);
1820 return CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl, NVT,
1828 SDNode *X86DAGToDAGISel::SelectAtomicLoadArith(SDNode *Node, MVT NVT) {
1829 if (Node->hasAnyUseOfValue(0))
1834 // Optimize common patterns for __sync_or_and_fetch and similar arith
1835 // operations where the result is not used. This allows us to use the "lock"
1836 // version of the arithmetic instruction.
1837 SDValue Chain = Node->getOperand(0);
1838 SDValue Ptr = Node->getOperand(1);
1839 SDValue Val = Node->getOperand(2);
1840 SDValue Base, Scale, Index, Disp, Segment;
1841 if (!SelectAddr(Node, Ptr, Base, Scale, Index, Disp, Segment))
1844 // Which index into the table.
1846 switch (Node->getOpcode()) {
1849 case ISD::ATOMIC_LOAD_OR:
1852 case ISD::ATOMIC_LOAD_AND:
1855 case ISD::ATOMIC_LOAD_XOR:
1858 case ISD::ATOMIC_LOAD_ADD:
1863 Val = getAtomicLoadArithTargetConstant(CurDAG, dl, Op, NVT, Val, Subtarget);
1864 bool isUnOp = !Val.getNode();
1865 bool isCN = Val.getNode() && (Val.getOpcode() == ISD::TargetConstant);
1868 switch (NVT.SimpleTy) {
1869 default: return nullptr;
1872 Opc = AtomicOpcTbl[Op][ConstantI8];
1874 Opc = AtomicOpcTbl[Op][I8];
1878 if (immSext8(Val.getNode()))
1879 Opc = AtomicOpcTbl[Op][SextConstantI16];
1881 Opc = AtomicOpcTbl[Op][ConstantI16];
1883 Opc = AtomicOpcTbl[Op][I16];
1887 if (immSext8(Val.getNode()))
1888 Opc = AtomicOpcTbl[Op][SextConstantI32];
1890 Opc = AtomicOpcTbl[Op][ConstantI32];
1892 Opc = AtomicOpcTbl[Op][I32];
1896 if (immSext8(Val.getNode()))
1897 Opc = AtomicOpcTbl[Op][SextConstantI64];
1898 else if (i64immSExt32(Val.getNode()))
1899 Opc = AtomicOpcTbl[Op][ConstantI64];
1901 llvm_unreachable("True 64 bits constant in SelectAtomicLoadArith");
1903 Opc = AtomicOpcTbl[Op][I64];
1907 assert(Opc != 0 && "Invalid arith lock transform!");
1909 // Building the new node.
1912 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Chain };
1913 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1915 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Val, Chain };
1916 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1919 // Copying the MachineMemOperand.
1920 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1921 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1922 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1924 // We need to have two outputs as that is what the original instruction had.
1925 // So we add a dummy, undefined output. This is safe as we checked first
1926 // that no-one uses our output anyway.
1927 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1929 SDValue RetVals[] = { Undef, Ret };
1930 return CurDAG->getMergeValues(RetVals, dl).getNode();
1933 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1934 /// any uses which require the SF or OF bits to be accurate.
1935 static bool HasNoSignedComparisonUses(SDNode *N) {
1936 // Examine each user of the node.
1937 for (SDNode::use_iterator UI = N->use_begin(),
1938 UE = N->use_end(); UI != UE; ++UI) {
1939 // Only examine CopyToReg uses.
1940 if (UI->getOpcode() != ISD::CopyToReg)
1942 // Only examine CopyToReg uses that copy to EFLAGS.
1943 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1946 // Examine each user of the CopyToReg use.
1947 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1948 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1949 // Only examine the Flag result.
1950 if (FlagUI.getUse().getResNo() != 1) continue;
1951 // Anything unusual: assume conservatively.
1952 if (!FlagUI->isMachineOpcode()) return false;
1953 // Examine the opcode of the user.
1954 switch (FlagUI->getMachineOpcode()) {
1955 // These comparisons don't treat the most significant bit specially.
1956 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1957 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1958 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1959 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1960 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1961 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1962 case X86::CMOVA16rr: case X86::CMOVA16rm:
1963 case X86::CMOVA32rr: case X86::CMOVA32rm:
1964 case X86::CMOVA64rr: case X86::CMOVA64rm:
1965 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1966 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1967 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1968 case X86::CMOVB16rr: case X86::CMOVB16rm:
1969 case X86::CMOVB32rr: case X86::CMOVB32rm:
1970 case X86::CMOVB64rr: case X86::CMOVB64rm:
1971 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1972 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1973 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1974 case X86::CMOVE16rr: case X86::CMOVE16rm:
1975 case X86::CMOVE32rr: case X86::CMOVE32rm:
1976 case X86::CMOVE64rr: case X86::CMOVE64rm:
1977 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1978 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1979 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1980 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1981 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1982 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1983 case X86::CMOVP16rr: case X86::CMOVP16rm:
1984 case X86::CMOVP32rr: case X86::CMOVP32rm:
1985 case X86::CMOVP64rr: case X86::CMOVP64rm:
1987 // Anything else: assume conservatively.
1988 default: return false;
1995 /// isLoadIncOrDecStore - Check whether or not the chain ending in StoreNode
1996 /// is suitable for doing the {load; increment or decrement; store} to modify
1998 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1999 SDValue StoredVal, SelectionDAG *CurDAG,
2000 LoadSDNode* &LoadNode, SDValue &InputChain) {
2002 // is the value stored the result of a DEC or INC?
2003 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
2005 // is the stored value result 0 of the load?
2006 if (StoredVal.getResNo() != 0) return false;
2008 // are there other uses of the loaded value than the inc or dec?
2009 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2011 // is the store non-extending and non-indexed?
2012 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2015 SDValue Load = StoredVal->getOperand(0);
2016 // Is the stored value a non-extending and non-indexed load?
2017 if (!ISD::isNormalLoad(Load.getNode())) return false;
2019 // Return LoadNode by reference.
2020 LoadNode = cast<LoadSDNode>(Load);
2021 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
2022 EVT LdVT = LoadNode->getMemoryVT();
2023 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
2027 // Is store the only read of the loaded value?
2028 if (!Load.hasOneUse())
2031 // Is the address of the store the same as the load?
2032 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2033 LoadNode->getOffset() != StoreNode->getOffset())
2036 // Check if the chain is produced by the load or is a TokenFactor with
2037 // the load output chain as an operand. Return InputChain by reference.
2038 SDValue Chain = StoreNode->getChain();
2040 bool ChainCheck = false;
2041 if (Chain == Load.getValue(1)) {
2043 InputChain = LoadNode->getChain();
2044 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2045 SmallVector<SDValue, 4> ChainOps;
2046 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2047 SDValue Op = Chain.getOperand(i);
2048 if (Op == Load.getValue(1)) {
2053 // Make sure using Op as part of the chain would not cause a cycle here.
2054 // In theory, we could check whether the chain node is a predecessor of
2055 // the load. But that can be very expensive. Instead visit the uses and
2056 // make sure they all have smaller node id than the load.
2057 int LoadId = LoadNode->getNodeId();
2058 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2059 UE = UI->use_end(); UI != UE; ++UI) {
2060 if (UI.getUse().getResNo() != 0)
2062 if (UI->getNodeId() > LoadId)
2066 ChainOps.push_back(Op);
2070 // Make a new TokenFactor with all the other input chains except
2072 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
2073 MVT::Other, ChainOps);
2081 /// getFusedLdStOpcode - Get the appropriate X86 opcode for an in memory
2082 /// increment or decrement. Opc should be X86ISD::DEC or X86ISD::INC.
2083 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
2084 if (Opc == X86ISD::DEC) {
2085 if (LdVT == MVT::i64) return X86::DEC64m;
2086 if (LdVT == MVT::i32) return X86::DEC32m;
2087 if (LdVT == MVT::i16) return X86::DEC16m;
2088 if (LdVT == MVT::i8) return X86::DEC8m;
2090 assert(Opc == X86ISD::INC && "unrecognized opcode");
2091 if (LdVT == MVT::i64) return X86::INC64m;
2092 if (LdVT == MVT::i32) return X86::INC32m;
2093 if (LdVT == MVT::i16) return X86::INC16m;
2094 if (LdVT == MVT::i8) return X86::INC8m;
2096 llvm_unreachable("unrecognized size for LdVT");
2099 /// SelectGather - Customized ISel for GATHER operations.
2101 SDNode *X86DAGToDAGISel::SelectGather(SDNode *Node, unsigned Opc) {
2102 // Operands of Gather: VSrc, Base, VIdx, VMask, Scale
2103 SDValue Chain = Node->getOperand(0);
2104 SDValue VSrc = Node->getOperand(2);
2105 SDValue Base = Node->getOperand(3);
2106 SDValue VIdx = Node->getOperand(4);
2107 SDValue VMask = Node->getOperand(5);
2108 ConstantSDNode *Scale = dyn_cast<ConstantSDNode>(Node->getOperand(6));
2112 SDVTList VTs = CurDAG->getVTList(VSrc.getValueType(), VSrc.getValueType(),
2117 // Memory Operands: Base, Scale, Index, Disp, Segment
2118 SDValue Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
2119 SDValue Segment = CurDAG->getRegister(0, MVT::i32);
2120 const SDValue Ops[] = { VSrc, Base, getI8Imm(Scale->getSExtValue(), DL), VIdx,
2121 Disp, Segment, VMask, Chain};
2122 SDNode *ResNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
2123 // Node has 2 outputs: VDst and MVT::Other.
2124 // ResNode has 3 outputs: VDst, VMask_wb, and MVT::Other.
2125 // We replace VDst of Node with VDst of ResNode, and Other of Node with Other
2127 ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
2128 ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 2));
2132 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
2133 MVT NVT = Node->getSimpleValueType(0);
2135 unsigned Opcode = Node->getOpcode();
2138 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2140 if (Node->isMachineOpcode()) {
2141 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
2142 Node->setNodeId(-1);
2143 return nullptr; // Already selected.
2148 case ISD::INTRINSIC_W_CHAIN: {
2149 unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2152 case Intrinsic::x86_avx2_gather_d_pd:
2153 case Intrinsic::x86_avx2_gather_d_pd_256:
2154 case Intrinsic::x86_avx2_gather_q_pd:
2155 case Intrinsic::x86_avx2_gather_q_pd_256:
2156 case Intrinsic::x86_avx2_gather_d_ps:
2157 case Intrinsic::x86_avx2_gather_d_ps_256:
2158 case Intrinsic::x86_avx2_gather_q_ps:
2159 case Intrinsic::x86_avx2_gather_q_ps_256:
2160 case Intrinsic::x86_avx2_gather_d_q:
2161 case Intrinsic::x86_avx2_gather_d_q_256:
2162 case Intrinsic::x86_avx2_gather_q_q:
2163 case Intrinsic::x86_avx2_gather_q_q_256:
2164 case Intrinsic::x86_avx2_gather_d_d:
2165 case Intrinsic::x86_avx2_gather_d_d_256:
2166 case Intrinsic::x86_avx2_gather_q_d:
2167 case Intrinsic::x86_avx2_gather_q_d_256: {
2168 if (!Subtarget->hasAVX2())
2172 default: llvm_unreachable("Impossible intrinsic");
2173 case Intrinsic::x86_avx2_gather_d_pd: Opc = X86::VGATHERDPDrm; break;
2174 case Intrinsic::x86_avx2_gather_d_pd_256: Opc = X86::VGATHERDPDYrm; break;
2175 case Intrinsic::x86_avx2_gather_q_pd: Opc = X86::VGATHERQPDrm; break;
2176 case Intrinsic::x86_avx2_gather_q_pd_256: Opc = X86::VGATHERQPDYrm; break;
2177 case Intrinsic::x86_avx2_gather_d_ps: Opc = X86::VGATHERDPSrm; break;
2178 case Intrinsic::x86_avx2_gather_d_ps_256: Opc = X86::VGATHERDPSYrm; break;
2179 case Intrinsic::x86_avx2_gather_q_ps: Opc = X86::VGATHERQPSrm; break;
2180 case Intrinsic::x86_avx2_gather_q_ps_256: Opc = X86::VGATHERQPSYrm; break;
2181 case Intrinsic::x86_avx2_gather_d_q: Opc = X86::VPGATHERDQrm; break;
2182 case Intrinsic::x86_avx2_gather_d_q_256: Opc = X86::VPGATHERDQYrm; break;
2183 case Intrinsic::x86_avx2_gather_q_q: Opc = X86::VPGATHERQQrm; break;
2184 case Intrinsic::x86_avx2_gather_q_q_256: Opc = X86::VPGATHERQQYrm; break;
2185 case Intrinsic::x86_avx2_gather_d_d: Opc = X86::VPGATHERDDrm; break;
2186 case Intrinsic::x86_avx2_gather_d_d_256: Opc = X86::VPGATHERDDYrm; break;
2187 case Intrinsic::x86_avx2_gather_q_d: Opc = X86::VPGATHERQDrm; break;
2188 case Intrinsic::x86_avx2_gather_q_d_256: Opc = X86::VPGATHERQDYrm; break;
2190 SDNode *RetVal = SelectGather(Node, Opc);
2192 // We already called ReplaceUses inside SelectGather.
2199 case X86ISD::GlobalBaseReg:
2200 return getGlobalBaseReg();
2202 case X86ISD::SHRUNKBLEND: {
2203 // SHRUNKBLEND selects like a regular VSELECT.
2204 SDValue VSelect = CurDAG->getNode(
2205 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2206 Node->getOperand(1), Node->getOperand(2));
2207 ReplaceUses(SDValue(Node, 0), VSelect);
2208 SelectCode(VSelect.getNode());
2209 // We already called ReplaceUses.
2213 case ISD::ATOMIC_LOAD_XOR:
2214 case ISD::ATOMIC_LOAD_AND:
2215 case ISD::ATOMIC_LOAD_OR:
2216 case ISD::ATOMIC_LOAD_ADD: {
2217 SDNode *RetVal = SelectAtomicLoadArith(Node, NVT);
2225 // For operations of the form (x << C1) op C2, check if we can use a smaller
2226 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2227 SDValue N0 = Node->getOperand(0);
2228 SDValue N1 = Node->getOperand(1);
2230 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2233 // i8 is unshrinkable, i16 should be promoted to i32.
2234 if (NVT != MVT::i32 && NVT != MVT::i64)
2237 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2238 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2239 if (!Cst || !ShlCst)
2242 int64_t Val = Cst->getSExtValue();
2243 uint64_t ShlVal = ShlCst->getZExtValue();
2245 // Make sure that we don't change the operation by removing bits.
2246 // This only matters for OR and XOR, AND is unaffected.
2247 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2248 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2251 unsigned ShlOp, AddOp, Op;
2254 // Check the minimum bitwidth for the new constant.
2255 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2256 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2257 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2258 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2260 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2263 // Bail if there is no smaller encoding.
2267 switch (NVT.SimpleTy) {
2268 default: llvm_unreachable("Unsupported VT!");
2270 assert(CstVT == MVT::i8);
2271 ShlOp = X86::SHL32ri;
2272 AddOp = X86::ADD32rr;
2275 default: llvm_unreachable("Impossible opcode");
2276 case ISD::AND: Op = X86::AND32ri8; break;
2277 case ISD::OR: Op = X86::OR32ri8; break;
2278 case ISD::XOR: Op = X86::XOR32ri8; break;
2282 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2283 ShlOp = X86::SHL64ri;
2284 AddOp = X86::ADD64rr;
2287 default: llvm_unreachable("Impossible opcode");
2288 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2289 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2290 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2295 // Emit the smaller op and the shift.
2296 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2297 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2299 return CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2301 return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2302 getI8Imm(ShlVal, dl));
2305 case X86ISD::SMUL8: {
2306 SDValue N0 = Node->getOperand(0);
2307 SDValue N1 = Node->getOperand(1);
2309 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2311 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2312 N0, SDValue()).getValue(1);
2314 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2315 SDValue Ops[] = {N1, InFlag};
2316 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2318 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2319 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2323 case X86ISD::UMUL: {
2324 SDValue N0 = Node->getOperand(0);
2325 SDValue N1 = Node->getOperand(1);
2328 switch (NVT.SimpleTy) {
2329 default: llvm_unreachable("Unsupported VT!");
2330 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2331 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2332 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2333 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2336 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2337 N0, SDValue()).getValue(1);
2339 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2340 SDValue Ops[] = {N1, InFlag};
2341 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2343 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2344 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2345 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 2));
2349 case ISD::SMUL_LOHI:
2350 case ISD::UMUL_LOHI: {
2351 SDValue N0 = Node->getOperand(0);
2352 SDValue N1 = Node->getOperand(1);
2354 bool isSigned = Opcode == ISD::SMUL_LOHI;
2355 bool hasBMI2 = Subtarget->hasBMI2();
2357 switch (NVT.SimpleTy) {
2358 default: llvm_unreachable("Unsupported VT!");
2359 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2360 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2361 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2362 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2363 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2364 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2367 switch (NVT.SimpleTy) {
2368 default: llvm_unreachable("Unsupported VT!");
2369 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2370 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2371 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2372 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2376 unsigned SrcReg, LoReg, HiReg;
2378 default: llvm_unreachable("Unknown MUL opcode!");
2381 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2385 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2389 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2393 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2396 SrcReg = X86::EDX; LoReg = HiReg = 0;
2399 SrcReg = X86::RDX; LoReg = HiReg = 0;
2403 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2404 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2405 // Multiply is commmutative.
2407 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2412 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2413 N0, SDValue()).getValue(1);
2414 SDValue ResHi, ResLo;
2418 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2420 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2421 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2422 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2423 ResHi = SDValue(CNode, 0);
2424 ResLo = SDValue(CNode, 1);
2425 Chain = SDValue(CNode, 2);
2426 InFlag = SDValue(CNode, 3);
2428 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2429 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2430 Chain = SDValue(CNode, 0);
2431 InFlag = SDValue(CNode, 1);
2434 // Update the chain.
2435 ReplaceUses(N1.getValue(1), Chain);
2437 SDValue Ops[] = { N1, InFlag };
2438 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2439 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2440 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2441 ResHi = SDValue(CNode, 0);
2442 ResLo = SDValue(CNode, 1);
2443 InFlag = SDValue(CNode, 2);
2445 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2446 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2447 InFlag = SDValue(CNode, 0);
2451 // Prevent use of AH in a REX instruction by referencing AX instead.
2452 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2453 !SDValue(Node, 1).use_empty()) {
2454 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2455 X86::AX, MVT::i16, InFlag);
2456 InFlag = Result.getValue(2);
2457 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2459 if (!SDValue(Node, 0).use_empty())
2460 ReplaceUses(SDValue(Node, 1),
2461 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2463 // Shift AX down 8 bits.
2464 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2466 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2468 // Then truncate it down to i8.
2469 ReplaceUses(SDValue(Node, 1),
2470 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2472 // Copy the low half of the result, if it is needed.
2473 if (!SDValue(Node, 0).use_empty()) {
2474 if (!ResLo.getNode()) {
2475 assert(LoReg && "Register for low half is not defined!");
2476 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2478 InFlag = ResLo.getValue(2);
2480 ReplaceUses(SDValue(Node, 0), ResLo);
2481 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2483 // Copy the high half of the result, if it is needed.
2484 if (!SDValue(Node, 1).use_empty()) {
2485 if (!ResHi.getNode()) {
2486 assert(HiReg && "Register for high half is not defined!");
2487 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2489 InFlag = ResHi.getValue(2);
2491 ReplaceUses(SDValue(Node, 1), ResHi);
2492 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2500 case X86ISD::SDIVREM8_SEXT_HREG:
2501 case X86ISD::UDIVREM8_ZEXT_HREG: {
2502 SDValue N0 = Node->getOperand(0);
2503 SDValue N1 = Node->getOperand(1);
2505 bool isSigned = (Opcode == ISD::SDIVREM ||
2506 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2508 switch (NVT.SimpleTy) {
2509 default: llvm_unreachable("Unsupported VT!");
2510 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2511 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2512 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2513 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2516 switch (NVT.SimpleTy) {
2517 default: llvm_unreachable("Unsupported VT!");
2518 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2519 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2520 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2521 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2525 unsigned LoReg, HiReg, ClrReg;
2526 unsigned SExtOpcode;
2527 switch (NVT.SimpleTy) {
2528 default: llvm_unreachable("Unsupported VT!");
2530 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2531 SExtOpcode = X86::CBW;
2534 LoReg = X86::AX; HiReg = X86::DX;
2536 SExtOpcode = X86::CWD;
2539 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2540 SExtOpcode = X86::CDQ;
2543 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2544 SExtOpcode = X86::CQO;
2548 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2549 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2550 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2553 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2554 // Special case for div8, just use a move with zero extension to AX to
2555 // clear the upper 8 bits (AH).
2556 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2557 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2558 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2560 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2561 MVT::Other, Ops), 0);
2562 Chain = Move.getValue(1);
2563 ReplaceUses(N0.getValue(1), Chain);
2566 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2567 Chain = CurDAG->getEntryNode();
2569 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2570 InFlag = Chain.getValue(1);
2573 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2574 LoReg, N0, SDValue()).getValue(1);
2575 if (isSigned && !signBitIsZero) {
2576 // Sign extend the low part into the high part.
2578 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2580 // Zero out the high part, effectively zero extending the input.
2581 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2582 switch (NVT.SimpleTy) {
2585 SDValue(CurDAG->getMachineNode(
2586 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2587 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2595 SDValue(CurDAG->getMachineNode(
2596 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2597 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2598 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2603 llvm_unreachable("Unexpected division source");
2606 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2607 ClrNode, InFlag).getValue(1);
2612 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2615 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2616 InFlag = SDValue(CNode, 1);
2617 // Update the chain.
2618 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2621 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2624 // Prevent use of AH in a REX instruction by explicitly copying it to
2625 // an ABCD_L register.
2627 // The current assumption of the register allocator is that isel
2628 // won't generate explicit references to the GR8_ABCD_H registers. If
2629 // the allocator and/or the backend get enhanced to be more robust in
2630 // that regard, this can be, and should be, removed.
2631 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2632 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2633 unsigned AHExtOpcode =
2634 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2636 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2637 MVT::Glue, AHCopy, InFlag);
2638 SDValue Result(RNode, 0);
2639 InFlag = SDValue(RNode, 1);
2641 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2642 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2643 if (Node->getValueType(1) == MVT::i64) {
2644 // It's not possible to directly movsx AH to a 64bit register, because
2645 // the latter needs the REX prefix, but the former can't have it.
2646 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2647 "Unexpected i64 sext of h-register");
2649 SDValue(CurDAG->getMachineNode(
2650 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2651 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2652 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2658 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2660 ReplaceUses(SDValue(Node, 1), Result);
2661 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2663 // Copy the division (low) result, if it is needed.
2664 if (!SDValue(Node, 0).use_empty()) {
2665 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2666 LoReg, NVT, InFlag);
2667 InFlag = Result.getValue(2);
2668 ReplaceUses(SDValue(Node, 0), Result);
2669 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2671 // Copy the remainder (high) result, if it is needed.
2672 if (!SDValue(Node, 1).use_empty()) {
2673 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2674 HiReg, NVT, InFlag);
2675 InFlag = Result.getValue(2);
2676 ReplaceUses(SDValue(Node, 1), Result);
2677 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2684 // Sometimes a SUB is used to perform comparison.
2685 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2686 // This node is not a CMP.
2688 SDValue N0 = Node->getOperand(0);
2689 SDValue N1 = Node->getOperand(1);
2691 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2692 HasNoSignedComparisonUses(Node))
2693 N0 = N0.getOperand(0);
2695 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2696 // use a smaller encoding.
2697 // Look past the truncate if CMP is the only use of it.
2698 if ((N0.getNode()->getOpcode() == ISD::AND ||
2699 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2700 N0.getNode()->hasOneUse() &&
2701 N0.getValueType() != MVT::i8 &&
2702 X86::isZeroNode(N1)) {
2703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2706 // For example, convert "testl %eax, $8" to "testb %al, $8"
2707 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2708 (!(C->getZExtValue() & 0x80) ||
2709 HasNoSignedComparisonUses(Node))) {
2710 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2711 SDValue Reg = N0.getNode()->getOperand(0);
2713 // On x86-32, only the ABCD registers have 8-bit subregisters.
2714 if (!Subtarget->is64Bit()) {
2715 const TargetRegisterClass *TRC;
2716 switch (N0.getSimpleValueType().SimpleTy) {
2717 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2718 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2719 default: llvm_unreachable("Unsupported TEST operand type!");
2721 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2722 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2723 Reg.getValueType(), Reg, RC), 0);
2726 // Extract the l-register.
2727 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2731 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2733 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2734 // one, do not call ReplaceAllUsesWith.
2735 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2736 SDValue(NewNode, 0));
2740 // For example, "testl %eax, $2048" to "testb %ah, $8".
2741 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2742 (!(C->getZExtValue() & 0x8000) ||
2743 HasNoSignedComparisonUses(Node))) {
2744 // Shift the immediate right by 8 bits.
2745 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2747 SDValue Reg = N0.getNode()->getOperand(0);
2749 // Put the value in an ABCD register.
2750 const TargetRegisterClass *TRC;
2751 switch (N0.getSimpleValueType().SimpleTy) {
2752 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2753 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2754 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2755 default: llvm_unreachable("Unsupported TEST operand type!");
2757 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2758 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2759 Reg.getValueType(), Reg, RC), 0);
2761 // Extract the h-register.
2762 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2765 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2766 // target GR8_NOREX registers, so make sure the register class is
2768 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2769 MVT::i32, Subreg, ShiftedImm);
2770 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2771 // one, do not call ReplaceAllUsesWith.
2772 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2773 SDValue(NewNode, 0));
2777 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2778 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2779 N0.getValueType() != MVT::i16 &&
2780 (!(C->getZExtValue() & 0x8000) ||
2781 HasNoSignedComparisonUses(Node))) {
2782 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2784 SDValue Reg = N0.getNode()->getOperand(0);
2786 // Extract the 16-bit subregister.
2787 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2791 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2793 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2794 // one, do not call ReplaceAllUsesWith.
2795 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2796 SDValue(NewNode, 0));
2800 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2801 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2802 N0.getValueType() == MVT::i64 &&
2803 (!(C->getZExtValue() & 0x80000000) ||
2804 HasNoSignedComparisonUses(Node))) {
2805 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2807 SDValue Reg = N0.getNode()->getOperand(0);
2809 // Extract the 32-bit subregister.
2810 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2814 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2816 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2817 // one, do not call ReplaceAllUsesWith.
2818 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2819 SDValue(NewNode, 0));
2826 // Change a chain of {load; incr or dec; store} of the same value into
2827 // a simple increment or decrement through memory of that value, if the
2828 // uses of the modified value and its address are suitable.
2829 // The DEC64m tablegen pattern is currently not able to match the case where
2830 // the EFLAGS on the original DEC are used. (This also applies to
2831 // {INC,DEC}X{64,32,16,8}.)
2832 // We'll need to improve tablegen to allow flags to be transferred from a
2833 // node in the pattern to the result node. probably with a new keyword
2834 // for example, we have this
2835 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2836 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2837 // (implicit EFLAGS)]>;
2838 // but maybe need something like this
2839 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2840 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2841 // (transferrable EFLAGS)]>;
2843 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2844 SDValue StoredVal = StoreNode->getOperand(1);
2845 unsigned Opc = StoredVal->getOpcode();
2847 LoadSDNode *LoadNode = nullptr;
2849 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2850 LoadNode, InputChain))
2853 SDValue Base, Scale, Index, Disp, Segment;
2854 if (!SelectAddr(LoadNode, LoadNode->getBasePtr(),
2855 Base, Scale, Index, Disp, Segment))
2858 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2859 MemOp[0] = StoreNode->getMemOperand();
2860 MemOp[1] = LoadNode->getMemOperand();
2861 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2862 EVT LdVT = LoadNode->getMemoryVT();
2863 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2864 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2866 MVT::i32, MVT::Other, Ops);
2867 Result->setMemRefs(MemOp, MemOp + 2);
2869 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2870 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2876 SDNode *ResNode = SelectCode(Node);
2878 DEBUG(dbgs() << "=> ";
2879 if (ResNode == nullptr || ResNode == Node)
2882 ResNode->dump(CurDAG);
2888 bool X86DAGToDAGISel::
2889 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2890 std::vector<SDValue> &OutOps) {
2891 SDValue Op0, Op1, Op2, Op3, Op4;
2892 switch (ConstraintID) {
2894 llvm_unreachable("Unexpected asm memory constraint");
2895 case InlineAsm::Constraint_i:
2896 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2897 // be an immediate and not a memory constraint.
2899 case InlineAsm::Constraint_o: // offsetable ??
2900 case InlineAsm::Constraint_v: // not offsetable ??
2901 case InlineAsm::Constraint_m: // memory
2902 case InlineAsm::Constraint_X:
2903 if (!SelectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2908 OutOps.push_back(Op0);
2909 OutOps.push_back(Op1);
2910 OutOps.push_back(Op2);
2911 OutOps.push_back(Op3);
2912 OutOps.push_back(Op4);
2916 /// createX86ISelDag - This pass converts a legalized DAG into a
2917 /// X86-specific DAG, ready for instruction scheduling.
2919 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2920 CodeGenOpt::Level OptLevel) {
2921 return new X86DAGToDAGISel(TM, OptLevel);