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