1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
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"
39 #include <stdint.h>
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "x86-isel"
43 
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45 
46 //===----------------------------------------------------------------------===//
47 //                      Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
49 
50 namespace {
51   /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52   /// numbers for the leaves of the matched tree.
53   struct X86ISelAddressMode {
54     enum {
55       RegBase,
56       FrameIndexBase
57     } BaseType;
58 
59     // This is really a union, discriminated by BaseType!
60     SDValue Base_Reg;
61     int Base_FrameIndex;
62 
63     unsigned Scale;
64     SDValue IndexReg;
65     int32_t Disp;
66     SDValue Segment;
67     const GlobalValue *GV;
68     const Constant *CP;
69     const BlockAddress *BlockAddr;
70     const char *ES;
71     MCSymbol *MCSym;
72     int JT;
73     unsigned Align;    // CP alignment.
74     unsigned char SymbolFlags;  // X86II::MO_*
75 
76     X86ISelAddressMode()
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) {}
80 
81     bool hasSymbolicDisplacement() const {
82       return GV != nullptr || CP != nullptr || ES != nullptr ||
83              MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
84     }
85 
86     bool hasBaseOrIndexReg() const {
87       return BaseType == FrameIndexBase ||
88              IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
89     }
90 
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;
97       return false;
98     }
99 
100     void setBaseReg(SDValue Reg) {
101       BaseType = RegBase;
102       Base_Reg = Reg;
103     }
104 
105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
106     void dump() {
107       dbgs() << "X86ISelAddressMode " << this << '\n';
108       dbgs() << "Base_Reg ";
109       if (Base_Reg.getNode())
110         Base_Reg.getNode()->dump();
111       else
112         dbgs() << "nul";
113       dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
114              << " Scale" << Scale << '\n'
115              << "IndexReg ";
116       if (IndexReg.getNode())
117         IndexReg.getNode()->dump();
118       else
119         dbgs() << "nul";
120       dbgs() << " Disp " << Disp << '\n'
121              << "GV ";
122       if (GV)
123         GV->dump();
124       else
125         dbgs() << "nul";
126       dbgs() << " CP ";
127       if (CP)
128         CP->dump();
129       else
130         dbgs() << "nul";
131       dbgs() << '\n'
132              << "ES ";
133       if (ES)
134         dbgs() << ES;
135       else
136         dbgs() << "nul";
137       dbgs() << " MCSym ";
138       if (MCSym)
139         dbgs() << MCSym;
140       else
141         dbgs() << "nul";
142       dbgs() << " JT" << JT << " Align" << Align << '\n';
143     }
144 #endif
145   };
146 }
147 
148 namespace {
149   //===--------------------------------------------------------------------===//
150   /// ISel - X86-specific code to select X86 machine instructions for
151   /// SelectionDAG operations.
152   ///
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;
157 
158     /// If true, selector should try to optimize for code size instead of
159     /// performance.
160     bool OptForSize;
161 
162     /// If true, selector should try to optimize for minimum code size.
163     bool OptForMinSize;
164 
165   public:
166     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
167         : SelectionDAGISel(tm, OptLevel), OptForSize(false),
168           OptForMinSize(false) {}
169 
170     StringRef getPassName() const override {
171       return "X86 DAG->DAG Instruction Selection";
172     }
173 
174     bool runOnMachineFunction(MachineFunction &MF) override {
175       // Reset the subtarget each time through.
176       Subtarget = &MF.getSubtarget<X86Subtarget>();
177       SelectionDAGISel::runOnMachineFunction(MF);
178       return true;
179     }
180 
181     void EmitFunctionEntryCode() override;
182 
183     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
184 
185     void PreprocessISelDAG() override;
186 
187 // Include the pieces autogenerated from the target description.
188 #include "X86GenDAGISel.inc"
189 
190   private:
191     void Select(SDNode *N) override;
192 
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,
199                                  unsigned Depth);
200     bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201     bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
202                     SDValue &Scale, SDValue &Index, SDValue &Disp,
203                     SDValue &Segment);
204     bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
205                           SDValue &Scale, SDValue &Index, SDValue &Disp,
206                           SDValue &Segment);
207     template <class GatherScatterSDNode>
208     bool selectAddrOfGatherScatterNode(GatherScatterSDNode *Parent, SDValue N,
209                                        SDValue &Base, SDValue &Scale,
210                                        SDValue &Index, SDValue &Disp,
211                                        SDValue &Segment);
212     bool selectMOV64Imm32(SDValue N, SDValue &Imm);
213     bool selectLEAAddr(SDValue N, SDValue &Base,
214                        SDValue &Scale, SDValue &Index, SDValue &Disp,
215                        SDValue &Segment);
216     bool selectLEA64_32Addr(SDValue N, SDValue &Base,
217                             SDValue &Scale, SDValue &Index, SDValue &Disp,
218                             SDValue &Segment);
219     bool selectTLSADDRAddr(SDValue N, SDValue &Base,
220                            SDValue &Scale, SDValue &Index, SDValue &Disp,
221                            SDValue &Segment);
222     bool selectScalarSSELoad(SDNode *Root, SDValue N,
223                              SDValue &Base, SDValue &Scale,
224                              SDValue &Index, SDValue &Disp,
225                              SDValue &Segment,
226                              SDValue &NodeWithChain);
227     bool selectRelocImm(SDValue N, SDValue &Op);
228 
229     bool tryFoldLoad(SDNode *P, SDValue N,
230                      SDValue &Base, SDValue &Scale,
231                      SDValue &Index, SDValue &Disp,
232                      SDValue &Segment);
233 
234     /// Implement addressing mode selection for inline asm expressions.
235     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
236                                       unsigned ConstraintID,
237                                       std::vector<SDValue> &OutOps) override;
238 
239     void emitSpecialCodeForMain();
240 
241     inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
242                                    SDValue &Base, SDValue &Scale,
243                                    SDValue &Index, SDValue &Disp,
244                                    SDValue &Segment) {
245       Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
246                  ? CurDAG->getTargetFrameIndex(
247                        AM.Base_FrameIndex,
248                        TLI->getPointerTy(CurDAG->getDataLayout()))
249                  : AM.Base_Reg;
250       Scale = getI8Imm(AM.Scale, DL);
251       Index = AM.IndexReg;
252       // These are 32-bit even in 64-bit mode since RIP-relative offset
253       // is 32-bit.
254       if (AM.GV)
255         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
256                                               MVT::i32, AM.Disp,
257                                               AM.SymbolFlags);
258       else if (AM.CP)
259         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
260                                              AM.Align, AM.Disp, AM.SymbolFlags);
261       else if (AM.ES) {
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,
273                                              AM.SymbolFlags);
274       else
275         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
276 
277       if (AM.Segment.getNode())
278         Segment = AM.Segment;
279       else
280         Segment = CurDAG->getRegister(0, MVT::i32);
281     }
282 
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.
288     //
289     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
290       uint32_t UseCount = 0;
291 
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.
295       if (!OptForSize)
296         return false;
297 
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) {
301 
302         SDNode *User = *UI;
303 
304         // This user is already selected. Count it as a legitimate use and
305         // move on.
306         if (User->isMachineOpcode()) {
307           UseCount++;
308           continue;
309         }
310 
311         // We want to count stores of immediates as real uses.
312         if (User->getOpcode() == ISD::STORE &&
313             User->getOperand(1).getNode() == N) {
314           UseCount++;
315           continue;
316         }
317 
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
323         // types.
324         if (User->getNumOperands() != 2)
325           continue;
326 
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) {
335 
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);
340 
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))
348               continue;
349         }
350 
351         // ... otherwise, count this and move on.
352         UseCount++;
353       }
354 
355       // If we have more than 1 use, then recommend for hoisting.
356       return (UseCount > 1);
357     }
358 
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);
362     }
363 
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);
367     }
368 
369     SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
370                                         const SDLoc &DL) {
371       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
372       uint64_t Index = N->getConstantOperandVal(1);
373       MVT VecVT = N->getOperand(0).getSimpleValueType();
374       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
375     }
376 
377     SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
378                                       const SDLoc &DL) {
379       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
380       uint64_t Index = N->getConstantOperandVal(2);
381       MVT VecVT = N->getSimpleValueType(0);
382       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
383     }
384 
385     /// Return an SDNode that returns the value of the global base register.
386     /// Output instructions required to initialize the global base register,
387     /// if necessary.
388     SDNode *getGlobalBaseReg();
389 
390     /// Return a reference to the TargetMachine, casted to the target-specific
391     /// type.
392     const X86TargetMachine &getTargetMachine() const {
393       return static_cast<const X86TargetMachine &>(TM);
394     }
395 
396     /// Return a reference to the TargetInstrInfo, casted to the target-specific
397     /// type.
398     const X86InstrInfo *getInstrInfo() const {
399       return Subtarget->getInstrInfo();
400     }
401 
402     /// \brief Address-mode matching performs shift-of-and to and-of-shift
403     /// reassociation in order to expose more scaled addressing
404     /// opportunities.
405     bool ComplexPatternFuncMutatesDAG() const override {
406       return true;
407     }
408 
409     bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
410 
411     /// Returns whether this is a relocatable immediate in the range
412     /// [-2^Width .. 2^Width-1].
413     template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
414       if (auto *CN = dyn_cast<ConstantSDNode>(N))
415         return isInt<Width>(CN->getSExtValue());
416       return isSExtAbsoluteSymbolRef(Width, N);
417     }
418 
419     // Indicates we should prefer to use a non-temporal load for this load.
420     bool useNonTemporalLoad(LoadSDNode *N) const {
421       if (!N->isNonTemporal())
422         return false;
423 
424       unsigned StoreSize = N->getMemoryVT().getStoreSize();
425 
426       if (N->getAlignment() < StoreSize)
427         return false;
428 
429       switch (StoreSize) {
430       default: llvm_unreachable("Unsupported store size");
431       case 16:
432         return Subtarget->hasSSE41();
433       case 32:
434         return Subtarget->hasAVX2();
435       case 64:
436         return Subtarget->hasAVX512();
437       }
438     }
439 
440     bool foldLoadStoreIntoMemOperand(SDNode *Node);
441 
442     bool matchBEXTRFromAnd(SDNode *Node);
443 
444     bool isMaskZeroExtended(SDNode *N) const;
445   };
446 }
447 
448 
449 // Returns true if this masked compare can be implemented legally with this
450 // type.
451 static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
452   if (N->getOpcode() == X86ISD::PCMPEQM ||
453       N->getOpcode() == X86ISD::PCMPGTM ||
454       N->getOpcode() == X86ISD::CMPM ||
455       N->getOpcode() == X86ISD::CMPMU) {
456     // We can get 256-bit 8 element types here without VLX being enabled. When
457     // this happens we will use 512-bit operations and the mask will not be
458     // zero extended.
459     if (N->getOperand(0).getValueType() == MVT::v8i32 ||
460         N->getOperand(0).getValueType() == MVT::v8f32)
461       return Subtarget->hasVLX();
462 
463     return true;
464   }
465 
466   return false;
467 }
468 
469 // Returns true if we can assume the writer of the mask has zero extended it
470 // for us.
471 bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
472   // If this is an AND, check if we have a compare on either side. As long as
473   // one side guarantees the mask is zero extended, the AND will preserve those
474   // zeros.
475   if (N->getOpcode() == ISD::AND)
476     return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
477            isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
478 
479   return isLegalMaskCompare(N, Subtarget);
480 }
481 
482 bool
483 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
484   if (OptLevel == CodeGenOpt::None) return false;
485 
486   if (!N.hasOneUse())
487     return false;
488 
489   if (N.getOpcode() != ISD::LOAD)
490     return true;
491 
492   // If N is a load, do additional profitability checks.
493   if (U == Root) {
494     switch (U->getOpcode()) {
495     default: break;
496     case X86ISD::ADD:
497     case X86ISD::SUB:
498     case X86ISD::AND:
499     case X86ISD::XOR:
500     case X86ISD::OR:
501     case ISD::ADD:
502     case ISD::ADDCARRY:
503     case ISD::AND:
504     case ISD::OR:
505     case ISD::XOR: {
506       SDValue Op1 = U->getOperand(1);
507 
508       // If the other operand is a 8-bit immediate we should fold the immediate
509       // instead. This reduces code size.
510       // e.g.
511       // movl 4(%esp), %eax
512       // addl $4, %eax
513       // vs.
514       // movl $4, %eax
515       // addl 4(%esp), %eax
516       // The former is 2 bytes shorter. In case where the increment is 1, then
517       // the saving can be 4 bytes (by using incl %eax).
518       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
519         if (Imm->getAPIntValue().isSignedIntN(8))
520           return false;
521 
522       // If the other operand is a TLS address, we should fold it instead.
523       // This produces
524       // movl    %gs:0, %eax
525       // leal    i@NTPOFF(%eax), %eax
526       // instead of
527       // movl    $i@NTPOFF, %eax
528       // addl    %gs:0, %eax
529       // if the block also has an access to a second TLS address this will save
530       // a load.
531       // FIXME: This is probably also true for non-TLS addresses.
532       if (Op1.getOpcode() == X86ISD::Wrapper) {
533         SDValue Val = Op1.getOperand(0);
534         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
535           return false;
536       }
537     }
538     }
539   }
540 
541   return true;
542 }
543 
544 /// Replace the original chain operand of the call with
545 /// load's chain operand and move load below the call's chain operand.
546 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
547                                SDValue Call, SDValue OrigChain) {
548   SmallVector<SDValue, 8> Ops;
549   SDValue Chain = OrigChain.getOperand(0);
550   if (Chain.getNode() == Load.getNode())
551     Ops.push_back(Load.getOperand(0));
552   else {
553     assert(Chain.getOpcode() == ISD::TokenFactor &&
554            "Unexpected chain operand");
555     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
556       if (Chain.getOperand(i).getNode() == Load.getNode())
557         Ops.push_back(Load.getOperand(0));
558       else
559         Ops.push_back(Chain.getOperand(i));
560     SDValue NewChain =
561       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
562     Ops.clear();
563     Ops.push_back(NewChain);
564   }
565   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
566   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
567   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
568                              Load.getOperand(1), Load.getOperand(2));
569 
570   Ops.clear();
571   Ops.push_back(SDValue(Load.getNode(), 1));
572   Ops.append(Call->op_begin() + 1, Call->op_end());
573   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
574 }
575 
576 /// Return true if call address is a load and it can be
577 /// moved below CALLSEQ_START and the chains leading up to the call.
578 /// Return the CALLSEQ_START by reference as a second output.
579 /// In the case of a tail call, there isn't a callseq node between the call
580 /// chain and the load.
581 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
582   // The transformation is somewhat dangerous if the call's chain was glued to
583   // the call. After MoveBelowOrigChain the load is moved between the call and
584   // the chain, this can create a cycle if the load is not folded. So it is
585   // *really* important that we are sure the load will be folded.
586   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
587     return false;
588   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
589   if (!LD ||
590       LD->isVolatile() ||
591       LD->getAddressingMode() != ISD::UNINDEXED ||
592       LD->getExtensionType() != ISD::NON_EXTLOAD)
593     return false;
594 
595   // Now let's find the callseq_start.
596   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
597     if (!Chain.hasOneUse())
598       return false;
599     Chain = Chain.getOperand(0);
600   }
601 
602   if (!Chain.getNumOperands())
603     return false;
604   // Since we are not checking for AA here, conservatively abort if the chain
605   // writes to memory. It's not safe to move the callee (a load) across a store.
606   if (isa<MemSDNode>(Chain.getNode()) &&
607       cast<MemSDNode>(Chain.getNode())->writeMem())
608     return false;
609   if (Chain.getOperand(0).getNode() == Callee.getNode())
610     return true;
611   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
612       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
613       Callee.getValue(1).hasOneUse())
614     return true;
615   return false;
616 }
617 
618 void X86DAGToDAGISel::PreprocessISelDAG() {
619   // OptFor[Min]Size are used in pattern predicates that isel is matching.
620   OptForSize = MF->getFunction()->optForSize();
621   OptForMinSize = MF->getFunction()->optForMinSize();
622   assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
623 
624   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
625        E = CurDAG->allnodes_end(); I != E; ) {
626     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
627 
628     if (OptLevel != CodeGenOpt::None &&
629         // Only does this when target favors doesn't favor register indirect
630         // call.
631         ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
632          (N->getOpcode() == X86ISD::TC_RETURN &&
633           // Only does this if load can be folded into TC_RETURN.
634           (Subtarget->is64Bit() ||
635            !getTargetMachine().isPositionIndependent())))) {
636       /// Also try moving call address load from outside callseq_start to just
637       /// before the call to allow it to be folded.
638       ///
639       ///     [Load chain]
640       ///         ^
641       ///         |
642       ///       [Load]
643       ///       ^    ^
644       ///       |    |
645       ///      /      \--
646       ///     /          |
647       ///[CALLSEQ_START] |
648       ///     ^          |
649       ///     |          |
650       /// [LOAD/C2Reg]   |
651       ///     |          |
652       ///      \        /
653       ///       \      /
654       ///       [CALL]
655       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
656       SDValue Chain = N->getOperand(0);
657       SDValue Load  = N->getOperand(1);
658       if (!isCalleeLoad(Load, Chain, HasCallSeq))
659         continue;
660       moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
661       ++NumLoadMoved;
662       continue;
663     }
664 
665     // Lower fpround and fpextend nodes that target the FP stack to be store and
666     // load to the stack.  This is a gross hack.  We would like to simply mark
667     // these as being illegal, but when we do that, legalize produces these when
668     // it expands calls, then expands these in the same legalize pass.  We would
669     // like dag combine to be able to hack on these between the call expansion
670     // and the node legalization.  As such this pass basically does "really
671     // late" legalization of these inline with the X86 isel pass.
672     // FIXME: This should only happen when not compiled with -O0.
673     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
674       continue;
675 
676     MVT SrcVT = N->getOperand(0).getSimpleValueType();
677     MVT DstVT = N->getSimpleValueType(0);
678 
679     // If any of the sources are vectors, no fp stack involved.
680     if (SrcVT.isVector() || DstVT.isVector())
681       continue;
682 
683     // If the source and destination are SSE registers, then this is a legal
684     // conversion that should not be lowered.
685     const X86TargetLowering *X86Lowering =
686         static_cast<const X86TargetLowering *>(TLI);
687     bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
688     bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
689     if (SrcIsSSE && DstIsSSE)
690       continue;
691 
692     if (!SrcIsSSE && !DstIsSSE) {
693       // If this is an FPStack extension, it is a noop.
694       if (N->getOpcode() == ISD::FP_EXTEND)
695         continue;
696       // If this is a value-preserving FPStack truncation, it is a noop.
697       if (N->getConstantOperandVal(1))
698         continue;
699     }
700 
701     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
702     // FPStack has extload and truncstore.  SSE can fold direct loads into other
703     // operations.  Based on this, decide what we want to do.
704     MVT MemVT;
705     if (N->getOpcode() == ISD::FP_ROUND)
706       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
707     else
708       MemVT = SrcIsSSE ? SrcVT : DstVT;
709 
710     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
711     SDLoc dl(N);
712 
713     // FIXME: optimize the case where the src/dest is a load or store?
714     SDValue Store =
715         CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
716                               MemTmp, MachinePointerInfo(), MemVT);
717     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
718                                         MachinePointerInfo(), MemVT);
719 
720     // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
721     // extload we created.  This will cause general havok on the dag because
722     // anything below the conversion could be folded into other existing nodes.
723     // To avoid invalidating 'I', back it up to the convert node.
724     --I;
725     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
726 
727     // Now that we did that, the node is dead.  Increment the iterator to the
728     // next node to process, then delete N.
729     ++I;
730     CurDAG->DeleteNode(N);
731   }
732 }
733 
734 
735 /// Emit any code that needs to be executed only in the main function.
736 void X86DAGToDAGISel::emitSpecialCodeForMain() {
737   if (Subtarget->isTargetCygMing()) {
738     TargetLowering::ArgListTy Args;
739     auto &DL = CurDAG->getDataLayout();
740 
741     TargetLowering::CallLoweringInfo CLI(*CurDAG);
742     CLI.setChain(CurDAG->getRoot())
743         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
744                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
745                    std::move(Args));
746     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
747     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
748     CurDAG->setRoot(Result.second);
749   }
750 }
751 
752 void X86DAGToDAGISel::EmitFunctionEntryCode() {
753   // If this is main, emit special code for main.
754   if (const Function *Fn = MF->getFunction())
755     if (Fn->hasExternalLinkage() && Fn->getName() == "main")
756       emitSpecialCodeForMain();
757 }
758 
759 static bool isDispSafeForFrameIndex(int64_t Val) {
760   // On 64-bit platforms, we can run into an issue where a frame index
761   // includes a displacement that, when added to the explicit displacement,
762   // will overflow the displacement field. Assuming that the frame index
763   // displacement fits into a 31-bit integer  (which is only slightly more
764   // aggressive than the current fundamental assumption that it fits into
765   // a 32-bit integer), a 31-bit disp should always be safe.
766   return isInt<31>(Val);
767 }
768 
769 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
770                                             X86ISelAddressMode &AM) {
771   // Cannot combine ExternalSymbol displacements with integer offsets.
772   if (Offset != 0 && (AM.ES || AM.MCSym))
773     return true;
774   int64_t Val = AM.Disp + Offset;
775   CodeModel::Model M = TM.getCodeModel();
776   if (Subtarget->is64Bit()) {
777     if (!X86::isOffsetSuitableForCodeModel(Val, M,
778                                            AM.hasSymbolicDisplacement()))
779       return true;
780     // In addition to the checks required for a register base, check that
781     // we do not try to use an unsafe Disp with a frame index.
782     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
783         !isDispSafeForFrameIndex(Val))
784       return true;
785   }
786   AM.Disp = Val;
787   return false;
788 
789 }
790 
791 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
792   SDValue Address = N->getOperand(1);
793 
794   // load gs:0 -> GS segment register.
795   // load fs:0 -> FS segment register.
796   //
797   // This optimization is valid because the GNU TLS model defines that
798   // gs:0 (or fs:0 on X86-64) contains its own address.
799   // For more information see http://people.redhat.com/drepper/tls.pdf
800   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
801     if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
802         (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
803          Subtarget->isTargetFuchsia()))
804       switch (N->getPointerInfo().getAddrSpace()) {
805       case 256:
806         AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
807         return false;
808       case 257:
809         AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
810         return false;
811       // Address space 258 is not handled here, because it is not used to
812       // address TLS areas.
813       }
814 
815   return true;
816 }
817 
818 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
819 /// mode. These wrap things that will resolve down into a symbol reference.
820 /// If no match is possible, this returns true, otherwise it returns false.
821 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
822   // If the addressing mode already has a symbol as the displacement, we can
823   // never match another symbol.
824   if (AM.hasSymbolicDisplacement())
825     return true;
826 
827   SDValue N0 = N.getOperand(0);
828   CodeModel::Model M = TM.getCodeModel();
829 
830   // Handle X86-64 rip-relative addresses.  We check this before checking direct
831   // folding because RIP is preferable to non-RIP accesses.
832   if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
833       // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
834       // they cannot be folded into immediate fields.
835       // FIXME: This can be improved for kernel and other models?
836       (M == CodeModel::Small || M == CodeModel::Kernel)) {
837     // Base and index reg must be 0 in order to use %rip as base.
838     if (AM.hasBaseOrIndexReg())
839       return true;
840     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
841       X86ISelAddressMode Backup = AM;
842       AM.GV = G->getGlobal();
843       AM.SymbolFlags = G->getTargetFlags();
844       if (foldOffsetIntoAddress(G->getOffset(), AM)) {
845         AM = Backup;
846         return true;
847       }
848     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
849       X86ISelAddressMode Backup = AM;
850       AM.CP = CP->getConstVal();
851       AM.Align = CP->getAlignment();
852       AM.SymbolFlags = CP->getTargetFlags();
853       if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
854         AM = Backup;
855         return true;
856       }
857     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
858       AM.ES = S->getSymbol();
859       AM.SymbolFlags = S->getTargetFlags();
860     } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
861       AM.MCSym = S->getMCSymbol();
862     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
863       AM.JT = J->getIndex();
864       AM.SymbolFlags = J->getTargetFlags();
865     } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
866       X86ISelAddressMode Backup = AM;
867       AM.BlockAddr = BA->getBlockAddress();
868       AM.SymbolFlags = BA->getTargetFlags();
869       if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
870         AM = Backup;
871         return true;
872       }
873     } else
874       llvm_unreachable("Unhandled symbol reference node.");
875 
876     if (N.getOpcode() == X86ISD::WrapperRIP)
877       AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
878     return false;
879   }
880 
881   // Handle the case when globals fit in our immediate field: This is true for
882   // X86-32 always and X86-64 when in -mcmodel=small mode.  In 64-bit
883   // mode, this only applies to a non-RIP-relative computation.
884   if (!Subtarget->is64Bit() ||
885       M == CodeModel::Small || M == CodeModel::Kernel) {
886     assert(N.getOpcode() != X86ISD::WrapperRIP &&
887            "RIP-relative addressing already handled");
888     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
889       AM.GV = G->getGlobal();
890       AM.Disp += G->getOffset();
891       AM.SymbolFlags = G->getTargetFlags();
892     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
893       AM.CP = CP->getConstVal();
894       AM.Align = CP->getAlignment();
895       AM.Disp += CP->getOffset();
896       AM.SymbolFlags = CP->getTargetFlags();
897     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
898       AM.ES = S->getSymbol();
899       AM.SymbolFlags = S->getTargetFlags();
900     } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
901       AM.MCSym = S->getMCSymbol();
902     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
903       AM.JT = J->getIndex();
904       AM.SymbolFlags = J->getTargetFlags();
905     } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
906       AM.BlockAddr = BA->getBlockAddress();
907       AM.Disp += BA->getOffset();
908       AM.SymbolFlags = BA->getTargetFlags();
909     } else
910       llvm_unreachable("Unhandled symbol reference node.");
911     return false;
912   }
913 
914   return true;
915 }
916 
917 /// Add the specified node to the specified addressing mode, returning true if
918 /// it cannot be done. This just pattern matches for the addressing mode.
919 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
920   if (matchAddressRecursively(N, AM, 0))
921     return true;
922 
923   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
924   // a smaller encoding and avoids a scaled-index.
925   if (AM.Scale == 2 &&
926       AM.BaseType == X86ISelAddressMode::RegBase &&
927       AM.Base_Reg.getNode() == nullptr) {
928     AM.Base_Reg = AM.IndexReg;
929     AM.Scale = 1;
930   }
931 
932   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
933   // because it has a smaller encoding.
934   // TODO: Which other code models can use this?
935   if (TM.getCodeModel() == CodeModel::Small &&
936       Subtarget->is64Bit() &&
937       AM.Scale == 1 &&
938       AM.BaseType == X86ISelAddressMode::RegBase &&
939       AM.Base_Reg.getNode() == nullptr &&
940       AM.IndexReg.getNode() == nullptr &&
941       AM.SymbolFlags == X86II::MO_NO_FLAG &&
942       AM.hasSymbolicDisplacement())
943     AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
944 
945   return false;
946 }
947 
948 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
949                                unsigned Depth) {
950   // Add an artificial use to this node so that we can keep track of
951   // it if it gets CSE'd with a different node.
952   HandleSDNode Handle(N);
953 
954   X86ISelAddressMode Backup = AM;
955   if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
956       !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
957     return false;
958   AM = Backup;
959 
960   // Try again after commuting the operands.
961   if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
962       !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
963     return false;
964   AM = Backup;
965 
966   // If we couldn't fold both operands into the address at the same time,
967   // see if we can just put each operand into a register and fold at least
968   // the add.
969   if (AM.BaseType == X86ISelAddressMode::RegBase &&
970       !AM.Base_Reg.getNode() &&
971       !AM.IndexReg.getNode()) {
972     N = Handle.getValue();
973     AM.Base_Reg = N.getOperand(0);
974     AM.IndexReg = N.getOperand(1);
975     AM.Scale = 1;
976     return false;
977   }
978   N = Handle.getValue();
979   return true;
980 }
981 
982 // Insert a node into the DAG at least before the Pos node's position. This
983 // will reposition the node as needed, and will assign it a node ID that is <=
984 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
985 // IDs! The selection DAG must no longer depend on their uniqueness when this
986 // is used.
987 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
988   if (N.getNode()->getNodeId() == -1 ||
989       N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
990     DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
991     N.getNode()->setNodeId(Pos.getNode()->getNodeId());
992   }
993 }
994 
995 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
996 // safe. This allows us to convert the shift and and into an h-register
997 // extract and a scaled index. Returns false if the simplification is
998 // performed.
999 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1000                                       uint64_t Mask,
1001                                       SDValue Shift, SDValue X,
1002                                       X86ISelAddressMode &AM) {
1003   if (Shift.getOpcode() != ISD::SRL ||
1004       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1005       !Shift.hasOneUse())
1006     return true;
1007 
1008   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1009   if (ScaleLog <= 0 || ScaleLog >= 4 ||
1010       Mask != (0xffu << ScaleLog))
1011     return true;
1012 
1013   MVT VT = N.getSimpleValueType();
1014   SDLoc DL(N);
1015   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1016   SDValue NewMask = DAG.getConstant(0xff, DL, VT);
1017   SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1018   SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
1019   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
1020   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1021 
1022   // Insert the new nodes into the topological ordering. We must do this in
1023   // a valid topological ordering as nothing is going to go back and re-sort
1024   // these nodes. We continually insert before 'N' in sequence as this is
1025   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1026   // hierarchy left to express.
1027   insertDAGNode(DAG, N, Eight);
1028   insertDAGNode(DAG, N, Srl);
1029   insertDAGNode(DAG, N, NewMask);
1030   insertDAGNode(DAG, N, And);
1031   insertDAGNode(DAG, N, ShlCount);
1032   insertDAGNode(DAG, N, Shl);
1033   DAG.ReplaceAllUsesWith(N, Shl);
1034   AM.IndexReg = And;
1035   AM.Scale = (1 << ScaleLog);
1036   return false;
1037 }
1038 
1039 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1040 // allows us to fold the shift into this addressing mode. Returns false if the
1041 // transform succeeded.
1042 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1043                                         uint64_t Mask,
1044                                         SDValue Shift, SDValue X,
1045                                         X86ISelAddressMode &AM) {
1046   if (Shift.getOpcode() != ISD::SHL ||
1047       !isa<ConstantSDNode>(Shift.getOperand(1)))
1048     return true;
1049 
1050   // Not likely to be profitable if either the AND or SHIFT node has more
1051   // than one use (unless all uses are for address computation). Besides,
1052   // isel mechanism requires their node ids to be reused.
1053   if (!N.hasOneUse() || !Shift.hasOneUse())
1054     return true;
1055 
1056   // Verify that the shift amount is something we can fold.
1057   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1058   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1059     return true;
1060 
1061   MVT VT = N.getSimpleValueType();
1062   SDLoc DL(N);
1063   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
1064   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1065   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1066 
1067   // Insert the new nodes into the topological ordering. We must do this in
1068   // a valid topological ordering as nothing is going to go back and re-sort
1069   // these nodes. We continually insert before 'N' in sequence as this is
1070   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1071   // hierarchy left to express.
1072   insertDAGNode(DAG, N, NewMask);
1073   insertDAGNode(DAG, N, NewAnd);
1074   insertDAGNode(DAG, N, NewShift);
1075   DAG.ReplaceAllUsesWith(N, NewShift);
1076 
1077   AM.Scale = 1 << ShiftAmt;
1078   AM.IndexReg = NewAnd;
1079   return false;
1080 }
1081 
1082 // Implement some heroics to detect shifts of masked values where the mask can
1083 // be replaced by extending the shift and undoing that in the addressing mode
1084 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1085 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1086 // the addressing mode. This results in code such as:
1087 //
1088 //   int f(short *y, int *lookup_table) {
1089 //     ...
1090 //     return *y + lookup_table[*y >> 11];
1091 //   }
1092 //
1093 // Turning into:
1094 //   movzwl (%rdi), %eax
1095 //   movl %eax, %ecx
1096 //   shrl $11, %ecx
1097 //   addl (%rsi,%rcx,4), %eax
1098 //
1099 // Instead of:
1100 //   movzwl (%rdi), %eax
1101 //   movl %eax, %ecx
1102 //   shrl $9, %ecx
1103 //   andl $124, %rcx
1104 //   addl (%rsi,%rcx), %eax
1105 //
1106 // Note that this function assumes the mask is provided as a mask *after* the
1107 // value is shifted. The input chain may or may not match that, but computing
1108 // such a mask is trivial.
1109 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1110                                     uint64_t Mask,
1111                                     SDValue Shift, SDValue X,
1112                                     X86ISelAddressMode &AM) {
1113   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1114       !isa<ConstantSDNode>(Shift.getOperand(1)))
1115     return true;
1116 
1117   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1118   unsigned MaskLZ = countLeadingZeros(Mask);
1119   unsigned MaskTZ = countTrailingZeros(Mask);
1120 
1121   // The amount of shift we're trying to fit into the addressing mode is taken
1122   // from the trailing zeros of the mask.
1123   unsigned AMShiftAmt = MaskTZ;
1124 
1125   // There is nothing we can do here unless the mask is removing some bits.
1126   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1127   if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1128 
1129   // We also need to ensure that mask is a continuous run of bits.
1130   if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1131 
1132   // Scale the leading zero count down based on the actual size of the value.
1133   // Also scale it down based on the size of the shift.
1134   unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1135   if (MaskLZ < ScaleDown)
1136     return true;
1137   MaskLZ -= ScaleDown;
1138 
1139   // The final check is to ensure that any masked out high bits of X are
1140   // already known to be zero. Otherwise, the mask has a semantic impact
1141   // other than masking out a couple of low bits. Unfortunately, because of
1142   // the mask, zero extensions will be removed from operands in some cases.
1143   // This code works extra hard to look through extensions because we can
1144   // replace them with zero extensions cheaply if necessary.
1145   bool ReplacingAnyExtend = false;
1146   if (X.getOpcode() == ISD::ANY_EXTEND) {
1147     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1148                           X.getOperand(0).getSimpleValueType().getSizeInBits();
1149     // Assume that we'll replace the any-extend with a zero-extend, and
1150     // narrow the search to the extended value.
1151     X = X.getOperand(0);
1152     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1153     ReplacingAnyExtend = true;
1154   }
1155   APInt MaskedHighBits =
1156     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1157   KnownBits Known;
1158   DAG.computeKnownBits(X, Known);
1159   if (MaskedHighBits != Known.Zero) return true;
1160 
1161   // We've identified a pattern that can be transformed into a single shift
1162   // and an addressing mode. Make it so.
1163   MVT VT = N.getSimpleValueType();
1164   if (ReplacingAnyExtend) {
1165     assert(X.getValueType() != VT);
1166     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1167     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1168     insertDAGNode(DAG, N, NewX);
1169     X = NewX;
1170   }
1171   SDLoc DL(N);
1172   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1173   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1174   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1175   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1176 
1177   // Insert the new nodes into the topological ordering. We must do this in
1178   // a valid topological ordering as nothing is going to go back and re-sort
1179   // these nodes. We continually insert before 'N' in sequence as this is
1180   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1181   // hierarchy left to express.
1182   insertDAGNode(DAG, N, NewSRLAmt);
1183   insertDAGNode(DAG, N, NewSRL);
1184   insertDAGNode(DAG, N, NewSHLAmt);
1185   insertDAGNode(DAG, N, NewSHL);
1186   DAG.ReplaceAllUsesWith(N, NewSHL);
1187 
1188   AM.Scale = 1 << AMShiftAmt;
1189   AM.IndexReg = NewSRL;
1190   return false;
1191 }
1192 
1193 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1194                                               unsigned Depth) {
1195   SDLoc dl(N);
1196   DEBUG({
1197       dbgs() << "MatchAddress: ";
1198       AM.dump();
1199     });
1200   // Limit recursion.
1201   if (Depth > 5)
1202     return matchAddressBase(N, AM);
1203 
1204   // If this is already a %rip relative address, we can only merge immediates
1205   // into it.  Instead of handling this in every case, we handle it here.
1206   // RIP relative addressing: %rip + 32-bit displacement!
1207   if (AM.isRIPRelative()) {
1208     // FIXME: JumpTable and ExternalSymbol address currently don't like
1209     // displacements.  It isn't very important, but this should be fixed for
1210     // consistency.
1211     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1212       return true;
1213 
1214     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1215       if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1216         return false;
1217     return true;
1218   }
1219 
1220   switch (N.getOpcode()) {
1221   default: break;
1222   case ISD::LOCAL_RECOVER: {
1223     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1224       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1225         // Use the symbol and don't prefix it.
1226         AM.MCSym = ESNode->getMCSymbol();
1227         return false;
1228       }
1229     break;
1230   }
1231   case ISD::Constant: {
1232     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1233     if (!foldOffsetIntoAddress(Val, AM))
1234       return false;
1235     break;
1236   }
1237 
1238   case X86ISD::Wrapper:
1239   case X86ISD::WrapperRIP:
1240     if (!matchWrapper(N, AM))
1241       return false;
1242     break;
1243 
1244   case ISD::LOAD:
1245     if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1246       return false;
1247     break;
1248 
1249   case ISD::FrameIndex:
1250     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1251         AM.Base_Reg.getNode() == nullptr &&
1252         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1253       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1254       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1255       return false;
1256     }
1257     break;
1258 
1259   case ISD::SHL:
1260     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1261       break;
1262 
1263     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1264       unsigned Val = CN->getZExtValue();
1265       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1266       // that the base operand remains free for further matching. If
1267       // the base doesn't end up getting used, a post-processing step
1268       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1269       if (Val == 1 || Val == 2 || Val == 3) {
1270         AM.Scale = 1 << Val;
1271         SDValue ShVal = N.getOperand(0);
1272 
1273         // Okay, we know that we have a scale by now.  However, if the scaled
1274         // value is an add of something and a constant, we can fold the
1275         // constant into the disp field here.
1276         if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1277           AM.IndexReg = ShVal.getOperand(0);
1278           ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
1279           uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1280           if (!foldOffsetIntoAddress(Disp, AM))
1281             return false;
1282         }
1283 
1284         AM.IndexReg = ShVal;
1285         return false;
1286       }
1287     }
1288     break;
1289 
1290   case ISD::SRL: {
1291     // Scale must not be used already.
1292     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1293 
1294     SDValue And = N.getOperand(0);
1295     if (And.getOpcode() != ISD::AND) break;
1296     SDValue X = And.getOperand(0);
1297 
1298     // We only handle up to 64-bit values here as those are what matter for
1299     // addressing mode optimizations.
1300     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1301 
1302     // The mask used for the transform is expected to be post-shift, but we
1303     // found the shift first so just apply the shift to the mask before passing
1304     // it down.
1305     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1306         !isa<ConstantSDNode>(And.getOperand(1)))
1307       break;
1308     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1309 
1310     // Try to fold the mask and shift into the scale, and return false if we
1311     // succeed.
1312     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1313       return false;
1314     break;
1315   }
1316 
1317   case ISD::SMUL_LOHI:
1318   case ISD::UMUL_LOHI:
1319     // A mul_lohi where we need the low part can be folded as a plain multiply.
1320     if (N.getResNo() != 0) break;
1321     LLVM_FALLTHROUGH;
1322   case ISD::MUL:
1323   case X86ISD::MUL_IMM:
1324     // X*[3,5,9] -> X+X*[2,4,8]
1325     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1326         AM.Base_Reg.getNode() == nullptr &&
1327         AM.IndexReg.getNode() == nullptr) {
1328       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1329         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1330             CN->getZExtValue() == 9) {
1331           AM.Scale = unsigned(CN->getZExtValue())-1;
1332 
1333           SDValue MulVal = N.getOperand(0);
1334           SDValue Reg;
1335 
1336           // Okay, we know that we have a scale by now.  However, if the scaled
1337           // value is an add of something and a constant, we can fold the
1338           // constant into the disp field here.
1339           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1340               isa<ConstantSDNode>(MulVal.getOperand(1))) {
1341             Reg = MulVal.getOperand(0);
1342             ConstantSDNode *AddVal =
1343               cast<ConstantSDNode>(MulVal.getOperand(1));
1344             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1345             if (foldOffsetIntoAddress(Disp, AM))
1346               Reg = N.getOperand(0);
1347           } else {
1348             Reg = N.getOperand(0);
1349           }
1350 
1351           AM.IndexReg = AM.Base_Reg = Reg;
1352           return false;
1353         }
1354     }
1355     break;
1356 
1357   case ISD::SUB: {
1358     // Given A-B, if A can be completely folded into the address and
1359     // the index field with the index field unused, use -B as the index.
1360     // This is a win if a has multiple parts that can be folded into
1361     // the address. Also, this saves a mov if the base register has
1362     // other uses, since it avoids a two-address sub instruction, however
1363     // it costs an additional mov if the index register has other uses.
1364 
1365     // Add an artificial use to this node so that we can keep track of
1366     // it if it gets CSE'd with a different node.
1367     HandleSDNode Handle(N);
1368 
1369     // Test if the LHS of the sub can be folded.
1370     X86ISelAddressMode Backup = AM;
1371     if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
1372       AM = Backup;
1373       break;
1374     }
1375     // Test if the index field is free for use.
1376     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1377       AM = Backup;
1378       break;
1379     }
1380 
1381     int Cost = 0;
1382     SDValue RHS = Handle.getValue().getOperand(1);
1383     // If the RHS involves a register with multiple uses, this
1384     // transformation incurs an extra mov, due to the neg instruction
1385     // clobbering its operand.
1386     if (!RHS.getNode()->hasOneUse() ||
1387         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1388         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1389         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1390         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1391          RHS.getOperand(0).getValueType() == MVT::i32))
1392       ++Cost;
1393     // If the base is a register with multiple uses, this
1394     // transformation may save a mov.
1395     // FIXME: Don't rely on DELETED_NODEs.
1396     if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1397          AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
1398          !AM.Base_Reg.getNode()->hasOneUse()) ||
1399         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1400       --Cost;
1401     // If the folded LHS was interesting, this transformation saves
1402     // address arithmetic.
1403     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1404         ((AM.Disp != 0) && (Backup.Disp == 0)) +
1405         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1406       --Cost;
1407     // If it doesn't look like it may be an overall win, don't do it.
1408     if (Cost >= 0) {
1409       AM = Backup;
1410       break;
1411     }
1412 
1413     // Ok, the transformation is legal and appears profitable. Go for it.
1414     SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1415     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1416     AM.IndexReg = Neg;
1417     AM.Scale = 1;
1418 
1419     // Insert the new nodes into the topological ordering.
1420     insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1421     insertDAGNode(*CurDAG, Handle.getValue(), Neg);
1422     return false;
1423   }
1424 
1425   case ISD::ADD:
1426     if (!matchAdd(N, AM, Depth))
1427       return false;
1428     break;
1429 
1430   case ISD::OR:
1431     // We want to look through a transform in InstCombine and DAGCombiner that
1432     // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1433     // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1434     // An 'lea' can then be used to match the shift (multiply) and add:
1435     // and $1, %esi
1436     // lea (%rsi, %rdi, 8), %rax
1437     if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1438         !matchAdd(N, AM, Depth))
1439       return false;
1440     break;
1441 
1442   case ISD::AND: {
1443     // Perform some heroic transforms on an and of a constant-count shift
1444     // with a constant to enable use of the scaled offset field.
1445 
1446     // Scale must not be used already.
1447     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1448 
1449     SDValue Shift = N.getOperand(0);
1450     if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1451     SDValue X = Shift.getOperand(0);
1452 
1453     // We only handle up to 64-bit values here as those are what matter for
1454     // addressing mode optimizations.
1455     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1456 
1457     if (!isa<ConstantSDNode>(N.getOperand(1)))
1458       break;
1459     uint64_t Mask = N.getConstantOperandVal(1);
1460 
1461     // Try to fold the mask and shift into an extract and scale.
1462     if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1463       return false;
1464 
1465     // Try to fold the mask and shift directly into the scale.
1466     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1467       return false;
1468 
1469     // Try to swap the mask and shift to place shifts which can be done as
1470     // a scale on the outside of the mask.
1471     if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1472       return false;
1473     break;
1474   }
1475   }
1476 
1477   return matchAddressBase(N, AM);
1478 }
1479 
1480 /// Helper for MatchAddress. Add the specified node to the
1481 /// specified addressing mode without any further recursion.
1482 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1483   // Is the base register already occupied?
1484   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1485     // If so, check to see if the scale index register is set.
1486     if (!AM.IndexReg.getNode()) {
1487       AM.IndexReg = N;
1488       AM.Scale = 1;
1489       return false;
1490     }
1491 
1492     // Otherwise, we cannot select it.
1493     return true;
1494   }
1495 
1496   // Default, generate it as a register.
1497   AM.BaseType = X86ISelAddressMode::RegBase;
1498   AM.Base_Reg = N;
1499   return false;
1500 }
1501 
1502 template <class GatherScatterSDNode>
1503 bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1504     GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1505     SDValue &Index, SDValue &Disp, SDValue &Segment) {
1506   X86ISelAddressMode AM;
1507   unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1508   // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1509   if (AddrSpace == 256)
1510     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1511   if (AddrSpace == 257)
1512     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1513   if (AddrSpace == 258)
1514     AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1515 
1516   SDLoc DL(N);
1517   Base = Mgs->getBasePtr();
1518   Index = Mgs->getIndex();
1519   unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
1520   Scale = getI8Imm(ScalarSize/8, DL);
1521 
1522   // If Base is 0, the whole address is in index and the Scale is 1
1523   if (isa<ConstantSDNode>(Base)) {
1524     assert(cast<ConstantSDNode>(Base)->isNullValue() &&
1525            "Unexpected base in gather/scatter");
1526     Scale = getI8Imm(1, DL);
1527     Base = CurDAG->getRegister(0, MVT::i32);
1528   }
1529   if (AM.Segment.getNode())
1530     Segment = AM.Segment;
1531   else
1532     Segment = CurDAG->getRegister(0, MVT::i32);
1533   Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1534   return true;
1535 }
1536 
1537 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1538                                        SDValue &Scale, SDValue &Index,
1539                                        SDValue &Disp, SDValue &Segment) {
1540   if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1541     return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1542         Mgs, N, Base, Scale, Index, Disp, Segment);
1543   if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1544     return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1545         X86Gather, N, Base, Scale, Index, Disp, Segment);
1546   return false;
1547 }
1548 
1549 /// Returns true if it is able to pattern match an addressing mode.
1550 /// It returns the operands which make up the maximal addressing mode it can
1551 /// match by reference.
1552 ///
1553 /// Parent is the parent node of the addr operand that is being matched.  It
1554 /// is always a load, store, atomic node, or null.  It is only null when
1555 /// checking memory operands for inline asm nodes.
1556 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1557                                  SDValue &Scale, SDValue &Index,
1558                                  SDValue &Disp, SDValue &Segment) {
1559   X86ISelAddressMode AM;
1560 
1561   if (Parent &&
1562       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1563       // that are not a MemSDNode, and thus don't have proper addrspace info.
1564       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1565       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1566       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1567       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1568       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1569     unsigned AddrSpace =
1570       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1571     // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1572     if (AddrSpace == 256)
1573       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1574     if (AddrSpace == 257)
1575       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1576     if (AddrSpace == 258)
1577       AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1578   }
1579 
1580   if (matchAddress(N, AM))
1581     return false;
1582 
1583   MVT VT = N.getSimpleValueType();
1584   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1585     if (!AM.Base_Reg.getNode())
1586       AM.Base_Reg = CurDAG->getRegister(0, VT);
1587   }
1588 
1589   if (!AM.IndexReg.getNode())
1590     AM.IndexReg = CurDAG->getRegister(0, VT);
1591 
1592   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1593   return true;
1594 }
1595 
1596 // We can only fold a load if all nodes between it and the root node have a
1597 // single use. If there are additional uses, we could end up duplicating the
1598 // load.
1599 static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1600   SDNode *User = *N->use_begin();
1601   while (User != Root) {
1602     if (!User->hasOneUse())
1603       return false;
1604     User = *User->use_begin();
1605   }
1606 
1607   return true;
1608 }
1609 
1610 /// Match a scalar SSE load. In particular, we want to match a load whose top
1611 /// elements are either undef or zeros. The load flavor is derived from the
1612 /// type of N, which is either v4f32 or v2f64.
1613 ///
1614 /// We also return:
1615 ///   PatternChainNode: this is the matched node that has a chain input and
1616 ///   output.
1617 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
1618                                           SDValue N, SDValue &Base,
1619                                           SDValue &Scale, SDValue &Index,
1620                                           SDValue &Disp, SDValue &Segment,
1621                                           SDValue &PatternNodeWithChain) {
1622   // We can allow a full vector load here since narrowing a load is ok.
1623   if (ISD::isNON_EXTLoad(N.getNode())) {
1624     PatternNodeWithChain = N;
1625     if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1626         IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1627         hasSingleUsesFromRoot(Root, N.getNode())) {
1628       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1629       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1630                         Segment);
1631     }
1632   }
1633 
1634   // We can also match the special zero extended load opcode.
1635   if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1636     PatternNodeWithChain = N;
1637     if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1638         IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1639         hasSingleUsesFromRoot(Root, N.getNode())) {
1640       auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1641       return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1642                         Segment);
1643     }
1644   }
1645 
1646   // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1647   // once. Otherwise the load might get duplicated and the chain output of the
1648   // duplicate load will not be observed by all dependencies.
1649   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
1650     PatternNodeWithChain = N.getOperand(0);
1651     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1652         IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1653         IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1654         hasSingleUsesFromRoot(Root, N.getNode())) {
1655       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1656       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1657                         Segment);
1658     }
1659   }
1660 
1661   // Also handle the case where we explicitly require zeros in the top
1662   // elements.  This is a vector shuffle from the zero vector.
1663   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1664       // Check to see if the top elements are all zeros (or bitcast of zeros).
1665       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1666       N.getOperand(0).getNode()->hasOneUse()) {
1667     PatternNodeWithChain = N.getOperand(0).getOperand(0);
1668     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1669         IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1670         IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1671         hasSingleUsesFromRoot(Root, N.getNode())) {
1672       // Okay, this is a zero extending load.  Fold it.
1673       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1674       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1675                         Segment);
1676     }
1677   }
1678 
1679   return false;
1680 }
1681 
1682 
1683 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
1684   if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1685     uint64_t ImmVal = CN->getZExtValue();
1686     if (!isUInt<32>(ImmVal))
1687       return false;
1688 
1689     Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1690     return true;
1691   }
1692 
1693   // In static codegen with small code model, we can get the address of a label
1694   // into a register with 'movl'. TableGen has already made sure we're looking
1695   // at a label of some kind.
1696   assert(N->getOpcode() == X86ISD::Wrapper &&
1697          "Unexpected node type for MOV32ri64");
1698   N = N.getOperand(0);
1699 
1700   // At least GNU as does not accept 'movl' for TPOFF relocations.
1701   // FIXME: We could use 'movl' when we know we are targeting MC.
1702   if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
1703     return false;
1704 
1705   Imm = N;
1706   if (N->getOpcode() != ISD::TargetGlobalAddress)
1707     return TM.getCodeModel() == CodeModel::Small;
1708 
1709   Optional<ConstantRange> CR =
1710       cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1711   if (!CR)
1712     return TM.getCodeModel() == CodeModel::Small;
1713 
1714   return CR->getUnsignedMax().ult(1ull << 32);
1715 }
1716 
1717 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
1718                                          SDValue &Scale, SDValue &Index,
1719                                          SDValue &Disp, SDValue &Segment) {
1720   // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1721   SDLoc DL(N);
1722 
1723   if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1724     return false;
1725 
1726   RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1727   if (RN && RN->getReg() == 0)
1728     Base = CurDAG->getRegister(0, MVT::i64);
1729   else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1730     // Base could already be %rip, particularly in the x32 ABI.
1731     Base = SDValue(CurDAG->getMachineNode(
1732                        TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1733                        CurDAG->getTargetConstant(0, DL, MVT::i64),
1734                        Base,
1735                        CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1736                    0);
1737   }
1738 
1739   RN = dyn_cast<RegisterSDNode>(Index);
1740   if (RN && RN->getReg() == 0)
1741     Index = CurDAG->getRegister(0, MVT::i64);
1742   else {
1743     assert(Index.getValueType() == MVT::i32 &&
1744            "Expect to be extending 32-bit registers for use in LEA");
1745     Index = SDValue(CurDAG->getMachineNode(
1746                         TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1747                         CurDAG->getTargetConstant(0, DL, MVT::i64),
1748                         Index,
1749                         CurDAG->getTargetConstant(X86::sub_32bit, DL,
1750                                                   MVT::i32)),
1751                     0);
1752   }
1753 
1754   return true;
1755 }
1756 
1757 /// Calls SelectAddr and determines if the maximal addressing
1758 /// mode it matches can be cost effectively emitted as an LEA instruction.
1759 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
1760                                     SDValue &Base, SDValue &Scale,
1761                                     SDValue &Index, SDValue &Disp,
1762                                     SDValue &Segment) {
1763   X86ISelAddressMode AM;
1764 
1765   // Save the DL and VT before calling matchAddress, it can invalidate N.
1766   SDLoc DL(N);
1767   MVT VT = N.getSimpleValueType();
1768 
1769   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1770   // segments.
1771   SDValue Copy = AM.Segment;
1772   SDValue T = CurDAG->getRegister(0, MVT::i32);
1773   AM.Segment = T;
1774   if (matchAddress(N, AM))
1775     return false;
1776   assert (T == AM.Segment);
1777   AM.Segment = Copy;
1778 
1779   unsigned Complexity = 0;
1780   if (AM.BaseType == X86ISelAddressMode::RegBase)
1781     if (AM.Base_Reg.getNode())
1782       Complexity = 1;
1783     else
1784       AM.Base_Reg = CurDAG->getRegister(0, VT);
1785   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1786     Complexity = 4;
1787 
1788   if (AM.IndexReg.getNode())
1789     Complexity++;
1790   else
1791     AM.IndexReg = CurDAG->getRegister(0, VT);
1792 
1793   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1794   // a simple shift.
1795   if (AM.Scale > 1)
1796     Complexity++;
1797 
1798   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1799   // to a LEA. This is determined with some experimentation but is by no means
1800   // optimal (especially for code size consideration). LEA is nice because of
1801   // its three-address nature. Tweak the cost function again when we can run
1802   // convertToThreeAddress() at register allocation time.
1803   if (AM.hasSymbolicDisplacement()) {
1804     // For X86-64, always use LEA to materialize RIP-relative addresses.
1805     if (Subtarget->is64Bit())
1806       Complexity = 4;
1807     else
1808       Complexity += 2;
1809   }
1810 
1811   if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1812     Complexity++;
1813 
1814   // If it isn't worth using an LEA, reject it.
1815   if (Complexity <= 2)
1816     return false;
1817 
1818   getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
1819   return true;
1820 }
1821 
1822 /// This is only run on TargetGlobalTLSAddress nodes.
1823 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
1824                                         SDValue &Scale, SDValue &Index,
1825                                         SDValue &Disp, SDValue &Segment) {
1826   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1827   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1828 
1829   X86ISelAddressMode AM;
1830   AM.GV = GA->getGlobal();
1831   AM.Disp += GA->getOffset();
1832   AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1833   AM.SymbolFlags = GA->getTargetFlags();
1834 
1835   if (N.getValueType() == MVT::i32) {
1836     AM.Scale = 1;
1837     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1838   } else {
1839     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1840   }
1841 
1842   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1843   return true;
1844 }
1845 
1846 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1847   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1848     Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1849                                    N.getValueType());
1850     return true;
1851   }
1852 
1853   // Keep track of the original value type and whether this value was
1854   // truncated. If we see a truncation from pointer type to VT that truncates
1855   // bits that are known to be zero, we can use a narrow reference.
1856   EVT VT = N.getValueType();
1857   bool WasTruncated = false;
1858   if (N.getOpcode() == ISD::TRUNCATE) {
1859     WasTruncated = true;
1860     N = N.getOperand(0);
1861   }
1862 
1863   if (N.getOpcode() != X86ISD::Wrapper)
1864     return false;
1865 
1866   // We can only use non-GlobalValues as immediates if they were not truncated,
1867   // as we do not have any range information. If we have a GlobalValue and the
1868   // address was not truncated, we can select it as an operand directly.
1869   unsigned Opc = N.getOperand(0)->getOpcode();
1870   if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1871     Op = N.getOperand(0);
1872     // We can only select the operand directly if we didn't have to look past a
1873     // truncate.
1874     return !WasTruncated;
1875   }
1876 
1877   // Check that the global's range fits into VT.
1878   auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1879   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1880   if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1881     return false;
1882 
1883   // Okay, we can use a narrow reference.
1884   Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1885                                       GA->getOffset(), GA->getTargetFlags());
1886   return true;
1887 }
1888 
1889 bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
1890                                   SDValue &Base, SDValue &Scale,
1891                                   SDValue &Index, SDValue &Disp,
1892                                   SDValue &Segment) {
1893   if (!ISD::isNON_EXTLoad(N.getNode()) ||
1894       !IsProfitableToFold(N, P, P) ||
1895       !IsLegalToFold(N, P, P, OptLevel))
1896     return false;
1897 
1898   return selectAddr(N.getNode(),
1899                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
1900 }
1901 
1902 /// Return an SDNode that returns the value of the global base register.
1903 /// Output instructions required to initialize the global base register,
1904 /// if necessary.
1905 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1906   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1907   auto &DL = MF->getDataLayout();
1908   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1909 }
1910 
1911 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1912   if (N->getOpcode() == ISD::TRUNCATE)
1913     N = N->getOperand(0).getNode();
1914   if (N->getOpcode() != X86ISD::Wrapper)
1915     return false;
1916 
1917   auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1918   if (!GA)
1919     return false;
1920 
1921   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1922   return CR && CR->getSignedMin().sge(-1ull << Width) &&
1923          CR->getSignedMax().slt(1ull << Width);
1924 }
1925 
1926 /// Test whether the given X86ISD::CMP node has any uses which require the SF
1927 /// or OF bits to be accurate.
1928 static bool hasNoSignedComparisonUses(SDNode *N) {
1929   // Examine each user of the node.
1930   for (SDNode::use_iterator UI = N->use_begin(),
1931          UE = N->use_end(); UI != UE; ++UI) {
1932     // Only examine CopyToReg uses.
1933     if (UI->getOpcode() != ISD::CopyToReg)
1934       return false;
1935     // Only examine CopyToReg uses that copy to EFLAGS.
1936     if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1937           X86::EFLAGS)
1938       return false;
1939     // Examine each user of the CopyToReg use.
1940     for (SDNode::use_iterator FlagUI = UI->use_begin(),
1941            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1942       // Only examine the Flag result.
1943       if (FlagUI.getUse().getResNo() != 1) continue;
1944       // Anything unusual: assume conservatively.
1945       if (!FlagUI->isMachineOpcode()) return false;
1946       // Examine the opcode of the user.
1947       switch (FlagUI->getMachineOpcode()) {
1948       // These comparisons don't treat the most significant bit specially.
1949       case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1950       case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1951       case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1952       case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1953       case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1954       case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1955       case X86::CMOVA16rr: case X86::CMOVA16rm:
1956       case X86::CMOVA32rr: case X86::CMOVA32rm:
1957       case X86::CMOVA64rr: case X86::CMOVA64rm:
1958       case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1959       case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1960       case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1961       case X86::CMOVB16rr: case X86::CMOVB16rm:
1962       case X86::CMOVB32rr: case X86::CMOVB32rm:
1963       case X86::CMOVB64rr: case X86::CMOVB64rm:
1964       case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1965       case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1966       case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1967       case X86::CMOVE16rr: case X86::CMOVE16rm:
1968       case X86::CMOVE32rr: case X86::CMOVE32rm:
1969       case X86::CMOVE64rr: case X86::CMOVE64rm:
1970       case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1971       case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1972       case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1973       case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1974       case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1975       case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1976       case X86::CMOVP16rr: case X86::CMOVP16rm:
1977       case X86::CMOVP32rr: case X86::CMOVP32rm:
1978       case X86::CMOVP64rr: case X86::CMOVP64rm:
1979         continue;
1980       // Anything else: assume conservatively.
1981       default: return false;
1982       }
1983     }
1984   }
1985   return true;
1986 }
1987 
1988 /// Test whether the given node which sets flags has any uses which require the
1989 /// CF flag to be accurate.
1990 static bool hasNoCarryFlagUses(SDNode *N) {
1991   // Examine each user of the node.
1992   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
1993        ++UI) {
1994     // Only check things that use the flags.
1995     if (UI.getUse().getResNo() != 1)
1996       continue;
1997     // Only examine CopyToReg uses.
1998     if (UI->getOpcode() != ISD::CopyToReg)
1999       return false;
2000     // Only examine CopyToReg uses that copy to EFLAGS.
2001     if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2002       return false;
2003     // Examine each user of the CopyToReg use.
2004     for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2005          FlagUI != FlagUE; ++FlagUI) {
2006       // Only examine the Flag result.
2007       if (FlagUI.getUse().getResNo() != 1)
2008         continue;
2009       // Anything unusual: assume conservatively.
2010       if (!FlagUI->isMachineOpcode())
2011         return false;
2012       // Examine the opcode of the user.
2013       switch (FlagUI->getMachineOpcode()) {
2014       // Comparisons which don't examine the CF flag.
2015       case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2016       case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2017       case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2018       case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2019       case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2020       case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2021       case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2022       case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2023       case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2024       case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2025       case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2026       case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2027       case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2028       case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2029       case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2030       case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2031       case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2032       case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2033       case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2034       case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2035       case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2036       case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2037       case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2038       case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2039       case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2040       case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2041       case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2042       case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2043       case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2044       case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2045         continue;
2046       // Anything else: assume conservatively.
2047       default:
2048         return false;
2049       }
2050     }
2051   }
2052   return true;
2053 }
2054 
2055 /// Check whether or not the chain ending in StoreNode is suitable for doing
2056 /// the {load; op; store} to modify transformation.
2057 static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2058                                         SDValue StoredVal, SelectionDAG *CurDAG,
2059                                         LoadSDNode *&LoadNode,
2060                                         SDValue &InputChain) {
2061   // is the stored value result 0 of the load?
2062   if (StoredVal.getResNo() != 0) return false;
2063 
2064   // are there other uses of the loaded value than the inc or dec?
2065   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2066 
2067   // is the store non-extending and non-indexed?
2068   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2069     return false;
2070 
2071   SDValue Load = StoredVal->getOperand(0);
2072   // Is the stored value a non-extending and non-indexed load?
2073   if (!ISD::isNormalLoad(Load.getNode())) return false;
2074 
2075   // Return LoadNode by reference.
2076   LoadNode = cast<LoadSDNode>(Load);
2077 
2078   // Is store the only read of the loaded value?
2079   if (!Load.hasOneUse())
2080     return false;
2081 
2082   // Is the address of the store the same as the load?
2083   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2084       LoadNode->getOffset() != StoreNode->getOffset())
2085     return false;
2086 
2087   // Check if the chain is produced by the load or is a TokenFactor with
2088   // the load output chain as an operand. Return InputChain by reference.
2089   SDValue Chain = StoreNode->getChain();
2090 
2091   bool ChainCheck = false;
2092   if (Chain == Load.getValue(1)) {
2093     ChainCheck = true;
2094     InputChain = LoadNode->getChain();
2095   } else if (Chain.getOpcode() == ISD::TokenFactor) {
2096     SmallVector<SDValue, 4> ChainOps;
2097     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2098       SDValue Op = Chain.getOperand(i);
2099       if (Op == Load.getValue(1)) {
2100         ChainCheck = true;
2101         // Drop Load, but keep its chain. No cycle check necessary.
2102         ChainOps.push_back(Load.getOperand(0));
2103         continue;
2104       }
2105 
2106       // Make sure using Op as part of the chain would not cause a cycle here.
2107       // In theory, we could check whether the chain node is a predecessor of
2108       // the load. But that can be very expensive. Instead visit the uses and
2109       // make sure they all have smaller node id than the load.
2110       int LoadId = LoadNode->getNodeId();
2111       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2112              UE = UI->use_end(); UI != UE; ++UI) {
2113         if (UI.getUse().getResNo() != 0)
2114           continue;
2115         if (UI->getNodeId() > LoadId)
2116           return false;
2117       }
2118 
2119       ChainOps.push_back(Op);
2120     }
2121 
2122     if (ChainCheck)
2123       // Make a new TokenFactor with all the other input chains except
2124       // for the load.
2125       InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
2126                                    MVT::Other, ChainOps);
2127   }
2128   if (!ChainCheck)
2129     return false;
2130 
2131   return true;
2132 }
2133 
2134 // Change a chain of {load; op; store} of the same value into a simple op
2135 // through memory of that value, if the uses of the modified value and its
2136 // address are suitable.
2137 //
2138 // The tablegen pattern memory operand pattern is currently not able to match
2139 // the case where the EFLAGS on the original operation are used.
2140 //
2141 // To move this to tablegen, we'll need to improve tablegen to allow flags to
2142 // be transferred from a node in the pattern to the result node, probably with
2143 // a new keyword. For example, we have this
2144 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2145 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2146 //   (implicit EFLAGS)]>;
2147 // but maybe need something like this
2148 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2149 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2150 //   (transferrable EFLAGS)]>;
2151 //
2152 // Until then, we manually fold these and instruction select the operation
2153 // here.
2154 bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2155   StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2156   SDValue StoredVal = StoreNode->getOperand(1);
2157   unsigned Opc = StoredVal->getOpcode();
2158 
2159   // Before we try to select anything, make sure this is memory operand size
2160   // and opcode we can handle. Note that this must match the code below that
2161   // actually lowers the opcodes.
2162   EVT MemVT = StoreNode->getMemoryVT();
2163   if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2164       MemVT != MVT::i8)
2165     return false;
2166   switch (Opc) {
2167   default:
2168     return false;
2169   case X86ISD::INC:
2170   case X86ISD::DEC:
2171   case X86ISD::ADD:
2172   case X86ISD::SUB:
2173   case X86ISD::AND:
2174   case X86ISD::OR:
2175   case X86ISD::XOR:
2176     break;
2177   }
2178 
2179   LoadSDNode *LoadNode = nullptr;
2180   SDValue InputChain;
2181   if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2182                                    InputChain))
2183     return false;
2184 
2185   SDValue Base, Scale, Index, Disp, Segment;
2186   if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2187                   Segment))
2188     return false;
2189 
2190   auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
2191                           unsigned Opc8) {
2192     switch (MemVT.getSimpleVT().SimpleTy) {
2193     case MVT::i64:
2194       return Opc64;
2195     case MVT::i32:
2196       return Opc32;
2197     case MVT::i16:
2198       return Opc16;
2199     case MVT::i8:
2200       return Opc8;
2201     default:
2202       llvm_unreachable("Invalid size!");
2203     }
2204   };
2205 
2206   MachineSDNode *Result;
2207   switch (Opc) {
2208   case X86ISD::INC:
2209   case X86ISD::DEC: {
2210     unsigned NewOpc =
2211         Opc == X86ISD::INC
2212             ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2213             : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
2214     const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2215     Result =
2216         CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2217     break;
2218   }
2219   case X86ISD::ADD:
2220   case X86ISD::SUB:
2221   case X86ISD::AND:
2222   case X86ISD::OR:
2223   case X86ISD::XOR: {
2224     auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2225       switch (Opc) {
2226       case X86ISD::ADD:
2227         return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2228                             X86::ADD8mr);
2229       case X86ISD::SUB:
2230         return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2231                             X86::SUB8mr);
2232       case X86ISD::AND:
2233         return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2234                             X86::AND8mr);
2235       case X86ISD::OR:
2236         return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2237       case X86ISD::XOR:
2238         return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2239                             X86::XOR8mr);
2240       default:
2241         llvm_unreachable("Invalid opcode!");
2242       }
2243     };
2244     auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2245       switch (Opc) {
2246       case X86ISD::ADD:
2247         return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
2248       case X86ISD::SUB:
2249         return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
2250       case X86ISD::AND:
2251         return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
2252       case X86ISD::OR:
2253         return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
2254       case X86ISD::XOR:
2255         return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
2256       default:
2257         llvm_unreachable("Invalid opcode!");
2258       }
2259     };
2260     auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2261       switch (Opc) {
2262       case X86ISD::ADD:
2263         return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2264                             X86::ADD8mi);
2265       case X86ISD::SUB:
2266         return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2267                             X86::SUB8mi);
2268       case X86ISD::AND:
2269         return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2270                             X86::AND8mi);
2271       case X86ISD::OR:
2272         return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2273                             X86::OR8mi);
2274       case X86ISD::XOR:
2275         return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2276                             X86::XOR8mi);
2277       default:
2278         llvm_unreachable("Invalid opcode!");
2279       }
2280     };
2281 
2282     unsigned NewOpc = SelectRegOpcode(Opc);
2283     SDValue Operand = StoredVal->getOperand(1);
2284 
2285     // See if the operand is a constant that we can fold into an immediate
2286     // operand.
2287     if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2288       auto OperandV = OperandC->getAPIntValue();
2289 
2290       // Check if we can shrink the operand enough to fit in an immediate (or
2291       // fit into a smaller immediate) by negating it and switching the
2292       // operation.
2293       if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2294           ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
2295             (-OperandV).getMinSignedBits() <= 8) ||
2296            (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2297             (-OperandV).getMinSignedBits() <= 32)) &&
2298           hasNoCarryFlagUses(StoredVal.getNode())) {
2299         OperandV = -OperandV;
2300         Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2301       }
2302 
2303       // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2304       // the larger immediate operand.
2305       if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2306         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2307         NewOpc = SelectImm8Opcode(Opc);
2308       } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2309                  (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2310         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2311         NewOpc = SelectImmOpcode(Opc);
2312       }
2313     }
2314 
2315     const SDValue Ops[] = {Base,    Scale,   Index,     Disp,
2316                            Segment, Operand, InputChain};
2317     Result =
2318         CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2319     break;
2320   }
2321   default:
2322     llvm_unreachable("Invalid opcode!");
2323   }
2324 
2325   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2326   MemOp[0] = StoreNode->getMemOperand();
2327   MemOp[1] = LoadNode->getMemOperand();
2328   Result->setMemRefs(MemOp, MemOp + 2);
2329 
2330   ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2331   ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2332   CurDAG->RemoveDeadNode(Node);
2333   return true;
2334 }
2335 
2336 // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2337 bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2338   MVT NVT = Node->getSimpleValueType(0);
2339   SDLoc dl(Node);
2340 
2341   SDValue N0 = Node->getOperand(0);
2342   SDValue N1 = Node->getOperand(1);
2343 
2344   if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2345     return false;
2346 
2347   // Must have a shift right.
2348   if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2349     return false;
2350 
2351   // Shift can't have additional users.
2352   if (!N0->hasOneUse())
2353     return false;
2354 
2355   // Only supported for 32 and 64 bits.
2356   if (NVT != MVT::i32 && NVT != MVT::i64)
2357     return false;
2358 
2359   // Shift amount and RHS of and must be constant.
2360   ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2361   ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2362   if (!MaskCst || !ShiftCst)
2363     return false;
2364 
2365   // And RHS must be a mask.
2366   uint64_t Mask = MaskCst->getZExtValue();
2367   if (!isMask_64(Mask))
2368     return false;
2369 
2370   uint64_t Shift = ShiftCst->getZExtValue();
2371   uint64_t MaskSize = countPopulation(Mask);
2372 
2373   // Don't interfere with something that can be handled by extracting AH.
2374   // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2375   if (Shift == 8 && MaskSize == 8)
2376     return false;
2377 
2378   // Make sure we are only using bits that were in the original value, not
2379   // shifted in.
2380   if (Shift + MaskSize > NVT.getSizeInBits())
2381     return false;
2382 
2383   SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
2384   unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
2385   unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
2386 
2387   // BMI requires the immediate to placed in a register.
2388   if (!Subtarget->hasTBM()) {
2389     ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
2390     MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
2391     New = SDValue(CurDAG->getMachineNode(X86::MOV32ri, dl, NVT, New), 0);
2392     if (NVT == MVT::i64) {
2393       New =
2394           SDValue(CurDAG->getMachineNode(
2395                       TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2396                       CurDAG->getTargetConstant(0, dl, MVT::i64), New,
2397                       CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
2398                   0);
2399     }
2400   }
2401 
2402   MachineSDNode *NewNode;
2403   SDValue Input = N0->getOperand(0);
2404   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2405   if (tryFoldLoad(Node, Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2406     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
2407     SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
2408     NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2409     // Update the chain.
2410     ReplaceUses(N1.getValue(1), SDValue(NewNode, 1));
2411     // Record the mem-refs
2412     LoadSDNode *LoadNode = cast<LoadSDNode>(Input);
2413     if (LoadNode) {
2414       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2415       MemOp[0] = LoadNode->getMemOperand();
2416       NewNode->setMemRefs(MemOp, MemOp + 1);
2417     }
2418   } else {
2419     NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
2420   }
2421 
2422   ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
2423   CurDAG->RemoveDeadNode(Node);
2424   return true;
2425 }
2426 
2427 void X86DAGToDAGISel::Select(SDNode *Node) {
2428   MVT NVT = Node->getSimpleValueType(0);
2429   unsigned Opc, MOpc;
2430   unsigned Opcode = Node->getOpcode();
2431   SDLoc dl(Node);
2432 
2433   DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2434 
2435   if (Node->isMachineOpcode()) {
2436     DEBUG(dbgs() << "== ";  Node->dump(CurDAG); dbgs() << '\n');
2437     Node->setNodeId(-1);
2438     return;   // Already selected.
2439   }
2440 
2441   switch (Opcode) {
2442   default: break;
2443   case ISD::BRIND: {
2444     if (Subtarget->isTargetNaCl())
2445       // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2446       // leave the instruction alone.
2447       break;
2448     if (Subtarget->isTarget64BitILP32()) {
2449       // Converts a 32-bit register to a 64-bit, zero-extended version of
2450       // it. This is needed because x86-64 can do many things, but jmp %r32
2451       // ain't one of them.
2452       const SDValue &Target = Node->getOperand(1);
2453       assert(Target.getSimpleValueType() == llvm::MVT::i32);
2454       SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2455       SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2456                                       Node->getOperand(0), ZextTarget);
2457       ReplaceNode(Node, Brind.getNode());
2458       SelectCode(ZextTarget.getNode());
2459       SelectCode(Brind.getNode());
2460       return;
2461     }
2462     break;
2463   }
2464   case X86ISD::GlobalBaseReg:
2465     ReplaceNode(Node, getGlobalBaseReg());
2466     return;
2467 
2468   case X86ISD::SELECT:
2469   case X86ISD::SHRUNKBLEND: {
2470     // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
2471     SDValue VSelect = CurDAG->getNode(
2472         ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2473         Node->getOperand(1), Node->getOperand(2));
2474     ReplaceNode(Node, VSelect.getNode());
2475     SelectCode(VSelect.getNode());
2476     // We already called ReplaceUses.
2477     return;
2478   }
2479 
2480   case ISD::AND:
2481     // Try to match BEXTR/BEXTRI instruction.
2482     if (matchBEXTRFromAnd(Node))
2483       return;
2484 
2485     LLVM_FALLTHROUGH;
2486   case ISD::OR:
2487   case ISD::XOR: {
2488 
2489     // For operations of the form (x << C1) op C2, check if we can use a smaller
2490     // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2491     SDValue N0 = Node->getOperand(0);
2492     SDValue N1 = Node->getOperand(1);
2493 
2494     if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2495       break;
2496 
2497     // i8 is unshrinkable, i16 should be promoted to i32.
2498     if (NVT != MVT::i32 && NVT != MVT::i64)
2499       break;
2500 
2501     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2502     ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2503     if (!Cst || !ShlCst)
2504       break;
2505 
2506     int64_t Val = Cst->getSExtValue();
2507     uint64_t ShlVal = ShlCst->getZExtValue();
2508 
2509     // Make sure that we don't change the operation by removing bits.
2510     // This only matters for OR and XOR, AND is unaffected.
2511     uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2512     if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2513       break;
2514 
2515     unsigned ShlOp, AddOp, Op;
2516     MVT CstVT = NVT;
2517 
2518     // Check the minimum bitwidth for the new constant.
2519     // TODO: AND32ri is the same as AND64ri32 with zext imm.
2520     // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2521     // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2522     if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2523       CstVT = MVT::i8;
2524     else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2525       CstVT = MVT::i32;
2526 
2527     // Bail if there is no smaller encoding.
2528     if (NVT == CstVT)
2529       break;
2530 
2531     switch (NVT.SimpleTy) {
2532     default: llvm_unreachable("Unsupported VT!");
2533     case MVT::i32:
2534       assert(CstVT == MVT::i8);
2535       ShlOp = X86::SHL32ri;
2536       AddOp = X86::ADD32rr;
2537 
2538       switch (Opcode) {
2539       default: llvm_unreachable("Impossible opcode");
2540       case ISD::AND: Op = X86::AND32ri8; break;
2541       case ISD::OR:  Op =  X86::OR32ri8; break;
2542       case ISD::XOR: Op = X86::XOR32ri8; break;
2543       }
2544       break;
2545     case MVT::i64:
2546       assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2547       ShlOp = X86::SHL64ri;
2548       AddOp = X86::ADD64rr;
2549 
2550       switch (Opcode) {
2551       default: llvm_unreachable("Impossible opcode");
2552       case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2553       case ISD::OR:  Op = CstVT==MVT::i8?  X86::OR64ri8 :  X86::OR64ri32; break;
2554       case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2555       }
2556       break;
2557     }
2558 
2559     // Emit the smaller op and the shift.
2560     SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2561     SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2562     if (ShlVal == 1)
2563       CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2564                            SDValue(New, 0));
2565     else
2566       CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2567                            getI8Imm(ShlVal, dl));
2568     return;
2569   }
2570   case X86ISD::UMUL8:
2571   case X86ISD::SMUL8: {
2572     SDValue N0 = Node->getOperand(0);
2573     SDValue N1 = Node->getOperand(1);
2574 
2575     Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2576 
2577     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2578                                           N0, SDValue()).getValue(1);
2579 
2580     SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2581     SDValue Ops[] = {N1, InFlag};
2582     SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2583 
2584     ReplaceNode(Node, CNode);
2585     return;
2586   }
2587 
2588   case X86ISD::UMUL: {
2589     SDValue N0 = Node->getOperand(0);
2590     SDValue N1 = Node->getOperand(1);
2591 
2592     unsigned LoReg;
2593     switch (NVT.SimpleTy) {
2594     default: llvm_unreachable("Unsupported VT!");
2595     // MVT::i8 is handled by X86ISD::UMUL8.
2596     case MVT::i16: LoReg = X86::AX;  Opc = X86::MUL16r; break;
2597     case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2598     case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2599     }
2600 
2601     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2602                                           N0, SDValue()).getValue(1);
2603 
2604     SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2605     SDValue Ops[] = {N1, InFlag};
2606     SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2607 
2608     ReplaceNode(Node, CNode);
2609     return;
2610   }
2611 
2612   case ISD::SMUL_LOHI:
2613   case ISD::UMUL_LOHI: {
2614     SDValue N0 = Node->getOperand(0);
2615     SDValue N1 = Node->getOperand(1);
2616 
2617     bool isSigned = Opcode == ISD::SMUL_LOHI;
2618     bool hasBMI2 = Subtarget->hasBMI2();
2619     if (!isSigned) {
2620       switch (NVT.SimpleTy) {
2621       default: llvm_unreachable("Unsupported VT!");
2622       case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
2623       case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2624       case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2625                      MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2626       case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2627                      MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2628       }
2629     } else {
2630       switch (NVT.SimpleTy) {
2631       default: llvm_unreachable("Unsupported VT!");
2632       case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
2633       case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2634       case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2635       case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2636       }
2637     }
2638 
2639     unsigned SrcReg, LoReg, HiReg;
2640     switch (Opc) {
2641     default: llvm_unreachable("Unknown MUL opcode!");
2642     case X86::IMUL8r:
2643     case X86::MUL8r:
2644       SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2645       break;
2646     case X86::IMUL16r:
2647     case X86::MUL16r:
2648       SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2649       break;
2650     case X86::IMUL32r:
2651     case X86::MUL32r:
2652       SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2653       break;
2654     case X86::IMUL64r:
2655     case X86::MUL64r:
2656       SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2657       break;
2658     case X86::MULX32rr:
2659       SrcReg = X86::EDX; LoReg = HiReg = 0;
2660       break;
2661     case X86::MULX64rr:
2662       SrcReg = X86::RDX; LoReg = HiReg = 0;
2663       break;
2664     }
2665 
2666     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2667     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2668     // Multiply is commmutative.
2669     if (!foldedLoad) {
2670       foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2671       if (foldedLoad)
2672         std::swap(N0, N1);
2673     }
2674 
2675     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2676                                           N0, SDValue()).getValue(1);
2677     SDValue ResHi, ResLo;
2678 
2679     if (foldedLoad) {
2680       SDValue Chain;
2681       MachineSDNode *CNode = nullptr;
2682       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2683                         InFlag };
2684       if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2685         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2686         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2687         ResHi = SDValue(CNode, 0);
2688         ResLo = SDValue(CNode, 1);
2689         Chain = SDValue(CNode, 2);
2690         InFlag = SDValue(CNode, 3);
2691       } else {
2692         SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2693         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2694         Chain = SDValue(CNode, 0);
2695         InFlag = SDValue(CNode, 1);
2696       }
2697 
2698       // Update the chain.
2699       ReplaceUses(N1.getValue(1), Chain);
2700       // Record the mem-refs
2701       LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2702       if (LoadNode) {
2703         MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2704         MemOp[0] = LoadNode->getMemOperand();
2705         CNode->setMemRefs(MemOp, MemOp + 1);
2706       }
2707     } else {
2708       SDValue Ops[] = { N1, InFlag };
2709       if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2710         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2711         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2712         ResHi = SDValue(CNode, 0);
2713         ResLo = SDValue(CNode, 1);
2714         InFlag = SDValue(CNode, 2);
2715       } else {
2716         SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2717         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2718         InFlag = SDValue(CNode, 0);
2719       }
2720     }
2721 
2722     // Prevent use of AH in a REX instruction by referencing AX instead.
2723     if (HiReg == X86::AH && Subtarget->is64Bit() &&
2724         !SDValue(Node, 1).use_empty()) {
2725       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2726                                               X86::AX, MVT::i16, InFlag);
2727       InFlag = Result.getValue(2);
2728       // Get the low part if needed. Don't use getCopyFromReg for aliasing
2729       // registers.
2730       if (!SDValue(Node, 0).use_empty())
2731         ReplaceUses(SDValue(Node, 1),
2732           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2733 
2734       // Shift AX down 8 bits.
2735       Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2736                                               Result,
2737                                      CurDAG->getTargetConstant(8, dl, MVT::i8)),
2738                        0);
2739       // Then truncate it down to i8.
2740       ReplaceUses(SDValue(Node, 1),
2741         CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2742     }
2743     // Copy the low half of the result, if it is needed.
2744     if (!SDValue(Node, 0).use_empty()) {
2745       if (!ResLo.getNode()) {
2746         assert(LoReg && "Register for low half is not defined!");
2747         ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2748                                        InFlag);
2749         InFlag = ResLo.getValue(2);
2750       }
2751       ReplaceUses(SDValue(Node, 0), ResLo);
2752       DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2753     }
2754     // Copy the high half of the result, if it is needed.
2755     if (!SDValue(Node, 1).use_empty()) {
2756       if (!ResHi.getNode()) {
2757         assert(HiReg && "Register for high half is not defined!");
2758         ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2759                                        InFlag);
2760         InFlag = ResHi.getValue(2);
2761       }
2762       ReplaceUses(SDValue(Node, 1), ResHi);
2763       DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2764     }
2765 
2766     CurDAG->RemoveDeadNode(Node);
2767     return;
2768   }
2769 
2770   case ISD::SDIVREM:
2771   case ISD::UDIVREM:
2772   case X86ISD::SDIVREM8_SEXT_HREG:
2773   case X86ISD::UDIVREM8_ZEXT_HREG: {
2774     SDValue N0 = Node->getOperand(0);
2775     SDValue N1 = Node->getOperand(1);
2776 
2777     bool isSigned = (Opcode == ISD::SDIVREM ||
2778                      Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2779     if (!isSigned) {
2780       switch (NVT.SimpleTy) {
2781       default: llvm_unreachable("Unsupported VT!");
2782       case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
2783       case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2784       case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2785       case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2786       }
2787     } else {
2788       switch (NVT.SimpleTy) {
2789       default: llvm_unreachable("Unsupported VT!");
2790       case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
2791       case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2792       case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2793       case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2794       }
2795     }
2796 
2797     unsigned LoReg, HiReg, ClrReg;
2798     unsigned SExtOpcode;
2799     switch (NVT.SimpleTy) {
2800     default: llvm_unreachable("Unsupported VT!");
2801     case MVT::i8:
2802       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
2803       SExtOpcode = X86::CBW;
2804       break;
2805     case MVT::i16:
2806       LoReg = X86::AX;  HiReg = X86::DX;
2807       ClrReg = X86::DX;
2808       SExtOpcode = X86::CWD;
2809       break;
2810     case MVT::i32:
2811       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2812       SExtOpcode = X86::CDQ;
2813       break;
2814     case MVT::i64:
2815       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2816       SExtOpcode = X86::CQO;
2817       break;
2818     }
2819 
2820     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2821     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2822     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2823 
2824     SDValue InFlag;
2825     if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2826       // Special case for div8, just use a move with zero extension to AX to
2827       // clear the upper 8 bits (AH).
2828       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2829       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2830         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2831         Move =
2832           SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2833                                          MVT::Other, Ops), 0);
2834         Chain = Move.getValue(1);
2835         ReplaceUses(N0.getValue(1), Chain);
2836       } else {
2837         Move =
2838           SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2839         Chain = CurDAG->getEntryNode();
2840       }
2841       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2842       InFlag = Chain.getValue(1);
2843     } else {
2844       InFlag =
2845         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2846                              LoReg, N0, SDValue()).getValue(1);
2847       if (isSigned && !signBitIsZero) {
2848         // Sign extend the low part into the high part.
2849         InFlag =
2850           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2851       } else {
2852         // Zero out the high part, effectively zero extending the input.
2853         SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2854         switch (NVT.SimpleTy) {
2855         case MVT::i16:
2856           ClrNode =
2857               SDValue(CurDAG->getMachineNode(
2858                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2859                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
2860                                                     MVT::i32)),
2861                       0);
2862           break;
2863         case MVT::i32:
2864           break;
2865         case MVT::i64:
2866           ClrNode =
2867               SDValue(CurDAG->getMachineNode(
2868                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2869                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2870                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
2871                                                     MVT::i32)),
2872                       0);
2873           break;
2874         default:
2875           llvm_unreachable("Unexpected division source");
2876         }
2877 
2878         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2879                                       ClrNode, InFlag).getValue(1);
2880       }
2881     }
2882 
2883     if (foldedLoad) {
2884       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2885                         InFlag };
2886       SDNode *CNode =
2887         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2888       InFlag = SDValue(CNode, 1);
2889       // Update the chain.
2890       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2891     } else {
2892       InFlag =
2893         SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2894     }
2895 
2896     // Prevent use of AH in a REX instruction by explicitly copying it to
2897     // an ABCD_L register.
2898     //
2899     // The current assumption of the register allocator is that isel
2900     // won't generate explicit references to the GR8_ABCD_H registers. If
2901     // the allocator and/or the backend get enhanced to be more robust in
2902     // that regard, this can be, and should be, removed.
2903     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2904       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2905       unsigned AHExtOpcode =
2906           isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2907 
2908       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2909                                              MVT::Glue, AHCopy, InFlag);
2910       SDValue Result(RNode, 0);
2911       InFlag = SDValue(RNode, 1);
2912 
2913       if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2914           Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2915         if (Node->getValueType(1) == MVT::i64) {
2916           // It's not possible to directly movsx AH to a 64bit register, because
2917           // the latter needs the REX prefix, but the former can't have it.
2918           assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2919                  "Unexpected i64 sext of h-register");
2920           Result =
2921               SDValue(CurDAG->getMachineNode(
2922                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2923                           CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2924                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
2925                                                     MVT::i32)),
2926                       0);
2927         }
2928       } else {
2929         Result =
2930             CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2931       }
2932       ReplaceUses(SDValue(Node, 1), Result);
2933       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2934     }
2935     // Copy the division (low) result, if it is needed.
2936     if (!SDValue(Node, 0).use_empty()) {
2937       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2938                                                 LoReg, NVT, InFlag);
2939       InFlag = Result.getValue(2);
2940       ReplaceUses(SDValue(Node, 0), Result);
2941       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2942     }
2943     // Copy the remainder (high) result, if it is needed.
2944     if (!SDValue(Node, 1).use_empty()) {
2945       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2946                                               HiReg, NVT, InFlag);
2947       InFlag = Result.getValue(2);
2948       ReplaceUses(SDValue(Node, 1), Result);
2949       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2950     }
2951     CurDAG->RemoveDeadNode(Node);
2952     return;
2953   }
2954 
2955   case X86ISD::CMP:
2956   case X86ISD::SUB: {
2957     // Sometimes a SUB is used to perform comparison.
2958     if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2959       // This node is not a CMP.
2960       break;
2961     SDValue N0 = Node->getOperand(0);
2962     SDValue N1 = Node->getOperand(1);
2963 
2964     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2965         hasNoSignedComparisonUses(Node))
2966       N0 = N0.getOperand(0);
2967 
2968     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2969     // use a smaller encoding.
2970     // Look past the truncate if CMP is the only use of it.
2971     if ((N0.getOpcode() == ISD::AND ||
2972          (N0.getResNo() == 0 && N0.getOpcode() == X86ISD::AND)) &&
2973         N0.getNode()->hasOneUse() &&
2974         N0.getValueType() != MVT::i8 &&
2975         X86::isZeroNode(N1)) {
2976       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2977       if (!C) break;
2978       uint64_t Mask = C->getZExtValue();
2979 
2980       // For example, convert "testl %eax, $8" to "testb %al, $8"
2981       if (isUInt<8>(Mask) &&
2982           (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
2983         SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i8);
2984         SDValue Reg = N0.getOperand(0);
2985 
2986         // Extract the l-register.
2987         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2988                                                         MVT::i8, Reg);
2989 
2990         // Emit a testb.
2991         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2992                                                  Subreg, Imm);
2993         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2994         // one, do not call ReplaceAllUsesWith.
2995         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2996                     SDValue(NewNode, 0));
2997         CurDAG->RemoveDeadNode(Node);
2998         return;
2999       }
3000 
3001       // For example, "testl %eax, $2048" to "testb %ah, $8".
3002       if (isShiftedUInt<8, 8>(Mask) &&
3003           (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3004         // Shift the immediate right by 8 bits.
3005         SDValue ShiftedImm = CurDAG->getTargetConstant(Mask >> 8, dl, MVT::i8);
3006         SDValue Reg = N0.getOperand(0);
3007 
3008         // Extract the h-register.
3009         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
3010                                                         MVT::i8, Reg);
3011 
3012         // Emit a testb.  The EXTRACT_SUBREG becomes a COPY that can only
3013         // target GR8_NOREX registers, so make sure the register class is
3014         // forced.
3015         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
3016                                                  MVT::i32, Subreg, ShiftedImm);
3017         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3018         // one, do not call ReplaceAllUsesWith.
3019         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3020                     SDValue(NewNode, 0));
3021         CurDAG->RemoveDeadNode(Node);
3022         return;
3023       }
3024 
3025       // For example, "testl %eax, $32776" to "testw %ax, $32776".
3026       // NOTE: We only want to form TESTW instructions if optimizing for
3027       // min size. Otherwise we only save one byte and possibly get a length
3028       // changing prefix penalty in the decoders.
3029       if (OptForMinSize && isUInt<16>(Mask) && N0.getValueType() != MVT::i16 &&
3030           (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3031         SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i16);
3032         SDValue Reg = N0.getOperand(0);
3033 
3034         // Extract the 16-bit subregister.
3035         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
3036                                                         MVT::i16, Reg);
3037 
3038         // Emit a testw.
3039         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
3040                                                  Subreg, Imm);
3041         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3042         // one, do not call ReplaceAllUsesWith.
3043         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3044                     SDValue(NewNode, 0));
3045         CurDAG->RemoveDeadNode(Node);
3046         return;
3047       }
3048 
3049       // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3050       if (isUInt<32>(Mask) && N0.getValueType() == MVT::i64 &&
3051           (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3052         SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
3053         SDValue Reg = N0.getOperand(0);
3054 
3055         // Extract the 32-bit subregister.
3056         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
3057                                                         MVT::i32, Reg);
3058 
3059         // Emit a testl.
3060         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
3061                                                  Subreg, Imm);
3062         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3063         // one, do not call ReplaceAllUsesWith.
3064         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3065                     SDValue(NewNode, 0));
3066         CurDAG->RemoveDeadNode(Node);
3067         return;
3068       }
3069     }
3070     break;
3071   }
3072   case ISD::STORE:
3073     if (foldLoadStoreIntoMemOperand(Node))
3074       return;
3075     break;
3076   }
3077 
3078   SelectCode(Node);
3079 }
3080 
3081 bool X86DAGToDAGISel::
3082 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
3083                              std::vector<SDValue> &OutOps) {
3084   SDValue Op0, Op1, Op2, Op3, Op4;
3085   switch (ConstraintID) {
3086   default:
3087     llvm_unreachable("Unexpected asm memory constraint");
3088   case InlineAsm::Constraint_i:
3089     // FIXME: It seems strange that 'i' is needed here since it's supposed to
3090     //        be an immediate and not a memory constraint.
3091     LLVM_FALLTHROUGH;
3092   case InlineAsm::Constraint_o: // offsetable        ??
3093   case InlineAsm::Constraint_v: // not offsetable    ??
3094   case InlineAsm::Constraint_m: // memory
3095   case InlineAsm::Constraint_X:
3096     if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
3097       return true;
3098     break;
3099   }
3100 
3101   OutOps.push_back(Op0);
3102   OutOps.push_back(Op1);
3103   OutOps.push_back(Op2);
3104   OutOps.push_back(Op3);
3105   OutOps.push_back(Op4);
3106   return false;
3107 }
3108 
3109 /// This pass converts a legalized DAG into a X86-specific DAG,
3110 /// ready for instruction scheduling.
3111 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
3112                                      CodeGenOpt::Level OptLevel) {
3113   return new X86DAGToDAGISel(TM, OptLevel);
3114 }
3115