1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a DAG pattern matching instruction selector for X86,
10 // converting from a legalized dag to a X86 dag.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86.h"
15 #include "X86MachineFunctionInfo.h"
16 #include "X86RegisterInfo.h"
17 #include "X86Subtarget.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/SelectionDAGISel.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/IntrinsicsX86.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <stdint.h>
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "x86-isel"
36 
37 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
38 
39 static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
40     cl::desc("Enable setting constant bits to reduce size of mask immediates"),
41     cl::Hidden);
42 
43 static cl::opt<bool> EnablePromoteAnyextLoad(
44     "x86-promote-anyext-load", cl::init(true),
45     cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden);
46 
47 //===----------------------------------------------------------------------===//
48 //                      Pattern Matcher Implementation
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// This corresponds to X86AddressMode, but uses SDValue's instead of register
53   /// numbers for the leaves of the matched tree.
54   struct X86ISelAddressMode {
55     enum {
56       RegBase,
57       FrameIndexBase
58     } BaseType;
59 
60     // This is really a union, discriminated by BaseType!
61     SDValue Base_Reg;
62     int Base_FrameIndex;
63 
64     unsigned Scale;
65     SDValue IndexReg;
66     int32_t Disp;
67     SDValue Segment;
68     const GlobalValue *GV;
69     const Constant *CP;
70     const BlockAddress *BlockAddr;
71     const char *ES;
72     MCSymbol *MCSym;
73     int JT;
74     Align Alignment;            // CP alignment.
75     unsigned char SymbolFlags;  // X86II::MO_*
76     bool NegateIndex = false;
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), 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 (NegateIndex)
120         dbgs() << "negate ";
121       if (IndexReg.getNode())
122         IndexReg.getNode()->dump(DAG);
123       else
124         dbgs() << "nul\n";
125       dbgs() << " Disp " << Disp << '\n'
126              << "GV ";
127       if (GV)
128         GV->dump();
129       else
130         dbgs() << "nul";
131       dbgs() << " CP ";
132       if (CP)
133         CP->dump();
134       else
135         dbgs() << "nul";
136       dbgs() << '\n'
137              << "ES ";
138       if (ES)
139         dbgs() << ES;
140       else
141         dbgs() << "nul";
142       dbgs() << " MCSym ";
143       if (MCSym)
144         dbgs() << MCSym;
145       else
146         dbgs() << "nul";
147       dbgs() << " JT" << JT << " Align" << Alignment.value() << '\n';
148     }
149 #endif
150   };
151 }
152 
153 namespace {
154   //===--------------------------------------------------------------------===//
155   /// ISel - X86-specific code to select X86 machine instructions for
156   /// SelectionDAG operations.
157   ///
158   class X86DAGToDAGISel final : public SelectionDAGISel {
159     /// Keep a pointer to the X86Subtarget around so that we can
160     /// make the right decision when generating code for different targets.
161     const X86Subtarget *Subtarget;
162 
163     /// If true, selector should try to optimize for minimum code size.
164     bool OptForMinSize;
165 
166     /// Disable direct TLS access through segment registers.
167     bool IndirectTlsSegRefs;
168 
169   public:
170     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
171         : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr),
172           OptForMinSize(false), IndirectTlsSegRefs(false) {}
173 
174     StringRef getPassName() const override {
175       return "X86 DAG->DAG Instruction Selection";
176     }
177 
178     bool runOnMachineFunction(MachineFunction &MF) override {
179       // Reset the subtarget each time through.
180       Subtarget = &MF.getSubtarget<X86Subtarget>();
181       IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
182                              "indirect-tls-seg-refs");
183 
184       // OptFor[Min]Size are used in pattern predicates that isel is matching.
185       OptForMinSize = MF.getFunction().hasMinSize();
186       assert((!OptForMinSize || MF.getFunction().hasOptSize()) &&
187              "OptForMinSize implies OptForSize");
188 
189       SelectionDAGISel::runOnMachineFunction(MF);
190       return true;
191     }
192 
193     void emitFunctionEntryCode() override;
194 
195     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
196 
197     void PreprocessISelDAG() override;
198     void PostprocessISelDAG() override;
199 
200 // Include the pieces autogenerated from the target description.
201 #include "X86GenDAGISel.inc"
202 
203   private:
204     void Select(SDNode *N) override;
205 
206     bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
207     bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
208     bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
209     bool matchAddress(SDValue N, X86ISelAddressMode &AM);
210     bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
211     bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);
212     bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
213                                  unsigned Depth);
214     bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
215     bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
216                     SDValue &Scale, SDValue &Index, SDValue &Disp,
217                     SDValue &Segment);
218     bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp,
219                           SDValue ScaleOp, SDValue &Base, SDValue &Scale,
220                           SDValue &Index, SDValue &Disp, SDValue &Segment);
221     bool selectMOV64Imm32(SDValue N, SDValue &Imm);
222     bool selectLEAAddr(SDValue N, SDValue &Base,
223                        SDValue &Scale, SDValue &Index, SDValue &Disp,
224                        SDValue &Segment);
225     bool selectLEA64_32Addr(SDValue N, SDValue &Base,
226                             SDValue &Scale, SDValue &Index, SDValue &Disp,
227                             SDValue &Segment);
228     bool selectTLSADDRAddr(SDValue N, SDValue &Base,
229                            SDValue &Scale, SDValue &Index, SDValue &Disp,
230                            SDValue &Segment);
231     bool selectRelocImm(SDValue N, SDValue &Op);
232 
233     bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
234                      SDValue &Base, SDValue &Scale,
235                      SDValue &Index, SDValue &Disp,
236                      SDValue &Segment);
237 
238     // Convenience method where P is also root.
239     bool tryFoldLoad(SDNode *P, SDValue N,
240                      SDValue &Base, SDValue &Scale,
241                      SDValue &Index, SDValue &Disp,
242                      SDValue &Segment) {
243       return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
244     }
245 
246     bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
247                           SDValue &Base, SDValue &Scale,
248                           SDValue &Index, SDValue &Disp,
249                           SDValue &Segment);
250 
251     bool isProfitableToFormMaskedOp(SDNode *N) const;
252 
253     /// Implement addressing mode selection for inline asm expressions.
254     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
255                                       unsigned ConstraintID,
256                                       std::vector<SDValue> &OutOps) override;
257 
258     void emitSpecialCodeForMain();
259 
260     inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
261                                    MVT VT, SDValue &Base, SDValue &Scale,
262                                    SDValue &Index, SDValue &Disp,
263                                    SDValue &Segment) {
264       if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
265         Base = CurDAG->getTargetFrameIndex(
266             AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));
267       else if (AM.Base_Reg.getNode())
268         Base = AM.Base_Reg;
269       else
270         Base = CurDAG->getRegister(0, VT);
271 
272       Scale = getI8Imm(AM.Scale, DL);
273 
274       // Negate the index if needed.
275       if (AM.NegateIndex) {
276         unsigned NegOpc = VT == MVT::i64 ? X86::NEG64r : X86::NEG32r;
277         SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,
278                                                      AM.IndexReg), 0);
279         AM.IndexReg = Neg;
280       }
281 
282       if (AM.IndexReg.getNode())
283         Index = AM.IndexReg;
284       else
285         Index = CurDAG->getRegister(0, VT);
286 
287       // These are 32-bit even in 64-bit mode since RIP-relative offset
288       // is 32-bit.
289       if (AM.GV)
290         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
291                                               MVT::i32, AM.Disp,
292                                               AM.SymbolFlags);
293       else if (AM.CP)
294         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Alignment,
295                                              AM.Disp, AM.SymbolFlags);
296       else if (AM.ES) {
297         assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
298         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
299       } else if (AM.MCSym) {
300         assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
301         assert(AM.SymbolFlags == 0 && "oo");
302         Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
303       } else if (AM.JT != -1) {
304         assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
305         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
306       } else if (AM.BlockAddr)
307         Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
308                                              AM.SymbolFlags);
309       else
310         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
311 
312       if (AM.Segment.getNode())
313         Segment = AM.Segment;
314       else
315         Segment = CurDAG->getRegister(0, MVT::i16);
316     }
317 
318     // Utility function to determine whether we should avoid selecting
319     // immediate forms of instructions for better code size or not.
320     // At a high level, we'd like to avoid such instructions when
321     // we have similar constants used within the same basic block
322     // that can be kept in a register.
323     //
324     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
325       uint32_t UseCount = 0;
326 
327       // Do not want to hoist if we're not optimizing for size.
328       // TODO: We'd like to remove this restriction.
329       // See the comment in X86InstrInfo.td for more info.
330       if (!CurDAG->shouldOptForSize())
331         return false;
332 
333       // Walk all the users of the immediate.
334       for (SDNode::use_iterator UI = N->use_begin(),
335            UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
336 
337         SDNode *User = *UI;
338 
339         // This user is already selected. Count it as a legitimate use and
340         // move on.
341         if (User->isMachineOpcode()) {
342           UseCount++;
343           continue;
344         }
345 
346         // We want to count stores of immediates as real uses.
347         if (User->getOpcode() == ISD::STORE &&
348             User->getOperand(1).getNode() == N) {
349           UseCount++;
350           continue;
351         }
352 
353         // We don't currently match users that have > 2 operands (except
354         // for stores, which are handled above)
355         // Those instruction won't match in ISEL, for now, and would
356         // be counted incorrectly.
357         // This may change in the future as we add additional instruction
358         // types.
359         if (User->getNumOperands() != 2)
360           continue;
361 
362         // If this is a sign-extended 8-bit integer immediate used in an ALU
363         // instruction, there is probably an opcode encoding to save space.
364         auto *C = dyn_cast<ConstantSDNode>(N);
365         if (C && isInt<8>(C->getSExtValue()))
366           continue;
367 
368         // Immediates that are used for offsets as part of stack
369         // manipulation should be left alone. These are typically
370         // used to indicate SP offsets for argument passing and
371         // will get pulled into stores/pushes (implicitly).
372         if (User->getOpcode() == X86ISD::ADD ||
373             User->getOpcode() == ISD::ADD    ||
374             User->getOpcode() == X86ISD::SUB ||
375             User->getOpcode() == ISD::SUB) {
376 
377           // Find the other operand of the add/sub.
378           SDValue OtherOp = User->getOperand(0);
379           if (OtherOp.getNode() == N)
380             OtherOp = User->getOperand(1);
381 
382           // Don't count if the other operand is SP.
383           RegisterSDNode *RegNode;
384           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
385               (RegNode = dyn_cast_or_null<RegisterSDNode>(
386                  OtherOp->getOperand(1).getNode())))
387             if ((RegNode->getReg() == X86::ESP) ||
388                 (RegNode->getReg() == X86::RSP))
389               continue;
390         }
391 
392         // ... otherwise, count this and move on.
393         UseCount++;
394       }
395 
396       // If we have more than 1 use, then recommend for hoisting.
397       return (UseCount > 1);
398     }
399 
400     /// Return a target constant with the specified value of type i8.
401     inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
402       return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
403     }
404 
405     /// Return a target constant with the specified value, of type i32.
406     inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
407       return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
408     }
409 
410     /// Return a target constant with the specified value, of type i64.
411     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
412       return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
413     }
414 
415     SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
416                                         const SDLoc &DL) {
417       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
418       uint64_t Index = N->getConstantOperandVal(1);
419       MVT VecVT = N->getOperand(0).getSimpleValueType();
420       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
421     }
422 
423     SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
424                                       const SDLoc &DL) {
425       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
426       uint64_t Index = N->getConstantOperandVal(2);
427       MVT VecVT = N->getSimpleValueType(0);
428       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
429     }
430 
431     // Helper to detect unneeded and instructions on shift amounts. Called
432     // from PatFrags in tablegen.
433     bool isUnneededShiftMask(SDNode *N, unsigned Width) const {
434       assert(N->getOpcode() == ISD::AND && "Unexpected opcode");
435       const APInt &Val = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
436 
437       if (Val.countTrailingOnes() >= Width)
438         return true;
439 
440       APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;
441       return Mask.countTrailingOnes() >= Width;
442     }
443 
444     /// Return an SDNode that returns the value of the global base register.
445     /// Output instructions required to initialize the global base register,
446     /// if necessary.
447     SDNode *getGlobalBaseReg();
448 
449     /// Return a reference to the TargetMachine, casted to the target-specific
450     /// type.
451     const X86TargetMachine &getTargetMachine() const {
452       return static_cast<const X86TargetMachine &>(TM);
453     }
454 
455     /// Return a reference to the TargetInstrInfo, casted to the target-specific
456     /// type.
457     const X86InstrInfo *getInstrInfo() const {
458       return Subtarget->getInstrInfo();
459     }
460 
461     /// Address-mode matching performs shift-of-and to and-of-shift
462     /// reassociation in order to expose more scaled addressing
463     /// opportunities.
464     bool ComplexPatternFuncMutatesDAG() const override {
465       return true;
466     }
467 
468     bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
469 
470     // Indicates we should prefer to use a non-temporal load for this load.
471     bool useNonTemporalLoad(LoadSDNode *N) const {
472       if (!N->isNonTemporal())
473         return false;
474 
475       unsigned StoreSize = N->getMemoryVT().getStoreSize();
476 
477       if (N->getAlignment() < StoreSize)
478         return false;
479 
480       switch (StoreSize) {
481       default: llvm_unreachable("Unsupported store size");
482       case 4:
483       case 8:
484         return false;
485       case 16:
486         return Subtarget->hasSSE41();
487       case 32:
488         return Subtarget->hasAVX2();
489       case 64:
490         return Subtarget->hasAVX512();
491       }
492     }
493 
494     bool foldLoadStoreIntoMemOperand(SDNode *Node);
495     MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
496     bool matchBitExtract(SDNode *Node);
497     bool shrinkAndImmediate(SDNode *N);
498     bool isMaskZeroExtended(SDNode *N) const;
499     bool tryShiftAmountMod(SDNode *N);
500     bool tryShrinkShlLogicImm(SDNode *N);
501     bool tryVPTERNLOG(SDNode *N);
502     bool matchVPTERNLOG(SDNode *Root, SDNode *ParentA, SDNode *ParentBC,
503                         SDValue A, SDValue B, SDValue C, uint8_t Imm);
504     bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);
505     bool tryMatchBitSelect(SDNode *N);
506 
507     MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
508                                 const SDLoc &dl, MVT VT, SDNode *Node);
509     MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
510                                 const SDLoc &dl, MVT VT, SDNode *Node,
511                                 SDValue &InFlag);
512 
513     bool tryOptimizeRem8Extend(SDNode *N);
514 
515     bool onlyUsesZeroFlag(SDValue Flags) const;
516     bool hasNoSignFlagUses(SDValue Flags) const;
517     bool hasNoCarryFlagUses(SDValue Flags) const;
518   };
519 }
520 
521 
522 // Returns true if this masked compare can be implemented legally with this
523 // type.
524 static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
525   unsigned Opcode = N->getOpcode();
526   if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMM ||
527       Opcode == X86ISD::STRICT_CMPM || Opcode == ISD::SETCC ||
528       Opcode == X86ISD::CMPMM_SAE || Opcode == X86ISD::VFPCLASS) {
529     // We can get 256-bit 8 element types here without VLX being enabled. When
530     // this happens we will use 512-bit operations and the mask will not be
531     // zero extended.
532     EVT OpVT = N->getOperand(0).getValueType();
533     // The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the
534     // second operand.
535     if (Opcode == X86ISD::STRICT_CMPM)
536       OpVT = N->getOperand(1).getValueType();
537     if (OpVT.is256BitVector() || OpVT.is128BitVector())
538       return Subtarget->hasVLX();
539 
540     return true;
541   }
542   // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
543   if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
544       Opcode == X86ISD::FSETCCM_SAE)
545     return true;
546 
547   return false;
548 }
549 
550 // Returns true if we can assume the writer of the mask has zero extended it
551 // for us.
552 bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
553   // If this is an AND, check if we have a compare on either side. As long as
554   // one side guarantees the mask is zero extended, the AND will preserve those
555   // zeros.
556   if (N->getOpcode() == ISD::AND)
557     return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
558            isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
559 
560   return isLegalMaskCompare(N, Subtarget);
561 }
562 
563 bool
564 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
565   if (OptLevel == CodeGenOpt::None) return false;
566 
567   if (!N.hasOneUse())
568     return false;
569 
570   if (N.getOpcode() != ISD::LOAD)
571     return true;
572 
573   // Don't fold non-temporal loads if we have an instruction for them.
574   if (useNonTemporalLoad(cast<LoadSDNode>(N)))
575     return false;
576 
577   // If N is a load, do additional profitability checks.
578   if (U == Root) {
579     switch (U->getOpcode()) {
580     default: break;
581     case X86ISD::ADD:
582     case X86ISD::ADC:
583     case X86ISD::SUB:
584     case X86ISD::SBB:
585     case X86ISD::AND:
586     case X86ISD::XOR:
587     case X86ISD::OR:
588     case ISD::ADD:
589     case ISD::ADDCARRY:
590     case ISD::AND:
591     case ISD::OR:
592     case ISD::XOR: {
593       SDValue Op1 = U->getOperand(1);
594 
595       // If the other operand is a 8-bit immediate we should fold the immediate
596       // instead. This reduces code size.
597       // e.g.
598       // movl 4(%esp), %eax
599       // addl $4, %eax
600       // vs.
601       // movl $4, %eax
602       // addl 4(%esp), %eax
603       // The former is 2 bytes shorter. In case where the increment is 1, then
604       // the saving can be 4 bytes (by using incl %eax).
605       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
606         if (Imm->getAPIntValue().isSignedIntN(8))
607           return false;
608 
609         // If this is a 64-bit AND with an immediate that fits in 32-bits,
610         // prefer using the smaller and over folding the load. This is needed to
611         // make sure immediates created by shrinkAndImmediate are always folded.
612         // Ideally we would narrow the load during DAG combine and get the
613         // best of both worlds.
614         if (U->getOpcode() == ISD::AND &&
615             Imm->getAPIntValue().getBitWidth() == 64 &&
616             Imm->getAPIntValue().isIntN(32))
617           return false;
618 
619         // If this really a zext_inreg that can be represented with a movzx
620         // instruction, prefer that.
621         // TODO: We could shrink the load and fold if it is non-volatile.
622         if (U->getOpcode() == ISD::AND &&
623             (Imm->getAPIntValue() == UINT8_MAX ||
624              Imm->getAPIntValue() == UINT16_MAX ||
625              Imm->getAPIntValue() == UINT32_MAX))
626           return false;
627 
628         // ADD/SUB with can negate the immediate and use the opposite operation
629         // to fit 128 into a sign extended 8 bit immediate.
630         if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&
631             (-Imm->getAPIntValue()).isSignedIntN(8))
632           return false;
633 
634         if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) &&
635             (-Imm->getAPIntValue()).isSignedIntN(8) &&
636             hasNoCarryFlagUses(SDValue(U, 1)))
637           return false;
638       }
639 
640       // If the other operand is a TLS address, we should fold it instead.
641       // This produces
642       // movl    %gs:0, %eax
643       // leal    i@NTPOFF(%eax), %eax
644       // instead of
645       // movl    $i@NTPOFF, %eax
646       // addl    %gs:0, %eax
647       // if the block also has an access to a second TLS address this will save
648       // a load.
649       // FIXME: This is probably also true for non-TLS addresses.
650       if (Op1.getOpcode() == X86ISD::Wrapper) {
651         SDValue Val = Op1.getOperand(0);
652         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
653           return false;
654       }
655 
656       // Don't fold load if this matches the BTS/BTR/BTC patterns.
657       // BTS: (or X, (shl 1, n))
658       // BTR: (and X, (rotl -2, n))
659       // BTC: (xor X, (shl 1, n))
660       if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
661         if (U->getOperand(0).getOpcode() == ISD::SHL &&
662             isOneConstant(U->getOperand(0).getOperand(0)))
663           return false;
664 
665         if (U->getOperand(1).getOpcode() == ISD::SHL &&
666             isOneConstant(U->getOperand(1).getOperand(0)))
667           return false;
668       }
669       if (U->getOpcode() == ISD::AND) {
670         SDValue U0 = U->getOperand(0);
671         SDValue U1 = U->getOperand(1);
672         if (U0.getOpcode() == ISD::ROTL) {
673           auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
674           if (C && C->getSExtValue() == -2)
675             return false;
676         }
677 
678         if (U1.getOpcode() == ISD::ROTL) {
679           auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
680           if (C && C->getSExtValue() == -2)
681             return false;
682         }
683       }
684 
685       break;
686     }
687     case ISD::SHL:
688     case ISD::SRA:
689     case ISD::SRL:
690       // Don't fold a load into a shift by immediate. The BMI2 instructions
691       // support folding a load, but not an immediate. The legacy instructions
692       // support folding an immediate, but can't fold a load. Folding an
693       // immediate is preferable to folding a load.
694       if (isa<ConstantSDNode>(U->getOperand(1)))
695         return false;
696 
697       break;
698     }
699   }
700 
701   // Prevent folding a load if this can implemented with an insert_subreg or
702   // a move that implicitly zeroes.
703   if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
704       isNullConstant(Root->getOperand(2)) &&
705       (Root->getOperand(0).isUndef() ||
706        ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
707     return false;
708 
709   return true;
710 }
711 
712 // Indicates it is profitable to form an AVX512 masked operation. Returning
713 // false will favor a masked register-register masked move or vblendm and the
714 // operation will be selected separately.
715 bool X86DAGToDAGISel::isProfitableToFormMaskedOp(SDNode *N) const {
716   assert(
717       (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::SELECTS) &&
718       "Unexpected opcode!");
719 
720   // If the operation has additional users, the operation will be duplicated.
721   // Check the use count to prevent that.
722   // FIXME: Are there cheap opcodes we might want to duplicate?
723   return N->getOperand(1).hasOneUse();
724 }
725 
726 /// Replace the original chain operand of the call with
727 /// load's chain operand and move load below the call's chain operand.
728 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
729                                SDValue Call, SDValue OrigChain) {
730   SmallVector<SDValue, 8> Ops;
731   SDValue Chain = OrigChain.getOperand(0);
732   if (Chain.getNode() == Load.getNode())
733     Ops.push_back(Load.getOperand(0));
734   else {
735     assert(Chain.getOpcode() == ISD::TokenFactor &&
736            "Unexpected chain operand");
737     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
738       if (Chain.getOperand(i).getNode() == Load.getNode())
739         Ops.push_back(Load.getOperand(0));
740       else
741         Ops.push_back(Chain.getOperand(i));
742     SDValue NewChain =
743       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
744     Ops.clear();
745     Ops.push_back(NewChain);
746   }
747   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
748   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
749   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
750                              Load.getOperand(1), Load.getOperand(2));
751 
752   Ops.clear();
753   Ops.push_back(SDValue(Load.getNode(), 1));
754   Ops.append(Call->op_begin() + 1, Call->op_end());
755   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
756 }
757 
758 /// Return true if call address is a load and it can be
759 /// moved below CALLSEQ_START and the chains leading up to the call.
760 /// Return the CALLSEQ_START by reference as a second output.
761 /// In the case of a tail call, there isn't a callseq node between the call
762 /// chain and the load.
763 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
764   // The transformation is somewhat dangerous if the call's chain was glued to
765   // the call. After MoveBelowOrigChain the load is moved between the call and
766   // the chain, this can create a cycle if the load is not folded. So it is
767   // *really* important that we are sure the load will be folded.
768   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
769     return false;
770   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
771   if (!LD ||
772       !LD->isSimple() ||
773       LD->getAddressingMode() != ISD::UNINDEXED ||
774       LD->getExtensionType() != ISD::NON_EXTLOAD)
775     return false;
776 
777   // Now let's find the callseq_start.
778   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
779     if (!Chain.hasOneUse())
780       return false;
781     Chain = Chain.getOperand(0);
782   }
783 
784   if (!Chain.getNumOperands())
785     return false;
786   // Since we are not checking for AA here, conservatively abort if the chain
787   // writes to memory. It's not safe to move the callee (a load) across a store.
788   if (isa<MemSDNode>(Chain.getNode()) &&
789       cast<MemSDNode>(Chain.getNode())->writeMem())
790     return false;
791   if (Chain.getOperand(0).getNode() == Callee.getNode())
792     return true;
793   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
794       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
795       Callee.getValue(1).hasOneUse())
796     return true;
797   return false;
798 }
799 
800 void X86DAGToDAGISel::PreprocessISelDAG() {
801   bool MadeChange = false;
802   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
803        E = CurDAG->allnodes_end(); I != E; ) {
804     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
805 
806     // If this is a target specific AND node with no flag usages, turn it back
807     // into ISD::AND to enable test instruction matching.
808     if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
809       SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
810                                     N->getOperand(0), N->getOperand(1));
811       --I;
812       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
813       ++I;
814       MadeChange = true;
815       continue;
816     }
817 
818     /// Convert vector increment or decrement to sub/add with an all-ones
819     /// constant:
820     /// add X, <1, 1...> --> sub X, <-1, -1...>
821     /// sub X, <1, 1...> --> add X, <-1, -1...>
822     /// The all-ones vector constant can be materialized using a pcmpeq
823     /// instruction that is commonly recognized as an idiom (has no register
824     /// dependency), so that's better/smaller than loading a splat 1 constant.
825     if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
826         N->getSimpleValueType(0).isVector()) {
827 
828       APInt SplatVal;
829       if (X86::isConstantSplat(N->getOperand(1), SplatVal) &&
830           SplatVal.isOneValue()) {
831         SDLoc DL(N);
832 
833         MVT VT = N->getSimpleValueType(0);
834         unsigned NumElts = VT.getSizeInBits() / 32;
835         SDValue AllOnes =
836             CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts));
837         AllOnes = CurDAG->getBitcast(VT, AllOnes);
838 
839         unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
840         SDValue Res =
841             CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes);
842         --I;
843         CurDAG->ReplaceAllUsesWith(N, Res.getNode());
844         ++I;
845         MadeChange = true;
846         continue;
847       }
848     }
849 
850     switch (N->getOpcode()) {
851     case X86ISD::VBROADCAST: {
852       MVT VT = N->getSimpleValueType(0);
853       // Emulate v32i16/v64i8 broadcast without BWI.
854       if (!Subtarget->hasBWI() && (VT == MVT::v32i16 || VT == MVT::v64i8)) {
855         MVT NarrowVT = VT == MVT::v32i16 ? MVT::v16i16 : MVT::v32i8;
856         SDLoc dl(N);
857         SDValue NarrowBCast =
858             CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0));
859         SDValue Res =
860             CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
861                             NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
862         unsigned Index = VT == MVT::v32i16 ? 16 : 32;
863         Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
864                               CurDAG->getIntPtrConstant(Index, dl));
865 
866         --I;
867         CurDAG->ReplaceAllUsesWith(N, Res.getNode());
868         ++I;
869         MadeChange = true;
870         continue;
871       }
872 
873       break;
874     }
875     case X86ISD::VBROADCAST_LOAD: {
876       MVT VT = N->getSimpleValueType(0);
877       // Emulate v32i16/v64i8 broadcast without BWI.
878       if (!Subtarget->hasBWI() && (VT == MVT::v32i16 || VT == MVT::v64i8)) {
879         MVT NarrowVT = VT == MVT::v32i16 ? MVT::v16i16 : MVT::v32i8;
880         auto *MemNode = cast<MemSDNode>(N);
881         SDLoc dl(N);
882         SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other);
883         SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()};
884         SDValue NarrowBCast = CurDAG->getMemIntrinsicNode(
885             X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(),
886             MemNode->getMemOperand());
887         SDValue Res =
888             CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
889                             NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
890         unsigned Index = VT == MVT::v32i16 ? 16 : 32;
891         Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
892                               CurDAG->getIntPtrConstant(Index, dl));
893 
894         --I;
895         SDValue To[] = {Res, NarrowBCast.getValue(1)};
896         CurDAG->ReplaceAllUsesWith(N, To);
897         ++I;
898         MadeChange = true;
899         continue;
900       }
901 
902       break;
903     }
904     case ISD::VSELECT: {
905       // Replace VSELECT with non-mask conditions with with BLENDV.
906       if (N->getOperand(0).getValueType().getVectorElementType() == MVT::i1)
907         break;
908 
909       assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!");
910       SDValue Blendv =
911           CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),
912                           N->getOperand(0), N->getOperand(1), N->getOperand(2));
913       --I;
914       CurDAG->ReplaceAllUsesWith(N, Blendv.getNode());
915       ++I;
916       MadeChange = true;
917       continue;
918     }
919     case ISD::FP_ROUND:
920     case ISD::STRICT_FP_ROUND:
921     case ISD::FP_TO_SINT:
922     case ISD::FP_TO_UINT:
923     case ISD::STRICT_FP_TO_SINT:
924     case ISD::STRICT_FP_TO_UINT: {
925       // Replace vector fp_to_s/uint with their X86 specific equivalent so we
926       // don't need 2 sets of patterns.
927       if (!N->getSimpleValueType(0).isVector())
928         break;
929 
930       unsigned NewOpc;
931       switch (N->getOpcode()) {
932       default: llvm_unreachable("Unexpected opcode!");
933       case ISD::FP_ROUND:          NewOpc = X86ISD::VFPROUND;        break;
934       case ISD::STRICT_FP_ROUND:   NewOpc = X86ISD::STRICT_VFPROUND; break;
935       case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break;
936       case ISD::FP_TO_SINT:        NewOpc = X86ISD::CVTTP2SI;        break;
937       case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break;
938       case ISD::FP_TO_UINT:        NewOpc = X86ISD::CVTTP2UI;        break;
939       }
940       SDValue Res;
941       if (N->isStrictFPOpcode())
942         Res =
943             CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other},
944                             {N->getOperand(0), N->getOperand(1)});
945       else
946         Res =
947             CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
948                             N->getOperand(0));
949       --I;
950       CurDAG->ReplaceAllUsesWith(N, Res.getNode());
951       ++I;
952       MadeChange = true;
953       continue;
954     }
955     case ISD::SHL:
956     case ISD::SRA:
957     case ISD::SRL: {
958       // Replace vector shifts with their X86 specific equivalent so we don't
959       // need 2 sets of patterns.
960       if (!N->getValueType(0).isVector())
961         break;
962 
963       unsigned NewOpc;
964       switch (N->getOpcode()) {
965       default: llvm_unreachable("Unexpected opcode!");
966       case ISD::SHL: NewOpc = X86ISD::VSHLV; break;
967       case ISD::SRA: NewOpc = X86ISD::VSRAV; break;
968       case ISD::SRL: NewOpc = X86ISD::VSRLV; break;
969       }
970       SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
971                                     N->getOperand(0), N->getOperand(1));
972       --I;
973       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
974       ++I;
975       MadeChange = true;
976       continue;
977     }
978     case ISD::ANY_EXTEND:
979     case ISD::ANY_EXTEND_VECTOR_INREG: {
980       // Replace vector any extend with the zero extend equivalents so we don't
981       // need 2 sets of patterns. Ignore vXi1 extensions.
982       if (!N->getValueType(0).isVector())
983         break;
984 
985       unsigned NewOpc;
986       if (N->getOperand(0).getScalarValueSizeInBits() == 1) {
987         assert(N->getOpcode() == ISD::ANY_EXTEND &&
988                "Unexpected opcode for mask vector!");
989         NewOpc = ISD::SIGN_EXTEND;
990       } else {
991         NewOpc = N->getOpcode() == ISD::ANY_EXTEND
992                               ? ISD::ZERO_EXTEND
993                               : ISD::ZERO_EXTEND_VECTOR_INREG;
994       }
995 
996       SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
997                                     N->getOperand(0));
998       --I;
999       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1000       ++I;
1001       MadeChange = true;
1002       continue;
1003     }
1004     case ISD::FCEIL:
1005     case ISD::STRICT_FCEIL:
1006     case ISD::FFLOOR:
1007     case ISD::STRICT_FFLOOR:
1008     case ISD::FTRUNC:
1009     case ISD::STRICT_FTRUNC:
1010     case ISD::FROUNDEVEN:
1011     case ISD::STRICT_FROUNDEVEN:
1012     case ISD::FNEARBYINT:
1013     case ISD::STRICT_FNEARBYINT:
1014     case ISD::FRINT:
1015     case ISD::STRICT_FRINT: {
1016       // Replace fp rounding with their X86 specific equivalent so we don't
1017       // need 2 sets of patterns.
1018       unsigned Imm;
1019       switch (N->getOpcode()) {
1020       default: llvm_unreachable("Unexpected opcode!");
1021       case ISD::STRICT_FCEIL:
1022       case ISD::FCEIL:      Imm = 0xA; break;
1023       case ISD::STRICT_FFLOOR:
1024       case ISD::FFLOOR:     Imm = 0x9; break;
1025       case ISD::STRICT_FTRUNC:
1026       case ISD::FTRUNC:     Imm = 0xB; break;
1027       case ISD::STRICT_FROUNDEVEN:
1028       case ISD::FROUNDEVEN: Imm = 0x8; break;
1029       case ISD::STRICT_FNEARBYINT:
1030       case ISD::FNEARBYINT: Imm = 0xC; break;
1031       case ISD::STRICT_FRINT:
1032       case ISD::FRINT:      Imm = 0x4; break;
1033       }
1034       SDLoc dl(N);
1035       bool IsStrict = N->isStrictFPOpcode();
1036       SDValue Res;
1037       if (IsStrict)
1038         Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl,
1039                               {N->getValueType(0), MVT::Other},
1040                               {N->getOperand(0), N->getOperand(1),
1041                                CurDAG->getTargetConstant(Imm, dl, MVT::i32)});
1042       else
1043         Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0),
1044                               N->getOperand(0),
1045                               CurDAG->getTargetConstant(Imm, dl, MVT::i32));
1046       --I;
1047       CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1048       ++I;
1049       MadeChange = true;
1050       continue;
1051     }
1052     case X86ISD::FANDN:
1053     case X86ISD::FAND:
1054     case X86ISD::FOR:
1055     case X86ISD::FXOR: {
1056       // Widen scalar fp logic ops to vector to reduce isel patterns.
1057       // FIXME: Can we do this during lowering/combine.
1058       MVT VT = N->getSimpleValueType(0);
1059       if (VT.isVector() || VT == MVT::f128)
1060         break;
1061 
1062       MVT VecVT = VT == MVT::f64 ? MVT::v2f64 : MVT::v4f32;
1063       SDLoc dl(N);
1064       SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1065                                     N->getOperand(0));
1066       SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1067                                     N->getOperand(1));
1068 
1069       SDValue Res;
1070       if (Subtarget->hasSSE2()) {
1071         EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger();
1072         Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0);
1073         Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1);
1074         unsigned Opc;
1075         switch (N->getOpcode()) {
1076         default: llvm_unreachable("Unexpected opcode!");
1077         case X86ISD::FANDN: Opc = X86ISD::ANDNP; break;
1078         case X86ISD::FAND:  Opc = ISD::AND;      break;
1079         case X86ISD::FOR:   Opc = ISD::OR;       break;
1080         case X86ISD::FXOR:  Opc = ISD::XOR;      break;
1081         }
1082         Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1);
1083         Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res);
1084       } else {
1085         Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1);
1086       }
1087       Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res,
1088                             CurDAG->getIntPtrConstant(0, dl));
1089       --I;
1090       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1091       ++I;
1092       MadeChange = true;
1093       continue;
1094     }
1095     }
1096 
1097     if (OptLevel != CodeGenOpt::None &&
1098         // Only do this when the target can fold the load into the call or
1099         // jmp.
1100         !Subtarget->useIndirectThunkCalls() &&
1101         ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
1102          (N->getOpcode() == X86ISD::TC_RETURN &&
1103           (Subtarget->is64Bit() ||
1104            !getTargetMachine().isPositionIndependent())))) {
1105       /// Also try moving call address load from outside callseq_start to just
1106       /// before the call to allow it to be folded.
1107       ///
1108       ///     [Load chain]
1109       ///         ^
1110       ///         |
1111       ///       [Load]
1112       ///       ^    ^
1113       ///       |    |
1114       ///      /      \--
1115       ///     /          |
1116       ///[CALLSEQ_START] |
1117       ///     ^          |
1118       ///     |          |
1119       /// [LOAD/C2Reg]   |
1120       ///     |          |
1121       ///      \        /
1122       ///       \      /
1123       ///       [CALL]
1124       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
1125       SDValue Chain = N->getOperand(0);
1126       SDValue Load  = N->getOperand(1);
1127       if (!isCalleeLoad(Load, Chain, HasCallSeq))
1128         continue;
1129       moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
1130       ++NumLoadMoved;
1131       MadeChange = true;
1132       continue;
1133     }
1134 
1135     // Lower fpround and fpextend nodes that target the FP stack to be store and
1136     // load to the stack.  This is a gross hack.  We would like to simply mark
1137     // these as being illegal, but when we do that, legalize produces these when
1138     // it expands calls, then expands these in the same legalize pass.  We would
1139     // like dag combine to be able to hack on these between the call expansion
1140     // and the node legalization.  As such this pass basically does "really
1141     // late" legalization of these inline with the X86 isel pass.
1142     // FIXME: This should only happen when not compiled with -O0.
1143     switch (N->getOpcode()) {
1144     default: continue;
1145     case ISD::FP_ROUND:
1146     case ISD::FP_EXTEND:
1147     {
1148       MVT SrcVT = N->getOperand(0).getSimpleValueType();
1149       MVT DstVT = N->getSimpleValueType(0);
1150 
1151       // If any of the sources are vectors, no fp stack involved.
1152       if (SrcVT.isVector() || DstVT.isVector())
1153         continue;
1154 
1155       // If the source and destination are SSE registers, then this is a legal
1156       // conversion that should not be lowered.
1157       const X86TargetLowering *X86Lowering =
1158           static_cast<const X86TargetLowering *>(TLI);
1159       bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1160       bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1161       if (SrcIsSSE && DstIsSSE)
1162         continue;
1163 
1164       if (!SrcIsSSE && !DstIsSSE) {
1165         // If this is an FPStack extension, it is a noop.
1166         if (N->getOpcode() == ISD::FP_EXTEND)
1167           continue;
1168         // If this is a value-preserving FPStack truncation, it is a noop.
1169         if (N->getConstantOperandVal(1))
1170           continue;
1171       }
1172 
1173       // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1174       // FPStack has extload and truncstore.  SSE can fold direct loads into other
1175       // operations.  Based on this, decide what we want to do.
1176       MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT;
1177       SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1178       int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1179       MachinePointerInfo MPI =
1180           MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1181       SDLoc dl(N);
1182 
1183       // FIXME: optimize the case where the src/dest is a load or store?
1184 
1185       SDValue Store = CurDAG->getTruncStore(
1186           CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT);
1187       SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store,
1188                                           MemTmp, MPI, MemVT);
1189 
1190       // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1191       // extload we created.  This will cause general havok on the dag because
1192       // anything below the conversion could be folded into other existing nodes.
1193       // To avoid invalidating 'I', back it up to the convert node.
1194       --I;
1195       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1196       break;
1197     }
1198 
1199     //The sequence of events for lowering STRICT_FP versions of these nodes requires
1200     //dealing with the chain differently, as there is already a preexisting chain.
1201     case ISD::STRICT_FP_ROUND:
1202     case ISD::STRICT_FP_EXTEND:
1203     {
1204       MVT SrcVT = N->getOperand(1).getSimpleValueType();
1205       MVT DstVT = N->getSimpleValueType(0);
1206 
1207       // If any of the sources are vectors, no fp stack involved.
1208       if (SrcVT.isVector() || DstVT.isVector())
1209         continue;
1210 
1211       // If the source and destination are SSE registers, then this is a legal
1212       // conversion that should not be lowered.
1213       const X86TargetLowering *X86Lowering =
1214           static_cast<const X86TargetLowering *>(TLI);
1215       bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1216       bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1217       if (SrcIsSSE && DstIsSSE)
1218         continue;
1219 
1220       if (!SrcIsSSE && !DstIsSSE) {
1221         // If this is an FPStack extension, it is a noop.
1222         if (N->getOpcode() == ISD::STRICT_FP_EXTEND)
1223           continue;
1224         // If this is a value-preserving FPStack truncation, it is a noop.
1225         if (N->getConstantOperandVal(2))
1226           continue;
1227       }
1228 
1229       // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1230       // FPStack has extload and truncstore.  SSE can fold direct loads into other
1231       // operations.  Based on this, decide what we want to do.
1232       MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT;
1233       SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1234       int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1235       MachinePointerInfo MPI =
1236           MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1237       SDLoc dl(N);
1238 
1239       // FIXME: optimize the case where the src/dest is a load or store?
1240 
1241       //Since the operation is StrictFP, use the preexisting chain.
1242       SDValue Store, Result;
1243       if (!SrcIsSSE) {
1244         SDVTList VTs = CurDAG->getVTList(MVT::Other);
1245         SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp};
1246         Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT,
1247                                             MPI, /*Align*/ None,
1248                                             MachineMemOperand::MOStore);
1249         if (N->getFlags().hasNoFPExcept()) {
1250           SDNodeFlags Flags = Store->getFlags();
1251           Flags.setNoFPExcept(true);
1252           Store->setFlags(Flags);
1253         }
1254       } else {
1255         assert(SrcVT == MemVT && "Unexpected VT!");
1256         Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp,
1257                                  MPI);
1258       }
1259 
1260       if (!DstIsSSE) {
1261         SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other);
1262         SDValue Ops[] = {Store, MemTmp};
1263         Result = CurDAG->getMemIntrinsicNode(
1264             X86ISD::FLD, dl, VTs, Ops, MemVT, MPI,
1265             /*Align*/ None, MachineMemOperand::MOLoad);
1266         if (N->getFlags().hasNoFPExcept()) {
1267           SDNodeFlags Flags = Result->getFlags();
1268           Flags.setNoFPExcept(true);
1269           Result->setFlags(Flags);
1270         }
1271       } else {
1272         assert(DstVT == MemVT && "Unexpected VT!");
1273         Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI);
1274       }
1275 
1276       // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1277       // extload we created.  This will cause general havok on the dag because
1278       // anything below the conversion could be folded into other existing nodes.
1279       // To avoid invalidating 'I', back it up to the convert node.
1280       --I;
1281       CurDAG->ReplaceAllUsesWith(N, Result.getNode());
1282       break;
1283     }
1284     }
1285 
1286 
1287     // Now that we did that, the node is dead.  Increment the iterator to the
1288     // next node to process, then delete N.
1289     ++I;
1290     MadeChange = true;
1291   }
1292 
1293   // Remove any dead nodes that may have been left behind.
1294   if (MadeChange)
1295     CurDAG->RemoveDeadNodes();
1296 }
1297 
1298 // Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
1299 bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
1300   unsigned Opc = N->getMachineOpcode();
1301   if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
1302       Opc != X86::MOVSX64rr8)
1303     return false;
1304 
1305   SDValue N0 = N->getOperand(0);
1306 
1307   // We need to be extracting the lower bit of an extend.
1308   if (!N0.isMachineOpcode() ||
1309       N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
1310       N0.getConstantOperandVal(1) != X86::sub_8bit)
1311     return false;
1312 
1313   // We're looking for either a movsx or movzx to match the original opcode.
1314   unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
1315                                                 : X86::MOVSX32rr8_NOREX;
1316   SDValue N00 = N0.getOperand(0);
1317   if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
1318     return false;
1319 
1320   if (Opc == X86::MOVSX64rr8) {
1321     // If we had a sign extend from 8 to 64 bits. We still need to go from 32
1322     // to 64.
1323     MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
1324                                                    MVT::i64, N00);
1325     ReplaceUses(N, Extend);
1326   } else {
1327     // Ok we can drop this extend and just use the original extend.
1328     ReplaceUses(N, N00.getNode());
1329   }
1330 
1331   return true;
1332 }
1333 
1334 void X86DAGToDAGISel::PostprocessISelDAG() {
1335   // Skip peepholes at -O0.
1336   if (TM.getOptLevel() == CodeGenOpt::None)
1337     return;
1338 
1339   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
1340 
1341   bool MadeChange = false;
1342   while (Position != CurDAG->allnodes_begin()) {
1343     SDNode *N = &*--Position;
1344     // Skip dead nodes and any non-machine opcodes.
1345     if (N->use_empty() || !N->isMachineOpcode())
1346       continue;
1347 
1348     if (tryOptimizeRem8Extend(N)) {
1349       MadeChange = true;
1350       continue;
1351     }
1352 
1353     // Look for a TESTrr+ANDrr pattern where both operands of the test are
1354     // the same. Rewrite to remove the AND.
1355     unsigned Opc = N->getMachineOpcode();
1356     if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr ||
1357          Opc == X86::TEST32rr || Opc == X86::TEST64rr) &&
1358         N->getOperand(0) == N->getOperand(1) &&
1359         N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1360         N->getOperand(0).isMachineOpcode()) {
1361       SDValue And = N->getOperand(0);
1362       unsigned N0Opc = And.getMachineOpcode();
1363       if (N0Opc == X86::AND8rr || N0Opc == X86::AND16rr ||
1364           N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) {
1365         MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N),
1366                                                      MVT::i32,
1367                                                      And.getOperand(0),
1368                                                      And.getOperand(1));
1369         ReplaceUses(N, Test);
1370         MadeChange = true;
1371         continue;
1372       }
1373       if (N0Opc == X86::AND8rm || N0Opc == X86::AND16rm ||
1374           N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) {
1375         unsigned NewOpc;
1376         switch (N0Opc) {
1377         case X86::AND8rm:  NewOpc = X86::TEST8mr; break;
1378         case X86::AND16rm: NewOpc = X86::TEST16mr; break;
1379         case X86::AND32rm: NewOpc = X86::TEST32mr; break;
1380         case X86::AND64rm: NewOpc = X86::TEST64mr; break;
1381         }
1382 
1383         // Need to swap the memory and register operand.
1384         SDValue Ops[] = { And.getOperand(1),
1385                           And.getOperand(2),
1386                           And.getOperand(3),
1387                           And.getOperand(4),
1388                           And.getOperand(5),
1389                           And.getOperand(0),
1390                           And.getOperand(6)  /* Chain */ };
1391         MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1392                                                      MVT::i32, MVT::Other, Ops);
1393         CurDAG->setNodeMemRefs(
1394             Test, cast<MachineSDNode>(And.getNode())->memoperands());
1395         ReplaceUses(N, Test);
1396         MadeChange = true;
1397         continue;
1398       }
1399     }
1400 
1401     // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
1402     // used. We're doing this late so we can prefer to fold the AND into masked
1403     // comparisons. Doing that can be better for the live range of the mask
1404     // register.
1405     if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr ||
1406          Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) &&
1407         N->getOperand(0) == N->getOperand(1) &&
1408         N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1409         N->getOperand(0).isMachineOpcode() &&
1410         onlyUsesZeroFlag(SDValue(N, 0))) {
1411       SDValue And = N->getOperand(0);
1412       unsigned N0Opc = And.getMachineOpcode();
1413       // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
1414       // KAND instructions and KTEST use the same ISA feature.
1415       if (N0Opc == X86::KANDBrr ||
1416           (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) ||
1417           N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) {
1418         unsigned NewOpc;
1419         switch (Opc) {
1420         default: llvm_unreachable("Unexpected opcode!");
1421         case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break;
1422         case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break;
1423         case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break;
1424         case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break;
1425         }
1426         MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1427                                                       MVT::i32,
1428                                                       And.getOperand(0),
1429                                                       And.getOperand(1));
1430         ReplaceUses(N, KTest);
1431         MadeChange = true;
1432         continue;
1433       }
1434     }
1435 
1436     // Attempt to remove vectors moves that were inserted to zero upper bits.
1437     if (Opc != TargetOpcode::SUBREG_TO_REG)
1438       continue;
1439 
1440     unsigned SubRegIdx = N->getConstantOperandVal(2);
1441     if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
1442       continue;
1443 
1444     SDValue Move = N->getOperand(1);
1445     if (!Move.isMachineOpcode())
1446       continue;
1447 
1448     // Make sure its one of the move opcodes we recognize.
1449     switch (Move.getMachineOpcode()) {
1450     default:
1451       continue;
1452     case X86::VMOVAPDrr:       case X86::VMOVUPDrr:
1453     case X86::VMOVAPSrr:       case X86::VMOVUPSrr:
1454     case X86::VMOVDQArr:       case X86::VMOVDQUrr:
1455     case X86::VMOVAPDYrr:      case X86::VMOVUPDYrr:
1456     case X86::VMOVAPSYrr:      case X86::VMOVUPSYrr:
1457     case X86::VMOVDQAYrr:      case X86::VMOVDQUYrr:
1458     case X86::VMOVAPDZ128rr:   case X86::VMOVUPDZ128rr:
1459     case X86::VMOVAPSZ128rr:   case X86::VMOVUPSZ128rr:
1460     case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
1461     case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
1462     case X86::VMOVAPDZ256rr:   case X86::VMOVUPDZ256rr:
1463     case X86::VMOVAPSZ256rr:   case X86::VMOVUPSZ256rr:
1464     case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
1465     case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
1466       break;
1467     }
1468 
1469     SDValue In = Move.getOperand(0);
1470     if (!In.isMachineOpcode() ||
1471         In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
1472       continue;
1473 
1474     // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
1475     // the SHA instructions which use a legacy encoding.
1476     uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
1477     if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
1478         (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
1479         (TSFlags & X86II::EncodingMask) != X86II::XOP)
1480       continue;
1481 
1482     // Producing instruction is another vector instruction. We can drop the
1483     // move.
1484     CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
1485     MadeChange = true;
1486   }
1487 
1488   if (MadeChange)
1489     CurDAG->RemoveDeadNodes();
1490 }
1491 
1492 
1493 /// Emit any code that needs to be executed only in the main function.
1494 void X86DAGToDAGISel::emitSpecialCodeForMain() {
1495   if (Subtarget->isTargetCygMing()) {
1496     TargetLowering::ArgListTy Args;
1497     auto &DL = CurDAG->getDataLayout();
1498 
1499     TargetLowering::CallLoweringInfo CLI(*CurDAG);
1500     CLI.setChain(CurDAG->getRoot())
1501         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
1502                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
1503                    std::move(Args));
1504     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
1505     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
1506     CurDAG->setRoot(Result.second);
1507   }
1508 }
1509 
1510 void X86DAGToDAGISel::emitFunctionEntryCode() {
1511   // If this is main, emit special code for main.
1512   const Function &F = MF->getFunction();
1513   if (F.hasExternalLinkage() && F.getName() == "main")
1514     emitSpecialCodeForMain();
1515 }
1516 
1517 static bool isDispSafeForFrameIndex(int64_t Val) {
1518   // On 64-bit platforms, we can run into an issue where a frame index
1519   // includes a displacement that, when added to the explicit displacement,
1520   // will overflow the displacement field. Assuming that the frame index
1521   // displacement fits into a 31-bit integer  (which is only slightly more
1522   // aggressive than the current fundamental assumption that it fits into
1523   // a 32-bit integer), a 31-bit disp should always be safe.
1524   return isInt<31>(Val);
1525 }
1526 
1527 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
1528                                             X86ISelAddressMode &AM) {
1529   // We may have already matched a displacement and the caller just added the
1530   // symbolic displacement. So we still need to do the checks even if Offset
1531   // is zero.
1532 
1533   int64_t Val = AM.Disp + Offset;
1534 
1535   // Cannot combine ExternalSymbol displacements with integer offsets.
1536   if (Val != 0 && (AM.ES || AM.MCSym))
1537     return true;
1538 
1539   CodeModel::Model M = TM.getCodeModel();
1540   if (Subtarget->is64Bit()) {
1541     if (Val != 0 &&
1542         !X86::isOffsetSuitableForCodeModel(Val, M,
1543                                            AM.hasSymbolicDisplacement()))
1544       return true;
1545     // In addition to the checks required for a register base, check that
1546     // we do not try to use an unsafe Disp with a frame index.
1547     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1548         !isDispSafeForFrameIndex(Val))
1549       return true;
1550   }
1551   AM.Disp = Val;
1552   return false;
1553 
1554 }
1555 
1556 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
1557   SDValue Address = N->getOperand(1);
1558 
1559   // load gs:0 -> GS segment register.
1560   // load fs:0 -> FS segment register.
1561   //
1562   // This optimization is valid because the GNU TLS model defines that
1563   // gs:0 (or fs:0 on X86-64) contains its own address.
1564   // For more information see http://people.redhat.com/drepper/tls.pdf
1565   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
1566     if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
1567         !IndirectTlsSegRefs &&
1568         (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1569          Subtarget->isTargetFuchsia()))
1570       switch (N->getPointerInfo().getAddrSpace()) {
1571       case X86AS::GS:
1572         AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1573         return false;
1574       case X86AS::FS:
1575         AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1576         return false;
1577       // Address space X86AS::SS is not handled here, because it is not used to
1578       // address TLS areas.
1579       }
1580 
1581   return true;
1582 }
1583 
1584 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1585 /// mode. These wrap things that will resolve down into a symbol reference.
1586 /// If no match is possible, this returns true, otherwise it returns false.
1587 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
1588   // If the addressing mode already has a symbol as the displacement, we can
1589   // never match another symbol.
1590   if (AM.hasSymbolicDisplacement())
1591     return true;
1592 
1593   bool IsRIPRelTLS = false;
1594   bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1595   if (IsRIPRel) {
1596     SDValue Val = N.getOperand(0);
1597     if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
1598       IsRIPRelTLS = true;
1599   }
1600 
1601   // We can't use an addressing mode in the 64-bit large code model.
1602   // Global TLS addressing is an exception. In the medium code model,
1603   // we use can use a mode when RIP wrappers are present.
1604   // That signifies access to globals that are known to be "near",
1605   // such as the GOT itself.
1606   CodeModel::Model M = TM.getCodeModel();
1607   if (Subtarget->is64Bit() &&
1608       ((M == CodeModel::Large && !IsRIPRelTLS) ||
1609        (M == CodeModel::Medium && !IsRIPRel)))
1610     return true;
1611 
1612   // Base and index reg must be 0 in order to use %rip as base.
1613   if (IsRIPRel && AM.hasBaseOrIndexReg())
1614     return true;
1615 
1616   // Make a local copy in case we can't do this fold.
1617   X86ISelAddressMode Backup = AM;
1618 
1619   int64_t Offset = 0;
1620   SDValue N0 = N.getOperand(0);
1621   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1622     AM.GV = G->getGlobal();
1623     AM.SymbolFlags = G->getTargetFlags();
1624     Offset = G->getOffset();
1625   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1626     AM.CP = CP->getConstVal();
1627     AM.Alignment = CP->getAlign();
1628     AM.SymbolFlags = CP->getTargetFlags();
1629     Offset = CP->getOffset();
1630   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1631     AM.ES = S->getSymbol();
1632     AM.SymbolFlags = S->getTargetFlags();
1633   } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1634     AM.MCSym = S->getMCSymbol();
1635   } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1636     AM.JT = J->getIndex();
1637     AM.SymbolFlags = J->getTargetFlags();
1638   } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1639     AM.BlockAddr = BA->getBlockAddress();
1640     AM.SymbolFlags = BA->getTargetFlags();
1641     Offset = BA->getOffset();
1642   } else
1643     llvm_unreachable("Unhandled symbol reference node.");
1644 
1645   if (foldOffsetIntoAddress(Offset, AM)) {
1646     AM = Backup;
1647     return true;
1648   }
1649 
1650   if (IsRIPRel)
1651     AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
1652 
1653   // Commit the changes now that we know this fold is safe.
1654   return false;
1655 }
1656 
1657 /// Add the specified node to the specified addressing mode, returning true if
1658 /// it cannot be done. This just pattern matches for the addressing mode.
1659 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1660   if (matchAddressRecursively(N, AM, 0))
1661     return true;
1662 
1663   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1664   // a smaller encoding and avoids a scaled-index.
1665   if (AM.Scale == 2 &&
1666       AM.BaseType == X86ISelAddressMode::RegBase &&
1667       AM.Base_Reg.getNode() == nullptr) {
1668     AM.Base_Reg = AM.IndexReg;
1669     AM.Scale = 1;
1670   }
1671 
1672   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1673   // because it has a smaller encoding.
1674   // TODO: Which other code models can use this?
1675   switch (TM.getCodeModel()) {
1676     default: break;
1677     case CodeModel::Small:
1678     case CodeModel::Kernel:
1679       if (Subtarget->is64Bit() &&
1680           AM.Scale == 1 &&
1681           AM.BaseType == X86ISelAddressMode::RegBase &&
1682           AM.Base_Reg.getNode() == nullptr &&
1683           AM.IndexReg.getNode() == nullptr &&
1684           AM.SymbolFlags == X86II::MO_NO_FLAG &&
1685           AM.hasSymbolicDisplacement())
1686         AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
1687       break;
1688   }
1689 
1690   return false;
1691 }
1692 
1693 bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,
1694                                unsigned Depth) {
1695   // Add an artificial use to this node so that we can keep track of
1696   // it if it gets CSE'd with a different node.
1697   HandleSDNode Handle(N);
1698 
1699   X86ISelAddressMode Backup = AM;
1700   if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1701       !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1702     return false;
1703   AM = Backup;
1704 
1705   // Try again after commutating the operands.
1706   if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM,
1707                                Depth + 1) &&
1708       !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1))
1709     return false;
1710   AM = Backup;
1711 
1712   // If we couldn't fold both operands into the address at the same time,
1713   // see if we can just put each operand into a register and fold at least
1714   // the add.
1715   if (AM.BaseType == X86ISelAddressMode::RegBase &&
1716       !AM.Base_Reg.getNode() &&
1717       !AM.IndexReg.getNode()) {
1718     N = Handle.getValue();
1719     AM.Base_Reg = N.getOperand(0);
1720     AM.IndexReg = N.getOperand(1);
1721     AM.Scale = 1;
1722     return false;
1723   }
1724   N = Handle.getValue();
1725   return true;
1726 }
1727 
1728 // Insert a node into the DAG at least before the Pos node's position. This
1729 // will reposition the node as needed, and will assign it a node ID that is <=
1730 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1731 // IDs! The selection DAG must no longer depend on their uniqueness when this
1732 // is used.
1733 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
1734   if (N->getNodeId() == -1 ||
1735       (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1736        SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1737     DAG.RepositionNode(Pos->getIterator(), N.getNode());
1738     // Mark Node as invalid for pruning as after this it may be a successor to a
1739     // selected node but otherwise be in the same position of Pos.
1740     // Conservatively mark it with the same -abs(Id) to assure node id
1741     // invariant is preserved.
1742     N->setNodeId(Pos->getNodeId());
1743     SelectionDAGISel::InvalidateNodeId(N.getNode());
1744   }
1745 }
1746 
1747 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1748 // safe. This allows us to convert the shift and and into an h-register
1749 // extract and a scaled index. Returns false if the simplification is
1750 // performed.
1751 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1752                                       uint64_t Mask,
1753                                       SDValue Shift, SDValue X,
1754                                       X86ISelAddressMode &AM) {
1755   if (Shift.getOpcode() != ISD::SRL ||
1756       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1757       !Shift.hasOneUse())
1758     return true;
1759 
1760   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1761   if (ScaleLog <= 0 || ScaleLog >= 4 ||
1762       Mask != (0xffu << ScaleLog))
1763     return true;
1764 
1765   MVT VT = N.getSimpleValueType();
1766   SDLoc DL(N);
1767   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1768   SDValue NewMask = DAG.getConstant(0xff, DL, VT);
1769   SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1770   SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
1771   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
1772   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1773 
1774   // Insert the new nodes into the topological ordering. We must do this in
1775   // a valid topological ordering as nothing is going to go back and re-sort
1776   // these nodes. We continually insert before 'N' in sequence as this is
1777   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1778   // hierarchy left to express.
1779   insertDAGNode(DAG, N, Eight);
1780   insertDAGNode(DAG, N, Srl);
1781   insertDAGNode(DAG, N, NewMask);
1782   insertDAGNode(DAG, N, And);
1783   insertDAGNode(DAG, N, ShlCount);
1784   insertDAGNode(DAG, N, Shl);
1785   DAG.ReplaceAllUsesWith(N, Shl);
1786   DAG.RemoveDeadNode(N.getNode());
1787   AM.IndexReg = And;
1788   AM.Scale = (1 << ScaleLog);
1789   return false;
1790 }
1791 
1792 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1793 // allows us to fold the shift into this addressing mode. Returns false if the
1794 // transform succeeded.
1795 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1796                                         X86ISelAddressMode &AM) {
1797   SDValue Shift = N.getOperand(0);
1798 
1799   // Use a signed mask so that shifting right will insert sign bits. These
1800   // bits will be removed when we shift the result left so it doesn't matter
1801   // what we use. This might allow a smaller immediate encoding.
1802   int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();
1803 
1804   // If we have an any_extend feeding the AND, look through it to see if there
1805   // is a shift behind it. But only if the AND doesn't use the extended bits.
1806   // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
1807   bool FoundAnyExtend = false;
1808   if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
1809       Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
1810       isUInt<32>(Mask)) {
1811     FoundAnyExtend = true;
1812     Shift = Shift.getOperand(0);
1813   }
1814 
1815   if (Shift.getOpcode() != ISD::SHL ||
1816       !isa<ConstantSDNode>(Shift.getOperand(1)))
1817     return true;
1818 
1819   SDValue X = Shift.getOperand(0);
1820 
1821   // Not likely to be profitable if either the AND or SHIFT node has more
1822   // than one use (unless all uses are for address computation). Besides,
1823   // isel mechanism requires their node ids to be reused.
1824   if (!N.hasOneUse() || !Shift.hasOneUse())
1825     return true;
1826 
1827   // Verify that the shift amount is something we can fold.
1828   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1829   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1830     return true;
1831 
1832   MVT VT = N.getSimpleValueType();
1833   SDLoc DL(N);
1834   if (FoundAnyExtend) {
1835     SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
1836     insertDAGNode(DAG, N, NewX);
1837     X = NewX;
1838   }
1839 
1840   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
1841   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1842   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1843 
1844   // Insert the new nodes into the topological ordering. We must do this in
1845   // a valid topological ordering as nothing is going to go back and re-sort
1846   // these nodes. We continually insert before 'N' in sequence as this is
1847   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1848   // hierarchy left to express.
1849   insertDAGNode(DAG, N, NewMask);
1850   insertDAGNode(DAG, N, NewAnd);
1851   insertDAGNode(DAG, N, NewShift);
1852   DAG.ReplaceAllUsesWith(N, NewShift);
1853   DAG.RemoveDeadNode(N.getNode());
1854 
1855   AM.Scale = 1 << ShiftAmt;
1856   AM.IndexReg = NewAnd;
1857   return false;
1858 }
1859 
1860 // Implement some heroics to detect shifts of masked values where the mask can
1861 // be replaced by extending the shift and undoing that in the addressing mode
1862 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1863 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1864 // the addressing mode. This results in code such as:
1865 //
1866 //   int f(short *y, int *lookup_table) {
1867 //     ...
1868 //     return *y + lookup_table[*y >> 11];
1869 //   }
1870 //
1871 // Turning into:
1872 //   movzwl (%rdi), %eax
1873 //   movl %eax, %ecx
1874 //   shrl $11, %ecx
1875 //   addl (%rsi,%rcx,4), %eax
1876 //
1877 // Instead of:
1878 //   movzwl (%rdi), %eax
1879 //   movl %eax, %ecx
1880 //   shrl $9, %ecx
1881 //   andl $124, %rcx
1882 //   addl (%rsi,%rcx), %eax
1883 //
1884 // Note that this function assumes the mask is provided as a mask *after* the
1885 // value is shifted. The input chain may or may not match that, but computing
1886 // such a mask is trivial.
1887 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1888                                     uint64_t Mask,
1889                                     SDValue Shift, SDValue X,
1890                                     X86ISelAddressMode &AM) {
1891   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1892       !isa<ConstantSDNode>(Shift.getOperand(1)))
1893     return true;
1894 
1895   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1896   unsigned MaskLZ = countLeadingZeros(Mask);
1897   unsigned MaskTZ = countTrailingZeros(Mask);
1898 
1899   // The amount of shift we're trying to fit into the addressing mode is taken
1900   // from the trailing zeros of the mask.
1901   unsigned AMShiftAmt = MaskTZ;
1902 
1903   // There is nothing we can do here unless the mask is removing some bits.
1904   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1905   if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
1906 
1907   // We also need to ensure that mask is a continuous run of bits.
1908   if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1909 
1910   // Scale the leading zero count down based on the actual size of the value.
1911   // Also scale it down based on the size of the shift.
1912   unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1913   if (MaskLZ < ScaleDown)
1914     return true;
1915   MaskLZ -= ScaleDown;
1916 
1917   // The final check is to ensure that any masked out high bits of X are
1918   // already known to be zero. Otherwise, the mask has a semantic impact
1919   // other than masking out a couple of low bits. Unfortunately, because of
1920   // the mask, zero extensions will be removed from operands in some cases.
1921   // This code works extra hard to look through extensions because we can
1922   // replace them with zero extensions cheaply if necessary.
1923   bool ReplacingAnyExtend = false;
1924   if (X.getOpcode() == ISD::ANY_EXTEND) {
1925     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1926                           X.getOperand(0).getSimpleValueType().getSizeInBits();
1927     // Assume that we'll replace the any-extend with a zero-extend, and
1928     // narrow the search to the extended value.
1929     X = X.getOperand(0);
1930     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1931     ReplacingAnyExtend = true;
1932   }
1933   APInt MaskedHighBits =
1934     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1935   KnownBits Known = DAG.computeKnownBits(X);
1936   if (MaskedHighBits != Known.Zero) return true;
1937 
1938   // We've identified a pattern that can be transformed into a single shift
1939   // and an addressing mode. Make it so.
1940   MVT VT = N.getSimpleValueType();
1941   if (ReplacingAnyExtend) {
1942     assert(X.getValueType() != VT);
1943     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1944     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1945     insertDAGNode(DAG, N, NewX);
1946     X = NewX;
1947   }
1948   SDLoc DL(N);
1949   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1950   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1951   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1952   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1953 
1954   // Insert the new nodes into the topological ordering. We must do this in
1955   // a valid topological ordering as nothing is going to go back and re-sort
1956   // these nodes. We continually insert before 'N' in sequence as this is
1957   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1958   // hierarchy left to express.
1959   insertDAGNode(DAG, N, NewSRLAmt);
1960   insertDAGNode(DAG, N, NewSRL);
1961   insertDAGNode(DAG, N, NewSHLAmt);
1962   insertDAGNode(DAG, N, NewSHL);
1963   DAG.ReplaceAllUsesWith(N, NewSHL);
1964   DAG.RemoveDeadNode(N.getNode());
1965 
1966   AM.Scale = 1 << AMShiftAmt;
1967   AM.IndexReg = NewSRL;
1968   return false;
1969 }
1970 
1971 // Transform "(X >> SHIFT) & (MASK << C1)" to
1972 // "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
1973 // matched to a BEXTR later. Returns false if the simplification is performed.
1974 static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,
1975                                    uint64_t Mask,
1976                                    SDValue Shift, SDValue X,
1977                                    X86ISelAddressMode &AM,
1978                                    const X86Subtarget &Subtarget) {
1979   if (Shift.getOpcode() != ISD::SRL ||
1980       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1981       !Shift.hasOneUse() || !N.hasOneUse())
1982     return true;
1983 
1984   // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
1985   if (!Subtarget.hasTBM() &&
1986       !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
1987     return true;
1988 
1989   // We need to ensure that mask is a continuous run of bits.
1990   if (!isShiftedMask_64(Mask)) return true;
1991 
1992   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1993 
1994   // The amount of shift we're trying to fit into the addressing mode is taken
1995   // from the trailing zeros of the mask.
1996   unsigned AMShiftAmt = countTrailingZeros(Mask);
1997 
1998   // There is nothing we can do here unless the mask is removing some bits.
1999   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
2000   if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
2001 
2002   MVT VT = N.getSimpleValueType();
2003   SDLoc DL(N);
2004   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
2005   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
2006   SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT);
2007   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask);
2008   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
2009   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt);
2010 
2011   // Insert the new nodes into the topological ordering. We must do this in
2012   // a valid topological ordering as nothing is going to go back and re-sort
2013   // these nodes. We continually insert before 'N' in sequence as this is
2014   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2015   // hierarchy left to express.
2016   insertDAGNode(DAG, N, NewSRLAmt);
2017   insertDAGNode(DAG, N, NewSRL);
2018   insertDAGNode(DAG, N, NewMask);
2019   insertDAGNode(DAG, N, NewAnd);
2020   insertDAGNode(DAG, N, NewSHLAmt);
2021   insertDAGNode(DAG, N, NewSHL);
2022   DAG.ReplaceAllUsesWith(N, NewSHL);
2023   DAG.RemoveDeadNode(N.getNode());
2024 
2025   AM.Scale = 1 << AMShiftAmt;
2026   AM.IndexReg = NewAnd;
2027   return false;
2028 }
2029 
2030 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
2031                                               unsigned Depth) {
2032   SDLoc dl(N);
2033   LLVM_DEBUG({
2034     dbgs() << "MatchAddress: ";
2035     AM.dump(CurDAG);
2036   });
2037   // Limit recursion.
2038   if (Depth > 5)
2039     return matchAddressBase(N, AM);
2040 
2041   // If this is already a %rip relative address, we can only merge immediates
2042   // into it.  Instead of handling this in every case, we handle it here.
2043   // RIP relative addressing: %rip + 32-bit displacement!
2044   if (AM.isRIPRelative()) {
2045     // FIXME: JumpTable and ExternalSymbol address currently don't like
2046     // displacements.  It isn't very important, but this should be fixed for
2047     // consistency.
2048     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
2049       return true;
2050 
2051     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
2052       if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
2053         return false;
2054     return true;
2055   }
2056 
2057   switch (N.getOpcode()) {
2058   default: break;
2059   case ISD::LOCAL_RECOVER: {
2060     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
2061       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
2062         // Use the symbol and don't prefix it.
2063         AM.MCSym = ESNode->getMCSymbol();
2064         return false;
2065       }
2066     break;
2067   }
2068   case ISD::Constant: {
2069     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2070     if (!foldOffsetIntoAddress(Val, AM))
2071       return false;
2072     break;
2073   }
2074 
2075   case X86ISD::Wrapper:
2076   case X86ISD::WrapperRIP:
2077     if (!matchWrapper(N, AM))
2078       return false;
2079     break;
2080 
2081   case ISD::LOAD:
2082     if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
2083       return false;
2084     break;
2085 
2086   case ISD::FrameIndex:
2087     if (AM.BaseType == X86ISelAddressMode::RegBase &&
2088         AM.Base_Reg.getNode() == nullptr &&
2089         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
2090       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
2091       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
2092       return false;
2093     }
2094     break;
2095 
2096   case ISD::SHL:
2097     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2098       break;
2099 
2100     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2101       unsigned Val = CN->getZExtValue();
2102       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
2103       // that the base operand remains free for further matching. If
2104       // the base doesn't end up getting used, a post-processing step
2105       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
2106       if (Val == 1 || Val == 2 || Val == 3) {
2107         AM.Scale = 1 << Val;
2108         SDValue ShVal = N.getOperand(0);
2109 
2110         // Okay, we know that we have a scale by now.  However, if the scaled
2111         // value is an add of something and a constant, we can fold the
2112         // constant into the disp field here.
2113         if (CurDAG->isBaseWithConstantOffset(ShVal)) {
2114           AM.IndexReg = ShVal.getOperand(0);
2115           ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
2116           uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
2117           if (!foldOffsetIntoAddress(Disp, AM))
2118             return false;
2119         }
2120 
2121         AM.IndexReg = ShVal;
2122         return false;
2123       }
2124     }
2125     break;
2126 
2127   case ISD::SRL: {
2128     // Scale must not be used already.
2129     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2130 
2131     // We only handle up to 64-bit values here as those are what matter for
2132     // addressing mode optimizations.
2133     assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2134            "Unexpected value size!");
2135 
2136     SDValue And = N.getOperand(0);
2137     if (And.getOpcode() != ISD::AND) break;
2138     SDValue X = And.getOperand(0);
2139 
2140     // The mask used for the transform is expected to be post-shift, but we
2141     // found the shift first so just apply the shift to the mask before passing
2142     // it down.
2143     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
2144         !isa<ConstantSDNode>(And.getOperand(1)))
2145       break;
2146     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
2147 
2148     // Try to fold the mask and shift into the scale, and return false if we
2149     // succeed.
2150     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
2151       return false;
2152     break;
2153   }
2154 
2155   case ISD::SMUL_LOHI:
2156   case ISD::UMUL_LOHI:
2157     // A mul_lohi where we need the low part can be folded as a plain multiply.
2158     if (N.getResNo() != 0) break;
2159     LLVM_FALLTHROUGH;
2160   case ISD::MUL:
2161   case X86ISD::MUL_IMM:
2162     // X*[3,5,9] -> X+X*[2,4,8]
2163     if (AM.BaseType == X86ISelAddressMode::RegBase &&
2164         AM.Base_Reg.getNode() == nullptr &&
2165         AM.IndexReg.getNode() == nullptr) {
2166       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
2167         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
2168             CN->getZExtValue() == 9) {
2169           AM.Scale = unsigned(CN->getZExtValue())-1;
2170 
2171           SDValue MulVal = N.getOperand(0);
2172           SDValue Reg;
2173 
2174           // Okay, we know that we have a scale by now.  However, if the scaled
2175           // value is an add of something and a constant, we can fold the
2176           // constant into the disp field here.
2177           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
2178               isa<ConstantSDNode>(MulVal.getOperand(1))) {
2179             Reg = MulVal.getOperand(0);
2180             ConstantSDNode *AddVal =
2181               cast<ConstantSDNode>(MulVal.getOperand(1));
2182             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
2183             if (foldOffsetIntoAddress(Disp, AM))
2184               Reg = N.getOperand(0);
2185           } else {
2186             Reg = N.getOperand(0);
2187           }
2188 
2189           AM.IndexReg = AM.Base_Reg = Reg;
2190           return false;
2191         }
2192     }
2193     break;
2194 
2195   case ISD::SUB: {
2196     // Given A-B, if A can be completely folded into the address and
2197     // the index field with the index field unused, use -B as the index.
2198     // This is a win if a has multiple parts that can be folded into
2199     // the address. Also, this saves a mov if the base register has
2200     // other uses, since it avoids a two-address sub instruction, however
2201     // it costs an additional mov if the index register has other uses.
2202 
2203     // Add an artificial use to this node so that we can keep track of
2204     // it if it gets CSE'd with a different node.
2205     HandleSDNode Handle(N);
2206 
2207     // Test if the LHS of the sub can be folded.
2208     X86ISelAddressMode Backup = AM;
2209     if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
2210       N = Handle.getValue();
2211       AM = Backup;
2212       break;
2213     }
2214     N = Handle.getValue();
2215     // Test if the index field is free for use.
2216     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
2217       AM = Backup;
2218       break;
2219     }
2220 
2221     int Cost = 0;
2222     SDValue RHS = N.getOperand(1);
2223     // If the RHS involves a register with multiple uses, this
2224     // transformation incurs an extra mov, due to the neg instruction
2225     // clobbering its operand.
2226     if (!RHS.getNode()->hasOneUse() ||
2227         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
2228         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
2229         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
2230         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
2231          RHS.getOperand(0).getValueType() == MVT::i32))
2232       ++Cost;
2233     // If the base is a register with multiple uses, this
2234     // transformation may save a mov.
2235     if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
2236          !AM.Base_Reg.getNode()->hasOneUse()) ||
2237         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2238       --Cost;
2239     // If the folded LHS was interesting, this transformation saves
2240     // address arithmetic.
2241     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
2242         ((AM.Disp != 0) && (Backup.Disp == 0)) +
2243         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
2244       --Cost;
2245     // If it doesn't look like it may be an overall win, don't do it.
2246     if (Cost >= 0) {
2247       AM = Backup;
2248       break;
2249     }
2250 
2251     // Ok, the transformation is legal and appears profitable. Go for it.
2252     // Negation will be emitted later to avoid creating dangling nodes if this
2253     // was an unprofitable LEA.
2254     AM.IndexReg = RHS;
2255     AM.NegateIndex = true;
2256     AM.Scale = 1;
2257     return false;
2258   }
2259 
2260   case ISD::ADD:
2261     if (!matchAdd(N, AM, Depth))
2262       return false;
2263     break;
2264 
2265   case ISD::OR:
2266     // We want to look through a transform in InstCombine and DAGCombiner that
2267     // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
2268     // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
2269     // An 'lea' can then be used to match the shift (multiply) and add:
2270     // and $1, %esi
2271     // lea (%rsi, %rdi, 8), %rax
2272     if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
2273         !matchAdd(N, AM, Depth))
2274       return false;
2275     break;
2276 
2277   case ISD::AND: {
2278     // Perform some heroic transforms on an and of a constant-count shift
2279     // with a constant to enable use of the scaled offset field.
2280 
2281     // Scale must not be used already.
2282     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2283 
2284     // We only handle up to 64-bit values here as those are what matter for
2285     // addressing mode optimizations.
2286     assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2287            "Unexpected value size!");
2288 
2289     if (!isa<ConstantSDNode>(N.getOperand(1)))
2290       break;
2291 
2292     if (N.getOperand(0).getOpcode() == ISD::SRL) {
2293       SDValue Shift = N.getOperand(0);
2294       SDValue X = Shift.getOperand(0);
2295 
2296       uint64_t Mask = N.getConstantOperandVal(1);
2297 
2298       // Try to fold the mask and shift into an extract and scale.
2299       if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
2300         return false;
2301 
2302       // Try to fold the mask and shift directly into the scale.
2303       if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
2304         return false;
2305 
2306       // Try to fold the mask and shift into BEXTR and scale.
2307       if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
2308         return false;
2309     }
2310 
2311     // Try to swap the mask and shift to place shifts which can be done as
2312     // a scale on the outside of the mask.
2313     if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))
2314       return false;
2315 
2316     break;
2317   }
2318   case ISD::ZERO_EXTEND: {
2319     // Try to widen a zexted shift left to the same size as its use, so we can
2320     // match the shift as a scale factor.
2321     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2322       break;
2323     if (N.getOperand(0).getOpcode() != ISD::SHL || !N.getOperand(0).hasOneUse())
2324       break;
2325 
2326     // Give up if the shift is not a valid scale factor [1,2,3].
2327     SDValue Shl = N.getOperand(0);
2328     auto *ShAmtC = dyn_cast<ConstantSDNode>(Shl.getOperand(1));
2329     if (!ShAmtC || ShAmtC->getZExtValue() > 3)
2330       break;
2331 
2332     // The narrow shift must only shift out zero bits (it must be 'nuw').
2333     // That makes it safe to widen to the destination type.
2334     APInt HighZeros = APInt::getHighBitsSet(Shl.getValueSizeInBits(),
2335                                             ShAmtC->getZExtValue());
2336     if (!CurDAG->MaskedValueIsZero(Shl.getOperand(0), HighZeros))
2337       break;
2338 
2339     // zext (shl nuw i8 %x, C) to i32 --> shl (zext i8 %x to i32), (zext C)
2340     MVT VT = N.getSimpleValueType();
2341     SDLoc DL(N);
2342     SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Shl.getOperand(0));
2343     SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, Shl.getOperand(1));
2344 
2345     // Convert the shift to scale factor.
2346     AM.Scale = 1 << ShAmtC->getZExtValue();
2347     AM.IndexReg = Zext;
2348 
2349     insertDAGNode(*CurDAG, N, Zext);
2350     insertDAGNode(*CurDAG, N, NewShl);
2351     CurDAG->ReplaceAllUsesWith(N, NewShl);
2352     CurDAG->RemoveDeadNode(N.getNode());
2353     return false;
2354   }
2355   }
2356 
2357   return matchAddressBase(N, AM);
2358 }
2359 
2360 /// Helper for MatchAddress. Add the specified node to the
2361 /// specified addressing mode without any further recursion.
2362 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
2363   // Is the base register already occupied?
2364   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
2365     // If so, check to see if the scale index register is set.
2366     if (!AM.IndexReg.getNode()) {
2367       AM.IndexReg = N;
2368       AM.Scale = 1;
2369       return false;
2370     }
2371 
2372     // Otherwise, we cannot select it.
2373     return true;
2374   }
2375 
2376   // Default, generate it as a register.
2377   AM.BaseType = X86ISelAddressMode::RegBase;
2378   AM.Base_Reg = N;
2379   return false;
2380 }
2381 
2382 /// Helper for selectVectorAddr. Handles things that can be folded into a
2383 /// gather scatter address. The index register and scale should have already
2384 /// been handled.
2385 bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
2386   // TODO: Support other operations.
2387   switch (N.getOpcode()) {
2388   case ISD::Constant: {
2389     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2390     if (!foldOffsetIntoAddress(Val, AM))
2391       return false;
2392     break;
2393   }
2394   case X86ISD::Wrapper:
2395     if (!matchWrapper(N, AM))
2396       return false;
2397     break;
2398   }
2399 
2400   return matchAddressBase(N, AM);
2401 }
2402 
2403 bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr,
2404                                        SDValue IndexOp, SDValue ScaleOp,
2405                                        SDValue &Base, SDValue &Scale,
2406                                        SDValue &Index, SDValue &Disp,
2407                                        SDValue &Segment) {
2408   X86ISelAddressMode AM;
2409   AM.IndexReg = IndexOp;
2410   AM.Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
2411 
2412   unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace();
2413   if (AddrSpace == X86AS::GS)
2414     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2415   if (AddrSpace == X86AS::FS)
2416     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2417   if (AddrSpace == X86AS::SS)
2418     AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2419 
2420   SDLoc DL(BasePtr);
2421   MVT VT = BasePtr.getSimpleValueType();
2422 
2423   // Try to match into the base and displacement fields.
2424   if (matchVectorAddress(BasePtr, AM))
2425     return false;
2426 
2427   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2428   return true;
2429 }
2430 
2431 /// Returns true if it is able to pattern match an addressing mode.
2432 /// It returns the operands which make up the maximal addressing mode it can
2433 /// match by reference.
2434 ///
2435 /// Parent is the parent node of the addr operand that is being matched.  It
2436 /// is always a load, store, atomic node, or null.  It is only null when
2437 /// checking memory operands for inline asm nodes.
2438 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
2439                                  SDValue &Scale, SDValue &Index,
2440                                  SDValue &Disp, SDValue &Segment) {
2441   X86ISelAddressMode AM;
2442 
2443   if (Parent &&
2444       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
2445       // that are not a MemSDNode, and thus don't have proper addrspace info.
2446       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
2447       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
2448       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
2449       Parent->getOpcode() != X86ISD::ENQCMD && // Fixme
2450       Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme
2451       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
2452       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
2453     unsigned AddrSpace =
2454       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
2455     if (AddrSpace == X86AS::GS)
2456       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2457     if (AddrSpace == X86AS::FS)
2458       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2459     if (AddrSpace == X86AS::SS)
2460       AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2461   }
2462 
2463   // Save the DL and VT before calling matchAddress, it can invalidate N.
2464   SDLoc DL(N);
2465   MVT VT = N.getSimpleValueType();
2466 
2467   if (matchAddress(N, AM))
2468     return false;
2469 
2470   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2471   return true;
2472 }
2473 
2474 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
2475   // In static codegen with small code model, we can get the address of a label
2476   // into a register with 'movl'
2477   if (N->getOpcode() != X86ISD::Wrapper)
2478     return false;
2479 
2480   N = N.getOperand(0);
2481 
2482   // At least GNU as does not accept 'movl' for TPOFF relocations.
2483   // FIXME: We could use 'movl' when we know we are targeting MC.
2484   if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
2485     return false;
2486 
2487   Imm = N;
2488   if (N->getOpcode() != ISD::TargetGlobalAddress)
2489     return TM.getCodeModel() == CodeModel::Small;
2490 
2491   Optional<ConstantRange> CR =
2492       cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
2493   if (!CR)
2494     return TM.getCodeModel() == CodeModel::Small;
2495 
2496   return CR->getUnsignedMax().ult(1ull << 32);
2497 }
2498 
2499 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
2500                                          SDValue &Scale, SDValue &Index,
2501                                          SDValue &Disp, SDValue &Segment) {
2502   // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
2503   SDLoc DL(N);
2504 
2505   if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
2506     return false;
2507 
2508   RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
2509   if (RN && RN->getReg() == 0)
2510     Base = CurDAG->getRegister(0, MVT::i64);
2511   else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) {
2512     // Base could already be %rip, particularly in the x32 ABI.
2513     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2514                                                      MVT::i64), 0);
2515     Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2516                                          Base);
2517   }
2518 
2519   RN = dyn_cast<RegisterSDNode>(Index);
2520   if (RN && RN->getReg() == 0)
2521     Index = CurDAG->getRegister(0, MVT::i64);
2522   else {
2523     assert(Index.getValueType() == MVT::i32 &&
2524            "Expect to be extending 32-bit registers for use in LEA");
2525     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2526                                                      MVT::i64), 0);
2527     Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2528                                           Index);
2529   }
2530 
2531   return true;
2532 }
2533 
2534 /// Calls SelectAddr and determines if the maximal addressing
2535 /// mode it matches can be cost effectively emitted as an LEA instruction.
2536 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
2537                                     SDValue &Base, SDValue &Scale,
2538                                     SDValue &Index, SDValue &Disp,
2539                                     SDValue &Segment) {
2540   X86ISelAddressMode AM;
2541 
2542   // Save the DL and VT before calling matchAddress, it can invalidate N.
2543   SDLoc DL(N);
2544   MVT VT = N.getSimpleValueType();
2545 
2546   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
2547   // segments.
2548   SDValue Copy = AM.Segment;
2549   SDValue T = CurDAG->getRegister(0, MVT::i32);
2550   AM.Segment = T;
2551   if (matchAddress(N, AM))
2552     return false;
2553   assert (T == AM.Segment);
2554   AM.Segment = Copy;
2555 
2556   unsigned Complexity = 0;
2557   if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())
2558     Complexity = 1;
2559   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2560     Complexity = 4;
2561 
2562   if (AM.IndexReg.getNode())
2563     Complexity++;
2564 
2565   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
2566   // a simple shift.
2567   if (AM.Scale > 1)
2568     Complexity++;
2569 
2570   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
2571   // to a LEA. This is determined with some experimentation but is by no means
2572   // optimal (especially for code size consideration). LEA is nice because of
2573   // its three-address nature. Tweak the cost function again when we can run
2574   // convertToThreeAddress() at register allocation time.
2575   if (AM.hasSymbolicDisplacement()) {
2576     // For X86-64, always use LEA to materialize RIP-relative addresses.
2577     if (Subtarget->is64Bit())
2578       Complexity = 4;
2579     else
2580       Complexity += 2;
2581   }
2582 
2583   // Heuristic: try harder to form an LEA from ADD if the operands set flags.
2584   // Unlike ADD, LEA does not affect flags, so we will be less likely to require
2585   // duplicating flag-producing instructions later in the pipeline.
2586   if (N.getOpcode() == ISD::ADD) {
2587     auto isMathWithFlags = [](SDValue V) {
2588       switch (V.getOpcode()) {
2589       case X86ISD::ADD:
2590       case X86ISD::SUB:
2591       case X86ISD::ADC:
2592       case X86ISD::SBB:
2593       /* TODO: These opcodes can be added safely, but we may want to justify
2594                their inclusion for different reasons (better for reg-alloc).
2595       case X86ISD::SMUL:
2596       case X86ISD::UMUL:
2597       case X86ISD::OR:
2598       case X86ISD::XOR:
2599       case X86ISD::AND:
2600       */
2601         // Value 1 is the flag output of the node - verify it's not dead.
2602         return !SDValue(V.getNode(), 1).use_empty();
2603       default:
2604         return false;
2605       }
2606     };
2607     // TODO: This could be an 'or' rather than 'and' to make the transform more
2608     //       likely to happen. We might want to factor in whether there's a
2609     //       load folding opportunity for the math op that disappears with LEA.
2610     if (isMathWithFlags(N.getOperand(0)) && isMathWithFlags(N.getOperand(1)))
2611       Complexity++;
2612   }
2613 
2614   if (AM.Disp)
2615     Complexity++;
2616 
2617   // If it isn't worth using an LEA, reject it.
2618   if (Complexity <= 2)
2619     return false;
2620 
2621   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2622   return true;
2623 }
2624 
2625 /// This is only run on TargetGlobalTLSAddress nodes.
2626 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
2627                                         SDValue &Scale, SDValue &Index,
2628                                         SDValue &Disp, SDValue &Segment) {
2629   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
2630   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
2631 
2632   X86ISelAddressMode AM;
2633   AM.GV = GA->getGlobal();
2634   AM.Disp += GA->getOffset();
2635   AM.SymbolFlags = GA->getTargetFlags();
2636 
2637   MVT VT = N.getSimpleValueType();
2638   if (VT == MVT::i32) {
2639     AM.Scale = 1;
2640     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
2641   }
2642 
2643   getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);
2644   return true;
2645 }
2646 
2647 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2648   // Keep track of the original value type and whether this value was
2649   // truncated. If we see a truncation from pointer type to VT that truncates
2650   // bits that are known to be zero, we can use a narrow reference.
2651   EVT VT = N.getValueType();
2652   bool WasTruncated = false;
2653   if (N.getOpcode() == ISD::TRUNCATE) {
2654     WasTruncated = true;
2655     N = N.getOperand(0);
2656   }
2657 
2658   if (N.getOpcode() != X86ISD::Wrapper)
2659     return false;
2660 
2661   // We can only use non-GlobalValues as immediates if they were not truncated,
2662   // as we do not have any range information. If we have a GlobalValue and the
2663   // address was not truncated, we can select it as an operand directly.
2664   unsigned Opc = N.getOperand(0)->getOpcode();
2665   if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2666     Op = N.getOperand(0);
2667     // We can only select the operand directly if we didn't have to look past a
2668     // truncate.
2669     return !WasTruncated;
2670   }
2671 
2672   // Check that the global's range fits into VT.
2673   auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2674   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2675   if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2676     return false;
2677 
2678   // Okay, we can use a narrow reference.
2679   Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2680                                       GA->getOffset(), GA->getTargetFlags());
2681   return true;
2682 }
2683 
2684 bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
2685                                   SDValue &Base, SDValue &Scale,
2686                                   SDValue &Index, SDValue &Disp,
2687                                   SDValue &Segment) {
2688   assert(Root && P && "Unknown root/parent nodes");
2689   if (!ISD::isNON_EXTLoad(N.getNode()) ||
2690       !IsProfitableToFold(N, P, Root) ||
2691       !IsLegalToFold(N, P, Root, OptLevel))
2692     return false;
2693 
2694   return selectAddr(N.getNode(),
2695                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
2696 }
2697 
2698 bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
2699                                        SDValue &Base, SDValue &Scale,
2700                                        SDValue &Index, SDValue &Disp,
2701                                        SDValue &Segment) {
2702   assert(Root && P && "Unknown root/parent nodes");
2703   if (N->getOpcode() != X86ISD::VBROADCAST_LOAD ||
2704       !IsProfitableToFold(N, P, Root) ||
2705       !IsLegalToFold(N, P, Root, OptLevel))
2706     return false;
2707 
2708   return selectAddr(N.getNode(),
2709                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
2710 }
2711 
2712 /// Return an SDNode that returns the value of the global base register.
2713 /// Output instructions required to initialize the global base register,
2714 /// if necessary.
2715 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
2716   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
2717   auto &DL = MF->getDataLayout();
2718   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
2719 }
2720 
2721 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2722   if (N->getOpcode() == ISD::TRUNCATE)
2723     N = N->getOperand(0).getNode();
2724   if (N->getOpcode() != X86ISD::Wrapper)
2725     return false;
2726 
2727   auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2728   if (!GA)
2729     return false;
2730 
2731   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2732   return CR && CR->getSignedMin().sge(-1ull << Width) &&
2733          CR->getSignedMax().slt(1ull << Width);
2734 }
2735 
2736 static X86::CondCode getCondFromNode(SDNode *N) {
2737   assert(N->isMachineOpcode() && "Unexpected node");
2738   X86::CondCode CC = X86::COND_INVALID;
2739   unsigned Opc = N->getMachineOpcode();
2740   if (Opc == X86::JCC_1)
2741     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(1));
2742   else if (Opc == X86::SETCCr)
2743     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(0));
2744   else if (Opc == X86::SETCCm)
2745     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(5));
2746   else if (Opc == X86::CMOV16rr || Opc == X86::CMOV32rr ||
2747            Opc == X86::CMOV64rr)
2748     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(2));
2749   else if (Opc == X86::CMOV16rm || Opc == X86::CMOV32rm ||
2750            Opc == X86::CMOV64rm)
2751     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(6));
2752 
2753   return CC;
2754 }
2755 
2756 /// Test whether the given X86ISD::CMP node has any users that use a flag
2757 /// other than ZF.
2758 bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
2759   // Examine each user of the node.
2760   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2761          UI != UE; ++UI) {
2762     // Only check things that use the flags.
2763     if (UI.getUse().getResNo() != Flags.getResNo())
2764       continue;
2765     // Only examine CopyToReg uses that copy to EFLAGS.
2766     if (UI->getOpcode() != ISD::CopyToReg ||
2767         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2768       return false;
2769     // Examine each user of the CopyToReg use.
2770     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2771            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2772       // Only examine the Flag result.
2773       if (FlagUI.getUse().getResNo() != 1) continue;
2774       // Anything unusual: assume conservatively.
2775       if (!FlagUI->isMachineOpcode()) return false;
2776       // Examine the condition code of the user.
2777       X86::CondCode CC = getCondFromNode(*FlagUI);
2778 
2779       switch (CC) {
2780       // Comparisons which only use the zero flag.
2781       case X86::COND_E: case X86::COND_NE:
2782         continue;
2783       // Anything else: assume conservatively.
2784       default:
2785         return false;
2786       }
2787     }
2788   }
2789   return true;
2790 }
2791 
2792 /// Test whether the given X86ISD::CMP node has any uses which require the SF
2793 /// flag to be accurate.
2794 bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
2795   // Examine each user of the node.
2796   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2797          UI != UE; ++UI) {
2798     // Only check things that use the flags.
2799     if (UI.getUse().getResNo() != Flags.getResNo())
2800       continue;
2801     // Only examine CopyToReg uses that copy to EFLAGS.
2802     if (UI->getOpcode() != ISD::CopyToReg ||
2803         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2804       return false;
2805     // Examine each user of the CopyToReg use.
2806     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2807            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2808       // Only examine the Flag result.
2809       if (FlagUI.getUse().getResNo() != 1) continue;
2810       // Anything unusual: assume conservatively.
2811       if (!FlagUI->isMachineOpcode()) return false;
2812       // Examine the condition code of the user.
2813       X86::CondCode CC = getCondFromNode(*FlagUI);
2814 
2815       switch (CC) {
2816       // Comparisons which don't examine the SF flag.
2817       case X86::COND_A: case X86::COND_AE:
2818       case X86::COND_B: case X86::COND_BE:
2819       case X86::COND_E: case X86::COND_NE:
2820       case X86::COND_O: case X86::COND_NO:
2821       case X86::COND_P: case X86::COND_NP:
2822         continue;
2823       // Anything else: assume conservatively.
2824       default:
2825         return false;
2826       }
2827     }
2828   }
2829   return true;
2830 }
2831 
2832 static bool mayUseCarryFlag(X86::CondCode CC) {
2833   switch (CC) {
2834   // Comparisons which don't examine the CF flag.
2835   case X86::COND_O: case X86::COND_NO:
2836   case X86::COND_E: case X86::COND_NE:
2837   case X86::COND_S: case X86::COND_NS:
2838   case X86::COND_P: case X86::COND_NP:
2839   case X86::COND_L: case X86::COND_GE:
2840   case X86::COND_G: case X86::COND_LE:
2841     return false;
2842   // Anything else: assume conservatively.
2843   default:
2844     return true;
2845   }
2846 }
2847 
2848 /// Test whether the given node which sets flags has any uses which require the
2849 /// CF flag to be accurate.
2850  bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
2851   // Examine each user of the node.
2852   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2853          UI != UE; ++UI) {
2854     // Only check things that use the flags.
2855     if (UI.getUse().getResNo() != Flags.getResNo())
2856       continue;
2857 
2858     unsigned UIOpc = UI->getOpcode();
2859 
2860     if (UIOpc == ISD::CopyToReg) {
2861       // Only examine CopyToReg uses that copy to EFLAGS.
2862       if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2863         return false;
2864       // Examine each user of the CopyToReg use.
2865       for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2866            FlagUI != FlagUE; ++FlagUI) {
2867         // Only examine the Flag result.
2868         if (FlagUI.getUse().getResNo() != 1)
2869           continue;
2870         // Anything unusual: assume conservatively.
2871         if (!FlagUI->isMachineOpcode())
2872           return false;
2873         // Examine the condition code of the user.
2874         X86::CondCode CC = getCondFromNode(*FlagUI);
2875 
2876         if (mayUseCarryFlag(CC))
2877           return false;
2878       }
2879 
2880       // This CopyToReg is ok. Move on to the next user.
2881       continue;
2882     }
2883 
2884     // This might be an unselected node. So look for the pre-isel opcodes that
2885     // use flags.
2886     unsigned CCOpNo;
2887     switch (UIOpc) {
2888     default:
2889       // Something unusual. Be conservative.
2890       return false;
2891     case X86ISD::SETCC:       CCOpNo = 0; break;
2892     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
2893     case X86ISD::CMOV:        CCOpNo = 2; break;
2894     case X86ISD::BRCOND:      CCOpNo = 2; break;
2895     }
2896 
2897     X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);
2898     if (mayUseCarryFlag(CC))
2899       return false;
2900   }
2901   return true;
2902 }
2903 
2904 /// Check whether or not the chain ending in StoreNode is suitable for doing
2905 /// the {load; op; store} to modify transformation.
2906 static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2907                                         SDValue StoredVal, SelectionDAG *CurDAG,
2908                                         unsigned LoadOpNo,
2909                                         LoadSDNode *&LoadNode,
2910                                         SDValue &InputChain) {
2911   // Is the stored value result 0 of the operation?
2912   if (StoredVal.getResNo() != 0) return false;
2913 
2914   // Are there other uses of the operation other than the store?
2915   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2916 
2917   // Is the store non-extending and non-indexed?
2918   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2919     return false;
2920 
2921   SDValue Load = StoredVal->getOperand(LoadOpNo);
2922   // Is the stored value a non-extending and non-indexed load?
2923   if (!ISD::isNormalLoad(Load.getNode())) return false;
2924 
2925   // Return LoadNode by reference.
2926   LoadNode = cast<LoadSDNode>(Load);
2927 
2928   // Is store the only read of the loaded value?
2929   if (!Load.hasOneUse())
2930     return false;
2931 
2932   // Is the address of the store the same as the load?
2933   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2934       LoadNode->getOffset() != StoreNode->getOffset())
2935     return false;
2936 
2937   bool FoundLoad = false;
2938   SmallVector<SDValue, 4> ChainOps;
2939   SmallVector<const SDNode *, 4> LoopWorklist;
2940   SmallPtrSet<const SDNode *, 16> Visited;
2941   const unsigned int Max = 1024;
2942 
2943   //  Visualization of Load-Op-Store fusion:
2944   // -------------------------
2945   // Legend:
2946   //    *-lines = Chain operand dependencies.
2947   //    |-lines = Normal operand dependencies.
2948   //    Dependencies flow down and right. n-suffix references multiple nodes.
2949   //
2950   //        C                        Xn  C
2951   //        *                         *  *
2952   //        *                          * *
2953   //  Xn  A-LD    Yn                    TF         Yn
2954   //   *    * \   |                       *        |
2955   //    *   *  \  |                        *       |
2956   //     *  *   \ |             =>       A--LD_OP_ST
2957   //      * *    \|                                 \
2958   //       TF    OP                                  \
2959   //         *   | \                                  Zn
2960   //          *  |  \
2961   //         A-ST    Zn
2962   //
2963 
2964   // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2965   //                                      #2: Yn -> LD
2966   //                                      #3: ST -> Zn
2967 
2968   // Ensure the transform is safe by checking for the dual
2969   // dependencies to make sure we do not induce a loop.
2970 
2971   // As LD is a predecessor to both OP and ST we can do this by checking:
2972   //  a). if LD is a predecessor to a member of Xn or Yn.
2973   //  b). if a Zn is a predecessor to ST.
2974 
2975   // However, (b) can only occur through being a chain predecessor to
2976   // ST, which is the same as Zn being a member or predecessor of Xn,
2977   // which is a subset of LD being a predecessor of Xn. So it's
2978   // subsumed by check (a).
2979 
2980   SDValue Chain = StoreNode->getChain();
2981 
2982   // Gather X elements in ChainOps.
2983   if (Chain == Load.getValue(1)) {
2984     FoundLoad = true;
2985     ChainOps.push_back(Load.getOperand(0));
2986   } else if (Chain.getOpcode() == ISD::TokenFactor) {
2987     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2988       SDValue Op = Chain.getOperand(i);
2989       if (Op == Load.getValue(1)) {
2990         FoundLoad = true;
2991         // Drop Load, but keep its chain. No cycle check necessary.
2992         ChainOps.push_back(Load.getOperand(0));
2993         continue;
2994       }
2995       LoopWorklist.push_back(Op.getNode());
2996       ChainOps.push_back(Op);
2997     }
2998   }
2999 
3000   if (!FoundLoad)
3001     return false;
3002 
3003   // Worklist is currently Xn. Add Yn to worklist.
3004   for (SDValue Op : StoredVal->ops())
3005     if (Op.getNode() != LoadNode)
3006       LoopWorklist.push_back(Op.getNode());
3007 
3008   // Check (a) if Load is a predecessor to Xn + Yn
3009   if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
3010                                    true))
3011     return false;
3012 
3013   InputChain =
3014       CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
3015   return true;
3016 }
3017 
3018 // Change a chain of {load; op; store} of the same value into a simple op
3019 // through memory of that value, if the uses of the modified value and its
3020 // address are suitable.
3021 //
3022 // The tablegen pattern memory operand pattern is currently not able to match
3023 // the case where the EFLAGS on the original operation are used.
3024 //
3025 // To move this to tablegen, we'll need to improve tablegen to allow flags to
3026 // be transferred from a node in the pattern to the result node, probably with
3027 // a new keyword. For example, we have this
3028 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3029 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
3030 //   (implicit EFLAGS)]>;
3031 // but maybe need something like this
3032 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3033 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
3034 //   (transferrable EFLAGS)]>;
3035 //
3036 // Until then, we manually fold these and instruction select the operation
3037 // here.
3038 bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
3039   StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
3040   SDValue StoredVal = StoreNode->getOperand(1);
3041   unsigned Opc = StoredVal->getOpcode();
3042 
3043   // Before we try to select anything, make sure this is memory operand size
3044   // and opcode we can handle. Note that this must match the code below that
3045   // actually lowers the opcodes.
3046   EVT MemVT = StoreNode->getMemoryVT();
3047   if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
3048       MemVT != MVT::i8)
3049     return false;
3050 
3051   bool IsCommutable = false;
3052   bool IsNegate = false;
3053   switch (Opc) {
3054   default:
3055     return false;
3056   case X86ISD::SUB:
3057     IsNegate = isNullConstant(StoredVal.getOperand(0));
3058     break;
3059   case X86ISD::SBB:
3060     break;
3061   case X86ISD::ADD:
3062   case X86ISD::ADC:
3063   case X86ISD::AND:
3064   case X86ISD::OR:
3065   case X86ISD::XOR:
3066     IsCommutable = true;
3067     break;
3068   }
3069 
3070   unsigned LoadOpNo = IsNegate ? 1 : 0;
3071   LoadSDNode *LoadNode = nullptr;
3072   SDValue InputChain;
3073   if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3074                                    LoadNode, InputChain)) {
3075     if (!IsCommutable)
3076       return false;
3077 
3078     // This operation is commutable, try the other operand.
3079     LoadOpNo = 1;
3080     if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3081                                      LoadNode, InputChain))
3082       return false;
3083   }
3084 
3085   SDValue Base, Scale, Index, Disp, Segment;
3086   if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
3087                   Segment))
3088     return false;
3089 
3090   auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
3091                           unsigned Opc8) {
3092     switch (MemVT.getSimpleVT().SimpleTy) {
3093     case MVT::i64:
3094       return Opc64;
3095     case MVT::i32:
3096       return Opc32;
3097     case MVT::i16:
3098       return Opc16;
3099     case MVT::i8:
3100       return Opc8;
3101     default:
3102       llvm_unreachable("Invalid size!");
3103     }
3104   };
3105 
3106   MachineSDNode *Result;
3107   switch (Opc) {
3108   case X86ISD::SUB:
3109     // Handle negate.
3110     if (IsNegate) {
3111       unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,
3112                                      X86::NEG8m);
3113       const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3114       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3115                                       MVT::Other, Ops);
3116       break;
3117     }
3118    LLVM_FALLTHROUGH;
3119   case X86ISD::ADD:
3120     // Try to match inc/dec.
3121     if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) {
3122       bool IsOne = isOneConstant(StoredVal.getOperand(1));
3123       bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
3124       // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
3125       if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
3126         unsigned NewOpc =
3127           ((Opc == X86ISD::ADD) == IsOne)
3128               ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
3129               : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
3130         const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3131         Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3132                                         MVT::Other, Ops);
3133         break;
3134       }
3135     }
3136     LLVM_FALLTHROUGH;
3137   case X86ISD::ADC:
3138   case X86ISD::SBB:
3139   case X86ISD::AND:
3140   case X86ISD::OR:
3141   case X86ISD::XOR: {
3142     auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
3143       switch (Opc) {
3144       case X86ISD::ADD:
3145         return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
3146                             X86::ADD8mr);
3147       case X86ISD::ADC:
3148         return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
3149                             X86::ADC8mr);
3150       case X86ISD::SUB:
3151         return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
3152                             X86::SUB8mr);
3153       case X86ISD::SBB:
3154         return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
3155                             X86::SBB8mr);
3156       case X86ISD::AND:
3157         return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
3158                             X86::AND8mr);
3159       case X86ISD::OR:
3160         return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
3161       case X86ISD::XOR:
3162         return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
3163                             X86::XOR8mr);
3164       default:
3165         llvm_unreachable("Invalid opcode!");
3166       }
3167     };
3168     auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
3169       switch (Opc) {
3170       case X86ISD::ADD:
3171         return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
3172       case X86ISD::ADC:
3173         return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
3174       case X86ISD::SUB:
3175         return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
3176       case X86ISD::SBB:
3177         return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
3178       case X86ISD::AND:
3179         return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
3180       case X86ISD::OR:
3181         return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
3182       case X86ISD::XOR:
3183         return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
3184       default:
3185         llvm_unreachable("Invalid opcode!");
3186       }
3187     };
3188     auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
3189       switch (Opc) {
3190       case X86ISD::ADD:
3191         return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
3192                             X86::ADD8mi);
3193       case X86ISD::ADC:
3194         return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
3195                             X86::ADC8mi);
3196       case X86ISD::SUB:
3197         return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
3198                             X86::SUB8mi);
3199       case X86ISD::SBB:
3200         return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
3201                             X86::SBB8mi);
3202       case X86ISD::AND:
3203         return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
3204                             X86::AND8mi);
3205       case X86ISD::OR:
3206         return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
3207                             X86::OR8mi);
3208       case X86ISD::XOR:
3209         return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
3210                             X86::XOR8mi);
3211       default:
3212         llvm_unreachable("Invalid opcode!");
3213       }
3214     };
3215 
3216     unsigned NewOpc = SelectRegOpcode(Opc);
3217     SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
3218 
3219     // See if the operand is a constant that we can fold into an immediate
3220     // operand.
3221     if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
3222       int64_t OperandV = OperandC->getSExtValue();
3223 
3224       // Check if we can shrink the operand enough to fit in an immediate (or
3225       // fit into a smaller immediate) by negating it and switching the
3226       // operation.
3227       if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
3228           ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||
3229            (MemVT == MVT::i64 && !isInt<32>(OperandV) &&
3230             isInt<32>(-OperandV))) &&
3231           hasNoCarryFlagUses(StoredVal.getValue(1))) {
3232         OperandV = -OperandV;
3233         Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
3234       }
3235 
3236       // First try to fit this into an Imm8 operand. If it doesn't fit, then try
3237       // the larger immediate operand.
3238       if (MemVT != MVT::i8 && isInt<8>(OperandV)) {
3239         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
3240         NewOpc = SelectImm8Opcode(Opc);
3241       } else if (MemVT != MVT::i64 || isInt<32>(OperandV)) {
3242         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
3243         NewOpc = SelectImmOpcode(Opc);
3244       }
3245     }
3246 
3247     if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
3248       SDValue CopyTo =
3249           CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
3250                                StoredVal.getOperand(2), SDValue());
3251 
3252       const SDValue Ops[] = {Base,    Scale,   Index,  Disp,
3253                              Segment, Operand, CopyTo, CopyTo.getValue(1)};
3254       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
3255                                       Ops);
3256     } else {
3257       const SDValue Ops[] = {Base,    Scale,   Index,     Disp,
3258                              Segment, Operand, InputChain};
3259       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
3260                                       Ops);
3261     }
3262     break;
3263   }
3264   default:
3265     llvm_unreachable("Invalid opcode!");
3266   }
3267 
3268   MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
3269                                  LoadNode->getMemOperand()};
3270   CurDAG->setNodeMemRefs(Result, MemOps);
3271 
3272   // Update Load Chain uses as well.
3273   ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
3274   ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
3275   ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
3276   CurDAG->RemoveDeadNode(Node);
3277   return true;
3278 }
3279 
3280 // See if this is an  X & Mask  that we can match to BEXTR/BZHI.
3281 // Where Mask is one of the following patterns:
3282 //   a) x &  (1 << nbits) - 1
3283 //   b) x & ~(-1 << nbits)
3284 //   c) x &  (-1 >> (32 - y))
3285 //   d) x << (32 - y) >> (32 - y)
3286 bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
3287   assert(
3288       (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) &&
3289       "Should be either an and-mask, or right-shift after clearing high bits.");
3290 
3291   // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
3292   if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
3293     return false;
3294 
3295   MVT NVT = Node->getSimpleValueType(0);
3296 
3297   // Only supported for 32 and 64 bits.
3298   if (NVT != MVT::i32 && NVT != MVT::i64)
3299     return false;
3300 
3301   SDValue NBits;
3302 
3303   // If we have BMI2's BZHI, we are ok with muti-use patterns.
3304   // Else, if we only have BMI1's BEXTR, we require one-use.
3305   const bool CanHaveExtraUses = Subtarget->hasBMI2();
3306   auto checkUses = [CanHaveExtraUses](SDValue Op, unsigned NUses) {
3307     return CanHaveExtraUses ||
3308            Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
3309   };
3310   auto checkOneUse = [checkUses](SDValue Op) { return checkUses(Op, 1); };
3311   auto checkTwoUse = [checkUses](SDValue Op) { return checkUses(Op, 2); };
3312 
3313   auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) {
3314     if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) {
3315       assert(V.getSimpleValueType() == MVT::i32 &&
3316              V.getOperand(0).getSimpleValueType() == MVT::i64 &&
3317              "Expected i64 -> i32 truncation");
3318       V = V.getOperand(0);
3319     }
3320     return V;
3321   };
3322 
3323   // a) x & ((1 << nbits) + (-1))
3324   auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation,
3325                         &NBits](SDValue Mask) -> bool {
3326     // Match `add`. Must only have one use!
3327     if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
3328       return false;
3329     // We should be adding all-ones constant (i.e. subtracting one.)
3330     if (!isAllOnesConstant(Mask->getOperand(1)))
3331       return false;
3332     // Match `1 << nbits`. Might be truncated. Must only have one use!
3333     SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
3334     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3335       return false;
3336     if (!isOneConstant(M0->getOperand(0)))
3337       return false;
3338     NBits = M0->getOperand(1);
3339     return true;
3340   };
3341 
3342   auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) {
3343     V = peekThroughOneUseTruncation(V);
3344     return CurDAG->MaskedValueIsAllOnes(
3345         V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(),
3346                                 NVT.getSizeInBits()));
3347   };
3348 
3349   // b) x & ~(-1 << nbits)
3350   auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation,
3351                         &NBits](SDValue Mask) -> bool {
3352     // Match `~()`. Must only have one use!
3353     if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask))
3354       return false;
3355     // The -1 only has to be all-ones for the final Node's NVT.
3356     if (!isAllOnes(Mask->getOperand(1)))
3357       return false;
3358     // Match `-1 << nbits`. Might be truncated. Must only have one use!
3359     SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
3360     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3361       return false;
3362     // The -1 only has to be all-ones for the final Node's NVT.
3363     if (!isAllOnes(M0->getOperand(0)))
3364       return false;
3365     NBits = M0->getOperand(1);
3366     return true;
3367   };
3368 
3369   // Match potentially-truncated (bitwidth - y)
3370   auto matchShiftAmt = [checkOneUse, &NBits](SDValue ShiftAmt,
3371                                              unsigned Bitwidth) {
3372     // Skip over a truncate of the shift amount.
3373     if (ShiftAmt.getOpcode() == ISD::TRUNCATE) {
3374       ShiftAmt = ShiftAmt.getOperand(0);
3375       // The trunc should have been the only user of the real shift amount.
3376       if (!checkOneUse(ShiftAmt))
3377         return false;
3378     }
3379     // Match the shift amount as: (bitwidth - y). It should go away, too.
3380     if (ShiftAmt.getOpcode() != ISD::SUB)
3381       return false;
3382     auto V0 = dyn_cast<ConstantSDNode>(ShiftAmt.getOperand(0));
3383     if (!V0 || V0->getZExtValue() != Bitwidth)
3384       return false;
3385     NBits = ShiftAmt.getOperand(1);
3386     return true;
3387   };
3388 
3389   // c) x &  (-1 >> (32 - y))
3390   auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation,
3391                         matchShiftAmt](SDValue Mask) -> bool {
3392     // The mask itself may be truncated.
3393     Mask = peekThroughOneUseTruncation(Mask);
3394     unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits();
3395     // Match `l>>`. Must only have one use!
3396     if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
3397       return false;
3398     // We should be shifting truly all-ones constant.
3399     if (!isAllOnesConstant(Mask.getOperand(0)))
3400       return false;
3401     SDValue M1 = Mask.getOperand(1);
3402     // The shift amount should not be used externally.
3403     if (!checkOneUse(M1))
3404       return false;
3405     return matchShiftAmt(M1, Bitwidth);
3406   };
3407 
3408   SDValue X;
3409 
3410   // d) x << (32 - y) >> (32 - y)
3411   auto matchPatternD = [checkOneUse, checkTwoUse, matchShiftAmt,
3412                         &X](SDNode *Node) -> bool {
3413     if (Node->getOpcode() != ISD::SRL)
3414       return false;
3415     SDValue N0 = Node->getOperand(0);
3416     if (N0->getOpcode() != ISD::SHL || !checkOneUse(N0))
3417       return false;
3418     unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits();
3419     SDValue N1 = Node->getOperand(1);
3420     SDValue N01 = N0->getOperand(1);
3421     // Both of the shifts must be by the exact same value.
3422     // There should not be any uses of the shift amount outside of the pattern.
3423     if (N1 != N01 || !checkTwoUse(N1))
3424       return false;
3425     if (!matchShiftAmt(N1, Bitwidth))
3426       return false;
3427     X = N0->getOperand(0);
3428     return true;
3429   };
3430 
3431   auto matchLowBitMask = [matchPatternA, matchPatternB,
3432                           matchPatternC](SDValue Mask) -> bool {
3433     return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
3434   };
3435 
3436   if (Node->getOpcode() == ISD::AND) {
3437     X = Node->getOperand(0);
3438     SDValue Mask = Node->getOperand(1);
3439 
3440     if (matchLowBitMask(Mask)) {
3441       // Great.
3442     } else {
3443       std::swap(X, Mask);
3444       if (!matchLowBitMask(Mask))
3445         return false;
3446     }
3447   } else if (!matchPatternD(Node))
3448     return false;
3449 
3450   SDLoc DL(Node);
3451 
3452   // Truncate the shift amount.
3453   NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
3454   insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3455 
3456   // Insert 8-bit NBits into lowest 8 bits of 32-bit register.
3457   // All the other bits are undefined, we do not care about them.
3458   SDValue ImplDef = SDValue(
3459       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);
3460   insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);
3461 
3462   SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32);
3463   insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal);
3464   NBits = SDValue(
3465       CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::i32, ImplDef,
3466                              NBits, SRIdxVal), 0);
3467   insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3468 
3469   if (Subtarget->hasBMI2()) {
3470     // Great, just emit the the BZHI..
3471     if (NVT != MVT::i32) {
3472       // But have to place the bit count into the wide-enough register first.
3473       NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits);
3474       insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3475     }
3476 
3477     SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
3478     ReplaceNode(Node, Extract.getNode());
3479     SelectCode(Extract.getNode());
3480     return true;
3481   }
3482 
3483   // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is
3484   // *logically* shifted (potentially with one-use trunc inbetween),
3485   // and the truncation was the only use of the shift,
3486   // and if so look past one-use truncation.
3487   {
3488     SDValue RealX = peekThroughOneUseTruncation(X);
3489     // FIXME: only if the shift is one-use?
3490     if (RealX != X && RealX.getOpcode() == ISD::SRL)
3491       X = RealX;
3492   }
3493 
3494   MVT XVT = X.getSimpleValueType();
3495 
3496   // Else, emitting BEXTR requires one more step.
3497   // The 'control' of BEXTR has the pattern of:
3498   // [15...8 bit][ 7...0 bit] location
3499   // [ bit count][     shift] name
3500   // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
3501 
3502   // Shift NBits left by 8 bits, thus producing 'control'.
3503   // This makes the low 8 bits to be zero.
3504   SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
3505   SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);
3506   insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3507 
3508   // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
3509   // FIXME: only if the shift is one-use?
3510   if (X.getOpcode() == ISD::SRL) {
3511     SDValue ShiftAmt = X.getOperand(1);
3512     X = X.getOperand(0);
3513 
3514     assert(ShiftAmt.getValueType() == MVT::i8 &&
3515            "Expected shift amount to be i8");
3516 
3517     // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
3518     // We could zext to i16 in some form, but we intentionally don't do that.
3519     SDValue OrigShiftAmt = ShiftAmt;
3520     ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);
3521     insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
3522 
3523     // And now 'or' these low 8 bits of shift amount into the 'control'.
3524     Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);
3525     insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3526   }
3527 
3528   // But have to place the 'control' into the wide-enough register first.
3529   if (XVT != MVT::i32) {
3530     Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);
3531     insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3532   }
3533 
3534   // And finally, form the BEXTR itself.
3535   SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);
3536 
3537   // The 'X' was originally truncated. Do that now.
3538   if (XVT != NVT) {
3539     insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);
3540     Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);
3541   }
3542 
3543   ReplaceNode(Node, Extract.getNode());
3544   SelectCode(Extract.getNode());
3545 
3546   return true;
3547 }
3548 
3549 // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
3550 MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
3551   MVT NVT = Node->getSimpleValueType(0);
3552   SDLoc dl(Node);
3553 
3554   SDValue N0 = Node->getOperand(0);
3555   SDValue N1 = Node->getOperand(1);
3556 
3557   // If we have TBM we can use an immediate for the control. If we have BMI
3558   // we should only do this if the BEXTR instruction is implemented well.
3559   // Otherwise moving the control into a register makes this more costly.
3560   // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
3561   // hoisting the move immediate would make it worthwhile with a less optimal
3562   // BEXTR?
3563   bool PreferBEXTR =
3564       Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR());
3565   if (!PreferBEXTR && !Subtarget->hasBMI2())
3566     return nullptr;
3567 
3568   // Must have a shift right.
3569   if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
3570     return nullptr;
3571 
3572   // Shift can't have additional users.
3573   if (!N0->hasOneUse())
3574     return nullptr;
3575 
3576   // Only supported for 32 and 64 bits.
3577   if (NVT != MVT::i32 && NVT != MVT::i64)
3578     return nullptr;
3579 
3580   // Shift amount and RHS of and must be constant.
3581   ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
3582   ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3583   if (!MaskCst || !ShiftCst)
3584     return nullptr;
3585 
3586   // And RHS must be a mask.
3587   uint64_t Mask = MaskCst->getZExtValue();
3588   if (!isMask_64(Mask))
3589     return nullptr;
3590 
3591   uint64_t Shift = ShiftCst->getZExtValue();
3592   uint64_t MaskSize = countPopulation(Mask);
3593 
3594   // Don't interfere with something that can be handled by extracting AH.
3595   // TODO: If we are able to fold a load, BEXTR might still be better than AH.
3596   if (Shift == 8 && MaskSize == 8)
3597     return nullptr;
3598 
3599   // Make sure we are only using bits that were in the original value, not
3600   // shifted in.
3601   if (Shift + MaskSize > NVT.getSizeInBits())
3602     return nullptr;
3603 
3604   // BZHI, if available, is always fast, unlike BEXTR. But even if we decide
3605   // that we can't use BEXTR, it is only worthwhile using BZHI if the mask
3606   // does not fit into 32 bits. Load folding is not a sufficient reason.
3607   if (!PreferBEXTR && MaskSize <= 32)
3608     return nullptr;
3609 
3610   SDValue Control;
3611   unsigned ROpc, MOpc;
3612 
3613   if (!PreferBEXTR) {
3614     assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then.");
3615     // If we can't make use of BEXTR then we can't fuse shift+mask stages.
3616     // Let's perform the mask first, and apply shift later. Note that we need to
3617     // widen the mask to account for the fact that we'll apply shift afterwards!
3618     Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT);
3619     ROpc = NVT == MVT::i64 ? X86::BZHI64rr : X86::BZHI32rr;
3620     MOpc = NVT == MVT::i64 ? X86::BZHI64rm : X86::BZHI32rm;
3621     unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3622     Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
3623   } else {
3624     // The 'control' of BEXTR has the pattern of:
3625     // [15...8 bit][ 7...0 bit] location
3626     // [ bit count][     shift] name
3627     // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
3628     Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
3629     if (Subtarget->hasTBM()) {
3630       ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
3631       MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
3632     } else {
3633       assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then.");
3634       // BMI requires the immediate to placed in a register.
3635       ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
3636       MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
3637       unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3638       Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
3639     }
3640   }
3641 
3642   MachineSDNode *NewNode;
3643   SDValue Input = N0->getOperand(0);
3644   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3645   if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3646     SDValue Ops[] = {
3647         Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)};
3648     SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
3649     NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3650     // Update the chain.
3651     ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));
3652     // Record the mem-refs
3653     CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
3654   } else {
3655     NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control);
3656   }
3657 
3658   if (!PreferBEXTR) {
3659     // We still need to apply the shift.
3660     SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT);
3661     unsigned NewOpc = NVT == MVT::i64 ? X86::SHR64ri : X86::SHR32ri;
3662     NewNode =
3663         CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt);
3664   }
3665 
3666   return NewNode;
3667 }
3668 
3669 // Emit a PCMISTR(I/M) instruction.
3670 MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
3671                                              bool MayFoldLoad, const SDLoc &dl,
3672                                              MVT VT, SDNode *Node) {
3673   SDValue N0 = Node->getOperand(0);
3674   SDValue N1 = Node->getOperand(1);
3675   SDValue Imm = Node->getOperand(2);
3676   const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3677   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3678 
3679   // Try to fold a load. No need to check alignment.
3680   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3681   if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3682     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3683                       N1.getOperand(0) };
3684     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
3685     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3686     // Update the chain.
3687     ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
3688     // Record the mem-refs
3689     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3690     return CNode;
3691   }
3692 
3693   SDValue Ops[] = { N0, N1, Imm };
3694   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
3695   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3696   return CNode;
3697 }
3698 
3699 // Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
3700 // to emit a second instruction after this one. This is needed since we have two
3701 // copyToReg nodes glued before this and we need to continue that glue through.
3702 MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
3703                                              bool MayFoldLoad, const SDLoc &dl,
3704                                              MVT VT, SDNode *Node,
3705                                              SDValue &InFlag) {
3706   SDValue N0 = Node->getOperand(0);
3707   SDValue N2 = Node->getOperand(2);
3708   SDValue Imm = Node->getOperand(4);
3709   const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3710   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3711 
3712   // Try to fold a load. No need to check alignment.
3713   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3714   if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3715     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3716                       N2.getOperand(0), InFlag };
3717     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
3718     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3719     InFlag = SDValue(CNode, 3);
3720     // Update the chain.
3721     ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
3722     // Record the mem-refs
3723     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
3724     return CNode;
3725   }
3726 
3727   SDValue Ops[] = { N0, N2, Imm, InFlag };
3728   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
3729   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3730   InFlag = SDValue(CNode, 2);
3731   return CNode;
3732 }
3733 
3734 bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
3735   EVT VT = N->getValueType(0);
3736 
3737   // Only handle scalar shifts.
3738   if (VT.isVector())
3739     return false;
3740 
3741   // Narrower shifts only mask to 5 bits in hardware.
3742   unsigned Size = VT == MVT::i64 ? 64 : 32;
3743 
3744   SDValue OrigShiftAmt = N->getOperand(1);
3745   SDValue ShiftAmt = OrigShiftAmt;
3746   SDLoc DL(N);
3747 
3748   // Skip over a truncate of the shift amount.
3749   if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
3750     ShiftAmt = ShiftAmt->getOperand(0);
3751 
3752   // This function is called after X86DAGToDAGISel::matchBitExtract(),
3753   // so we are not afraid that we might mess up BZHI/BEXTR pattern.
3754 
3755   SDValue NewShiftAmt;
3756   if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
3757     SDValue Add0 = ShiftAmt->getOperand(0);
3758     SDValue Add1 = ShiftAmt->getOperand(1);
3759     // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
3760     // to avoid the ADD/SUB.
3761     if (isa<ConstantSDNode>(Add1) &&
3762         cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) {
3763       NewShiftAmt = Add0;
3764     // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
3765     // generate a NEG instead of a SUB of a constant.
3766     } else if (ShiftAmt->getOpcode() == ISD::SUB &&
3767                isa<ConstantSDNode>(Add0) &&
3768                cast<ConstantSDNode>(Add0)->getZExtValue() != 0 &&
3769                cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) {
3770       // Insert a negate op.
3771       // TODO: This isn't guaranteed to replace the sub if there is a logic cone
3772       // that uses it that's not a shift.
3773       EVT SubVT = ShiftAmt.getValueType();
3774       SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
3775       SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1);
3776       NewShiftAmt = Neg;
3777 
3778       // Insert these operands into a valid topological order so they can
3779       // get selected independently.
3780       insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
3781       insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
3782     } else
3783       return false;
3784   } else
3785     return false;
3786 
3787   if (NewShiftAmt.getValueType() != MVT::i8) {
3788     // Need to truncate the shift amount.
3789     NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
3790     // Add to a correct topological ordering.
3791     insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3792   }
3793 
3794   // Insert a new mask to keep the shift amount legal. This should be removed
3795   // by isel patterns.
3796   NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
3797                                 CurDAG->getConstant(Size - 1, DL, MVT::i8));
3798   // Place in a correct topological ordering.
3799   insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3800 
3801   SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
3802                                                    NewShiftAmt);
3803   if (UpdatedNode != N) {
3804     // If we found an existing node, we should replace ourselves with that node
3805     // and wait for it to be selected after its other users.
3806     ReplaceNode(N, UpdatedNode);
3807     return true;
3808   }
3809 
3810   // If the original shift amount is now dead, delete it so that we don't run
3811   // it through isel.
3812   if (OrigShiftAmt.getNode()->use_empty())
3813     CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
3814 
3815   // Now that we've optimized the shift amount, defer to normal isel to get
3816   // load folding and legacy vs BMI2 selection without repeating it here.
3817   SelectCode(N);
3818   return true;
3819 }
3820 
3821 bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) {
3822   MVT NVT = N->getSimpleValueType(0);
3823   unsigned Opcode = N->getOpcode();
3824   SDLoc dl(N);
3825 
3826   // For operations of the form (x << C1) op C2, check if we can use a smaller
3827   // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
3828   SDValue Shift = N->getOperand(0);
3829   SDValue N1 = N->getOperand(1);
3830 
3831   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
3832   if (!Cst)
3833     return false;
3834 
3835   int64_t Val = Cst->getSExtValue();
3836 
3837   // If we have an any_extend feeding the AND, look through it to see if there
3838   // is a shift behind it. But only if the AND doesn't use the extended bits.
3839   // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
3840   bool FoundAnyExtend = false;
3841   if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
3842       Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
3843       isUInt<32>(Val)) {
3844     FoundAnyExtend = true;
3845     Shift = Shift.getOperand(0);
3846   }
3847 
3848   if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())
3849     return false;
3850 
3851   // i8 is unshrinkable, i16 should be promoted to i32.
3852   if (NVT != MVT::i32 && NVT != MVT::i64)
3853     return false;
3854 
3855   ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
3856   if (!ShlCst)
3857     return false;
3858 
3859   uint64_t ShAmt = ShlCst->getZExtValue();
3860 
3861   // Make sure that we don't change the operation by removing bits.
3862   // This only matters for OR and XOR, AND is unaffected.
3863   uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;
3864   if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
3865     return false;
3866 
3867   // Check the minimum bitwidth for the new constant.
3868   // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
3869   auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {
3870     if (Opcode == ISD::AND) {
3871       // AND32ri is the same as AND64ri32 with zext imm.
3872       // Try this before sign extended immediates below.
3873       ShiftedVal = (uint64_t)Val >> ShAmt;
3874       if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
3875         return true;
3876       // Also swap order when the AND can become MOVZX.
3877       if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX)
3878         return true;
3879     }
3880     ShiftedVal = Val >> ShAmt;
3881     if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||
3882         (!isInt<32>(Val) && isInt<32>(ShiftedVal)))
3883       return true;
3884     if (Opcode != ISD::AND) {
3885       // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr
3886       ShiftedVal = (uint64_t)Val >> ShAmt;
3887       if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
3888         return true;
3889     }
3890     return false;
3891   };
3892 
3893   int64_t ShiftedVal;
3894   if (!CanShrinkImmediate(ShiftedVal))
3895     return false;
3896 
3897   // Ok, we can reorder to get a smaller immediate.
3898 
3899   // But, its possible the original immediate allowed an AND to become MOVZX.
3900   // Doing this late due to avoid the MakedValueIsZero call as late as
3901   // possible.
3902   if (Opcode == ISD::AND) {
3903     // Find the smallest zext this could possibly be.
3904     unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();
3905     ZExtWidth = PowerOf2Ceil(std::max(ZExtWidth, 8U));
3906 
3907     // Figure out which bits need to be zero to achieve that mask.
3908     APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),
3909                                             ZExtWidth);
3910     NeededMask &= ~Cst->getAPIntValue();
3911 
3912     if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask))
3913       return false;
3914   }
3915 
3916   SDValue X = Shift.getOperand(0);
3917   if (FoundAnyExtend) {
3918     SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);
3919     insertDAGNode(*CurDAG, SDValue(N, 0), NewX);
3920     X = NewX;
3921   }
3922 
3923   SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT);
3924   insertDAGNode(*CurDAG, SDValue(N, 0), NewCst);
3925   SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);
3926   insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp);
3927   SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,
3928                                    Shift.getOperand(1));
3929   ReplaceNode(N, NewSHL.getNode());
3930   SelectCode(NewSHL.getNode());
3931   return true;
3932 }
3933 
3934 bool X86DAGToDAGISel::matchVPTERNLOG(SDNode *Root, SDNode *ParentA,
3935                                      SDNode *ParentBC, SDValue A, SDValue B,
3936                                      SDValue C, uint8_t Imm) {
3937   assert(A.isOperandOf(ParentA));
3938   assert(B.isOperandOf(ParentBC));
3939   assert(C.isOperandOf(ParentBC));
3940 
3941   auto tryFoldLoadOrBCast =
3942       [this](SDNode *Root, SDNode *P, SDValue &L, SDValue &Base, SDValue &Scale,
3943              SDValue &Index, SDValue &Disp, SDValue &Segment) {
3944         if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
3945           return true;
3946 
3947         // Not a load, check for broadcast which may be behind a bitcast.
3948         if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
3949           P = L.getNode();
3950           L = L.getOperand(0);
3951         }
3952 
3953         if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
3954           return false;
3955 
3956         // Only 32 and 64 bit broadcasts are supported.
3957         auto *MemIntr = cast<MemIntrinsicSDNode>(L);
3958         unsigned Size = MemIntr->getMemoryVT().getSizeInBits();
3959         if (Size != 32 && Size != 64)
3960           return false;
3961 
3962         return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
3963       };
3964 
3965   bool FoldedLoad = false;
3966   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3967   if (tryFoldLoadOrBCast(Root, ParentBC, C, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3968     FoldedLoad = true;
3969   } else if (tryFoldLoadOrBCast(Root, ParentA, A, Tmp0, Tmp1, Tmp2, Tmp3,
3970                                 Tmp4)) {
3971     FoldedLoad = true;
3972     std::swap(A, C);
3973     // Swap bits 1/4 and 3/6.
3974     uint8_t OldImm = Imm;
3975     Imm = OldImm & 0xa5;
3976     if (OldImm & 0x02) Imm |= 0x10;
3977     if (OldImm & 0x10) Imm |= 0x02;
3978     if (OldImm & 0x08) Imm |= 0x40;
3979     if (OldImm & 0x40) Imm |= 0x08;
3980   } else if (tryFoldLoadOrBCast(Root, ParentBC, B, Tmp0, Tmp1, Tmp2, Tmp3,
3981                                 Tmp4)) {
3982     FoldedLoad = true;
3983     std::swap(B, C);
3984     // Swap bits 1/2 and 5/6.
3985     uint8_t OldImm = Imm;
3986     Imm = OldImm & 0x99;
3987     if (OldImm & 0x02) Imm |= 0x04;
3988     if (OldImm & 0x04) Imm |= 0x02;
3989     if (OldImm & 0x20) Imm |= 0x40;
3990     if (OldImm & 0x40) Imm |= 0x20;
3991   }
3992 
3993   SDLoc DL(Root);
3994 
3995   SDValue TImm = CurDAG->getTargetConstant(Imm, DL, MVT::i8);
3996 
3997   MVT NVT = Root->getSimpleValueType(0);
3998 
3999   MachineSDNode *MNode;
4000   if (FoldedLoad) {
4001     SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
4002 
4003     unsigned Opc;
4004     if (C.getOpcode() == X86ISD::VBROADCAST_LOAD) {
4005       auto *MemIntr = cast<MemIntrinsicSDNode>(C);
4006       unsigned EltSize = MemIntr->getMemoryVT().getSizeInBits();
4007       assert((EltSize == 32 || EltSize == 64) && "Unexpected broadcast size!");
4008 
4009       bool UseD = EltSize == 32;
4010       if (NVT.is128BitVector())
4011         Opc = UseD ? X86::VPTERNLOGDZ128rmbi : X86::VPTERNLOGQZ128rmbi;
4012       else if (NVT.is256BitVector())
4013         Opc = UseD ? X86::VPTERNLOGDZ256rmbi : X86::VPTERNLOGQZ256rmbi;
4014       else if (NVT.is512BitVector())
4015         Opc = UseD ? X86::VPTERNLOGDZrmbi : X86::VPTERNLOGQZrmbi;
4016       else
4017         llvm_unreachable("Unexpected vector size!");
4018     } else {
4019       bool UseD = NVT.getVectorElementType() == MVT::i32;
4020       if (NVT.is128BitVector())
4021         Opc = UseD ? X86::VPTERNLOGDZ128rmi : X86::VPTERNLOGQZ128rmi;
4022       else if (NVT.is256BitVector())
4023         Opc = UseD ? X86::VPTERNLOGDZ256rmi : X86::VPTERNLOGQZ256rmi;
4024       else if (NVT.is512BitVector())
4025         Opc = UseD ? X86::VPTERNLOGDZrmi : X86::VPTERNLOGQZrmi;
4026       else
4027         llvm_unreachable("Unexpected vector size!");
4028     }
4029 
4030     SDValue Ops[] = {A, B, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, TImm, C.getOperand(0)};
4031     MNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
4032 
4033     // Update the chain.
4034     ReplaceUses(C.getValue(1), SDValue(MNode, 1));
4035     // Record the mem-refs
4036     CurDAG->setNodeMemRefs(MNode, {cast<MemSDNode>(C)->getMemOperand()});
4037   } else {
4038     bool UseD = NVT.getVectorElementType() == MVT::i32;
4039     unsigned Opc;
4040     if (NVT.is128BitVector())
4041       Opc = UseD ? X86::VPTERNLOGDZ128rri : X86::VPTERNLOGQZ128rri;
4042     else if (NVT.is256BitVector())
4043       Opc = UseD ? X86::VPTERNLOGDZ256rri : X86::VPTERNLOGQZ256rri;
4044     else if (NVT.is512BitVector())
4045       Opc = UseD ? X86::VPTERNLOGDZrri : X86::VPTERNLOGQZrri;
4046     else
4047       llvm_unreachable("Unexpected vector size!");
4048 
4049     MNode = CurDAG->getMachineNode(Opc, DL, NVT, {A, B, C, TImm});
4050   }
4051 
4052   ReplaceUses(SDValue(Root, 0), SDValue(MNode, 0));
4053   CurDAG->RemoveDeadNode(Root);
4054   return true;
4055 }
4056 
4057 // Try to match two logic ops to a VPTERNLOG.
4058 // FIXME: Handle inverted inputs?
4059 // FIXME: Handle more complex patterns that use an operand more than once?
4060 bool X86DAGToDAGISel::tryVPTERNLOG(SDNode *N) {
4061   MVT NVT = N->getSimpleValueType(0);
4062 
4063   // Make sure we support VPTERNLOG.
4064   if (!NVT.isVector() || !Subtarget->hasAVX512() ||
4065       NVT.getVectorElementType() == MVT::i1)
4066     return false;
4067 
4068   // We need VLX for 128/256-bit.
4069   if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
4070     return false;
4071 
4072   SDValue N0 = N->getOperand(0);
4073   SDValue N1 = N->getOperand(1);
4074 
4075   auto getFoldableLogicOp = [](SDValue Op) {
4076     // Peek through single use bitcast.
4077     if (Op.getOpcode() == ISD::BITCAST && Op.hasOneUse())
4078       Op = Op.getOperand(0);
4079 
4080     if (!Op.hasOneUse())
4081       return SDValue();
4082 
4083     unsigned Opc = Op.getOpcode();
4084     if (Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR ||
4085         Opc == X86ISD::ANDNP)
4086       return Op;
4087 
4088     return SDValue();
4089   };
4090 
4091   SDValue A, FoldableOp;
4092   if ((FoldableOp = getFoldableLogicOp(N1))) {
4093     A = N0;
4094   } else if ((FoldableOp = getFoldableLogicOp(N0))) {
4095     A = N1;
4096   } else
4097     return false;
4098 
4099   SDValue B = FoldableOp.getOperand(0);
4100   SDValue C = FoldableOp.getOperand(1);
4101 
4102   // We can build the appropriate control immediate by performing the logic
4103   // operation we're matching using these constants for A, B, and C.
4104   const uint8_t TernlogMagicA = 0xf0;
4105   const uint8_t TernlogMagicB = 0xcc;
4106   const uint8_t TernlogMagicC = 0xaa;
4107 
4108   uint8_t Imm;
4109   switch (FoldableOp.getOpcode()) {
4110   default: llvm_unreachable("Unexpected opcode!");
4111   case ISD::AND:      Imm = TernlogMagicB & TernlogMagicC; break;
4112   case ISD::OR:       Imm = TernlogMagicB | TernlogMagicC; break;
4113   case ISD::XOR:      Imm = TernlogMagicB ^ TernlogMagicC; break;
4114   case X86ISD::ANDNP: Imm = ~(TernlogMagicB) & TernlogMagicC; break;
4115   }
4116 
4117   switch (N->getOpcode()) {
4118   default: llvm_unreachable("Unexpected opcode!");
4119   case X86ISD::ANDNP:
4120     if (A == N0)
4121       Imm &= ~TernlogMagicA;
4122     else
4123       Imm = ~(Imm) & TernlogMagicA;
4124     break;
4125   case ISD::AND: Imm &= TernlogMagicA; break;
4126   case ISD::OR:  Imm |= TernlogMagicA; break;
4127   case ISD::XOR: Imm ^= TernlogMagicA; break;
4128   }
4129 
4130   return matchVPTERNLOG(N, N, FoldableOp.getNode(), A, B, C, Imm);
4131 }
4132 
4133 /// If the high bits of an 'and' operand are known zero, try setting the
4134 /// high bits of an 'and' constant operand to produce a smaller encoding by
4135 /// creating a small, sign-extended negative immediate rather than a large
4136 /// positive one. This reverses a transform in SimplifyDemandedBits that
4137 /// shrinks mask constants by clearing bits. There is also a possibility that
4138 /// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
4139 /// case, just replace the 'and'. Return 'true' if the node is replaced.
4140 bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
4141   // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
4142   // have immediate operands.
4143   MVT VT = And->getSimpleValueType(0);
4144   if (VT != MVT::i32 && VT != MVT::i64)
4145     return false;
4146 
4147   auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
4148   if (!And1C)
4149     return false;
4150 
4151   // Bail out if the mask constant is already negative. It's can't shrink more.
4152   // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
4153   // patterns to use a 32-bit and instead of a 64-bit and by relying on the
4154   // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
4155   // are negative too.
4156   APInt MaskVal = And1C->getAPIntValue();
4157   unsigned MaskLZ = MaskVal.countLeadingZeros();
4158   if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
4159     return false;
4160 
4161   // Don't extend into the upper 32 bits of a 64 bit mask.
4162   if (VT == MVT::i64 && MaskLZ >= 32) {
4163     MaskLZ -= 32;
4164     MaskVal = MaskVal.trunc(32);
4165   }
4166 
4167   SDValue And0 = And->getOperand(0);
4168   APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
4169   APInt NegMaskVal = MaskVal | HighZeros;
4170 
4171   // If a negative constant would not allow a smaller encoding, there's no need
4172   // to continue. Only change the constant when we know it's a win.
4173   unsigned MinWidth = NegMaskVal.getMinSignedBits();
4174   if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
4175     return false;
4176 
4177   // Extend masks if we truncated above.
4178   if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
4179     NegMaskVal = NegMaskVal.zext(64);
4180     HighZeros = HighZeros.zext(64);
4181   }
4182 
4183   // The variable operand must be all zeros in the top bits to allow using the
4184   // new, negative constant as the mask.
4185   if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
4186     return false;
4187 
4188   // Check if the mask is -1. In that case, this is an unnecessary instruction
4189   // that escaped earlier analysis.
4190   if (NegMaskVal.isAllOnesValue()) {
4191     ReplaceNode(And, And0.getNode());
4192     return true;
4193   }
4194 
4195   // A negative mask allows a smaller encoding. Create a new 'and' node.
4196   SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
4197   SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
4198   ReplaceNode(And, NewAnd.getNode());
4199   SelectCode(NewAnd.getNode());
4200   return true;
4201 }
4202 
4203 static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,
4204                               bool FoldedBCast, bool Masked) {
4205 #define VPTESTM_CASE(VT, SUFFIX) \
4206 case MVT::VT: \
4207   if (Masked) \
4208     return IsTestN ? X86::VPTESTNM##SUFFIX##k: X86::VPTESTM##SUFFIX##k; \
4209   return IsTestN ? X86::VPTESTNM##SUFFIX : X86::VPTESTM##SUFFIX;
4210 
4211 
4212 #define VPTESTM_BROADCAST_CASES(SUFFIX) \
4213 default: llvm_unreachable("Unexpected VT!"); \
4214 VPTESTM_CASE(v4i32, DZ128##SUFFIX) \
4215 VPTESTM_CASE(v2i64, QZ128##SUFFIX) \
4216 VPTESTM_CASE(v8i32, DZ256##SUFFIX) \
4217 VPTESTM_CASE(v4i64, QZ256##SUFFIX) \
4218 VPTESTM_CASE(v16i32, DZ##SUFFIX) \
4219 VPTESTM_CASE(v8i64, QZ##SUFFIX)
4220 
4221 #define VPTESTM_FULL_CASES(SUFFIX) \
4222 VPTESTM_BROADCAST_CASES(SUFFIX) \
4223 VPTESTM_CASE(v16i8, BZ128##SUFFIX) \
4224 VPTESTM_CASE(v8i16, WZ128##SUFFIX) \
4225 VPTESTM_CASE(v32i8, BZ256##SUFFIX) \
4226 VPTESTM_CASE(v16i16, WZ256##SUFFIX) \
4227 VPTESTM_CASE(v64i8, BZ##SUFFIX) \
4228 VPTESTM_CASE(v32i16, WZ##SUFFIX)
4229 
4230   if (FoldedBCast) {
4231     switch (TestVT.SimpleTy) {
4232     VPTESTM_BROADCAST_CASES(rmb)
4233     }
4234   }
4235 
4236   if (FoldedLoad) {
4237     switch (TestVT.SimpleTy) {
4238     VPTESTM_FULL_CASES(rm)
4239     }
4240   }
4241 
4242   switch (TestVT.SimpleTy) {
4243   VPTESTM_FULL_CASES(rr)
4244   }
4245 
4246 #undef VPTESTM_FULL_CASES
4247 #undef VPTESTM_BROADCAST_CASES
4248 #undef VPTESTM_CASE
4249 }
4250 
4251 // Try to create VPTESTM instruction. If InMask is not null, it will be used
4252 // to form a masked operation.
4253 bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,
4254                                  SDValue InMask) {
4255   assert(Subtarget->hasAVX512() && "Expected AVX512!");
4256   assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&
4257          "Unexpected VT!");
4258 
4259   // Look for equal and not equal compares.
4260   ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
4261   if (CC != ISD::SETEQ && CC != ISD::SETNE)
4262     return false;
4263 
4264   SDValue SetccOp0 = Setcc.getOperand(0);
4265   SDValue SetccOp1 = Setcc.getOperand(1);
4266 
4267   // Canonicalize the all zero vector to the RHS.
4268   if (ISD::isBuildVectorAllZeros(SetccOp0.getNode()))
4269     std::swap(SetccOp0, SetccOp1);
4270 
4271   // See if we're comparing against zero.
4272   if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode()))
4273     return false;
4274 
4275   SDValue N0 = SetccOp0;
4276 
4277   MVT CmpVT = N0.getSimpleValueType();
4278   MVT CmpSVT = CmpVT.getVectorElementType();
4279 
4280   // Start with both operands the same. We'll try to refine this.
4281   SDValue Src0 = N0;
4282   SDValue Src1 = N0;
4283 
4284   {
4285     // Look through single use bitcasts.
4286     SDValue N0Temp = N0;
4287     if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())
4288       N0Temp = N0.getOperand(0);
4289 
4290      // Look for single use AND.
4291     if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {
4292       Src0 = N0Temp.getOperand(0);
4293       Src1 = N0Temp.getOperand(1);
4294     }
4295   }
4296 
4297   // Without VLX we need to widen the operation.
4298   bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();
4299 
4300   auto tryFoldLoadOrBCast = [&](SDNode *Root, SDNode *P, SDValue &L,
4301                                 SDValue &Base, SDValue &Scale, SDValue &Index,
4302                                 SDValue &Disp, SDValue &Segment) {
4303     // If we need to widen, we can't fold the load.
4304     if (!Widen)
4305       if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
4306         return true;
4307 
4308     // If we didn't fold a load, try to match broadcast. No widening limitation
4309     // for this. But only 32 and 64 bit types are supported.
4310     if (CmpSVT != MVT::i32 && CmpSVT != MVT::i64)
4311       return false;
4312 
4313     // Look through single use bitcasts.
4314     if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
4315       P = L.getNode();
4316       L = L.getOperand(0);
4317     }
4318 
4319     if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
4320       return false;
4321 
4322     auto *MemIntr = cast<MemIntrinsicSDNode>(L);
4323     if (MemIntr->getMemoryVT().getSizeInBits() != CmpSVT.getSizeInBits())
4324       return false;
4325 
4326     return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
4327   };
4328 
4329   // We can only fold loads if the sources are unique.
4330   bool CanFoldLoads = Src0 != Src1;
4331 
4332   bool FoldedLoad = false;
4333   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4334   if (CanFoldLoads) {
4335     FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src1, Tmp0, Tmp1, Tmp2,
4336                                     Tmp3, Tmp4);
4337     if (!FoldedLoad) {
4338       // And is commutative.
4339       FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src0, Tmp0, Tmp1,
4340                                       Tmp2, Tmp3, Tmp4);
4341       if (FoldedLoad)
4342         std::swap(Src0, Src1);
4343     }
4344   }
4345 
4346   bool FoldedBCast = FoldedLoad && Src1.getOpcode() == X86ISD::VBROADCAST_LOAD;
4347 
4348   bool IsMasked = InMask.getNode() != nullptr;
4349 
4350   SDLoc dl(Root);
4351 
4352   MVT ResVT = Setcc.getSimpleValueType();
4353   MVT MaskVT = ResVT;
4354   if (Widen) {
4355     // Widen the inputs using insert_subreg or copy_to_regclass.
4356     unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;
4357     unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;
4358     unsigned NumElts = CmpVT.getVectorNumElements() * Scale;
4359     CmpVT = MVT::getVectorVT(CmpSVT, NumElts);
4360     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
4361     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,
4362                                                      CmpVT), 0);
4363     Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);
4364 
4365     if (!FoldedBCast)
4366       Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);
4367 
4368     if (IsMasked) {
4369       // Widen the mask.
4370       unsigned RegClass = TLI->getRegClassFor(MaskVT)->getID();
4371       SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
4372       InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4373                                               dl, MaskVT, InMask, RC), 0);
4374     }
4375   }
4376 
4377   bool IsTestN = CC == ISD::SETEQ;
4378   unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,
4379                                IsMasked);
4380 
4381   MachineSDNode *CNode;
4382   if (FoldedLoad) {
4383     SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);
4384 
4385     if (IsMasked) {
4386       SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4387                         Src1.getOperand(0) };
4388       CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4389     } else {
4390       SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4391                         Src1.getOperand(0) };
4392       CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4393     }
4394 
4395     // Update the chain.
4396     ReplaceUses(Src1.getValue(1), SDValue(CNode, 1));
4397     // Record the mem-refs
4398     CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Src1)->getMemOperand()});
4399   } else {
4400     if (IsMasked)
4401       CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);
4402     else
4403       CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);
4404   }
4405 
4406   // If we widened, we need to shrink the mask VT.
4407   if (Widen) {
4408     unsigned RegClass = TLI->getRegClassFor(ResVT)->getID();
4409     SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
4410     CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4411                                    dl, ResVT, SDValue(CNode, 0), RC);
4412   }
4413 
4414   ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));
4415   CurDAG->RemoveDeadNode(Root);
4416   return true;
4417 }
4418 
4419 // Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it
4420 // into vpternlog.
4421 bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) {
4422   assert(N->getOpcode() == ISD::OR && "Unexpected opcode!");
4423 
4424   MVT NVT = N->getSimpleValueType(0);
4425 
4426   // Make sure we support VPTERNLOG.
4427   if (!NVT.isVector() || !Subtarget->hasAVX512())
4428     return false;
4429 
4430   // We need VLX for 128/256-bit.
4431   if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
4432     return false;
4433 
4434   SDValue N0 = N->getOperand(0);
4435   SDValue N1 = N->getOperand(1);
4436 
4437   // Canonicalize AND to LHS.
4438   if (N1.getOpcode() == ISD::AND)
4439     std::swap(N0, N1);
4440 
4441   if (N0.getOpcode() != ISD::AND ||
4442       N1.getOpcode() != X86ISD::ANDNP ||
4443       !N0.hasOneUse() || !N1.hasOneUse())
4444     return false;
4445 
4446   // ANDN is not commutable, use it to pick down A and C.
4447   SDValue A = N1.getOperand(0);
4448   SDValue C = N1.getOperand(1);
4449 
4450   // AND is commutable, if one operand matches A, the other operand is B.
4451   // Otherwise this isn't a match.
4452   SDValue B;
4453   if (N0.getOperand(0) == A)
4454     B = N0.getOperand(1);
4455   else if (N0.getOperand(1) == A)
4456     B = N0.getOperand(0);
4457   else
4458     return false;
4459 
4460   SDLoc dl(N);
4461   SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8);
4462   SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm);
4463   ReplaceNode(N, Ternlog.getNode());
4464 
4465   return matchVPTERNLOG(Ternlog.getNode(), Ternlog.getNode(), Ternlog.getNode(),
4466                         A, B, C, 0xCA);
4467 }
4468 
4469 void X86DAGToDAGISel::Select(SDNode *Node) {
4470   MVT NVT = Node->getSimpleValueType(0);
4471   unsigned Opcode = Node->getOpcode();
4472   SDLoc dl(Node);
4473 
4474   if (Node->isMachineOpcode()) {
4475     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
4476     Node->setNodeId(-1);
4477     return;   // Already selected.
4478   }
4479 
4480   switch (Opcode) {
4481   default: break;
4482   case ISD::INTRINSIC_VOID: {
4483     unsigned IntNo = Node->getConstantOperandVal(1);
4484     switch (IntNo) {
4485     default: break;
4486     case Intrinsic::x86_sse3_monitor:
4487     case Intrinsic::x86_monitorx:
4488     case Intrinsic::x86_clzero: {
4489       bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;
4490 
4491       unsigned Opc = 0;
4492       switch (IntNo) {
4493       default: llvm_unreachable("Unexpected intrinsic!");
4494       case Intrinsic::x86_sse3_monitor:
4495         if (!Subtarget->hasSSE3())
4496           break;
4497         Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;
4498         break;
4499       case Intrinsic::x86_monitorx:
4500         if (!Subtarget->hasMWAITX())
4501           break;
4502         Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;
4503         break;
4504       case Intrinsic::x86_clzero:
4505         if (!Subtarget->hasCLZERO())
4506           break;
4507         Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;
4508         break;
4509       }
4510 
4511       if (Opc) {
4512         unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;
4513         SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,
4514                                              Node->getOperand(2), SDValue());
4515         SDValue InFlag = Chain.getValue(1);
4516 
4517         if (IntNo == Intrinsic::x86_sse3_monitor ||
4518             IntNo == Intrinsic::x86_monitorx) {
4519           // Copy the other two operands to ECX and EDX.
4520           Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),
4521                                        InFlag);
4522           InFlag = Chain.getValue(1);
4523           Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),
4524                                        InFlag);
4525           InFlag = Chain.getValue(1);
4526         }
4527 
4528         MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
4529                                                       { Chain, InFlag});
4530         ReplaceNode(Node, CNode);
4531         return;
4532       }
4533 
4534       break;
4535     }
4536     case Intrinsic::x86_tileloadd64:
4537     case Intrinsic::x86_tileloaddt164:
4538     case Intrinsic::x86_tilestored64: {
4539       if (!Subtarget->hasAMXTILE())
4540         break;
4541       unsigned Opc;
4542       switch (IntNo) {
4543       default: llvm_unreachable("Unexpected intrinsic!");
4544       case Intrinsic::x86_tileloadd64:   Opc = X86::PTILELOADD; break;
4545       case Intrinsic::x86_tileloaddt164: Opc = X86::PTILELOADDT1; break;
4546       case Intrinsic::x86_tilestored64:  Opc = X86::PTILESTORED; break;
4547       }
4548       // FIXME: Match displacement and scale.
4549       unsigned TIndex = Node->getConstantOperandVal(2);
4550       SDValue TReg = getI8Imm(TIndex, dl);
4551       SDValue Base = Node->getOperand(3);
4552       SDValue Scale = getI8Imm(1, dl);
4553       SDValue Index = Node->getOperand(4);
4554       SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
4555       SDValue Segment = CurDAG->getRegister(0, MVT::i16);
4556       SDValue Chain = Node->getOperand(0);
4557       MachineSDNode *CNode;
4558       if (Opc == X86::PTILESTORED) {
4559         SDValue Ops[] = { Base, Scale, Index, Disp, Segment, TReg, Chain };
4560         CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
4561       } else {
4562         SDValue Ops[] = { TReg, Base, Scale, Index, Disp, Segment, Chain };
4563         CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
4564       }
4565       ReplaceNode(Node, CNode);
4566       return;
4567     }
4568     }
4569     break;
4570   }
4571   case ISD::BRIND: {
4572     if (Subtarget->isTargetNaCl())
4573       // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
4574       // leave the instruction alone.
4575       break;
4576     if (Subtarget->isTarget64BitILP32()) {
4577       // Converts a 32-bit register to a 64-bit, zero-extended version of
4578       // it. This is needed because x86-64 can do many things, but jmp %r32
4579       // ain't one of them.
4580       SDValue Target = Node->getOperand(1);
4581       assert(Target.getValueType() == MVT::i32 && "Unexpected VT!");
4582       SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, MVT::i64);
4583       SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
4584                                       Node->getOperand(0), ZextTarget);
4585       ReplaceNode(Node, Brind.getNode());
4586       SelectCode(ZextTarget.getNode());
4587       SelectCode(Brind.getNode());
4588       return;
4589     }
4590     break;
4591   }
4592   case X86ISD::GlobalBaseReg:
4593     ReplaceNode(Node, getGlobalBaseReg());
4594     return;
4595 
4596   case ISD::BITCAST:
4597     // Just drop all 128/256/512-bit bitcasts.
4598     if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
4599         NVT == MVT::f128) {
4600       ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
4601       CurDAG->RemoveDeadNode(Node);
4602       return;
4603     }
4604     break;
4605 
4606   case ISD::SRL:
4607     if (matchBitExtract(Node))
4608       return;
4609     LLVM_FALLTHROUGH;
4610   case ISD::SRA:
4611   case ISD::SHL:
4612     if (tryShiftAmountMod(Node))
4613       return;
4614     break;
4615 
4616   case X86ISD::VPTERNLOG: {
4617     uint8_t Imm = cast<ConstantSDNode>(Node->getOperand(3))->getZExtValue();
4618     if (matchVPTERNLOG(Node, Node, Node, Node->getOperand(0),
4619                        Node->getOperand(1), Node->getOperand(2), Imm))
4620       return;
4621     break;
4622   }
4623 
4624   case X86ISD::ANDNP:
4625     if (tryVPTERNLOG(Node))
4626       return;
4627     break;
4628 
4629   case ISD::AND:
4630     if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) {
4631       // Try to form a masked VPTESTM. Operands can be in either order.
4632       SDValue N0 = Node->getOperand(0);
4633       SDValue N1 = Node->getOperand(1);
4634       if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() &&
4635           tryVPTESTM(Node, N0, N1))
4636         return;
4637       if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
4638           tryVPTESTM(Node, N1, N0))
4639         return;
4640     }
4641 
4642     if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
4643       ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
4644       CurDAG->RemoveDeadNode(Node);
4645       return;
4646     }
4647     if (matchBitExtract(Node))
4648       return;
4649     if (AndImmShrink && shrinkAndImmediate(Node))
4650       return;
4651 
4652     LLVM_FALLTHROUGH;
4653   case ISD::OR:
4654   case ISD::XOR:
4655     if (tryShrinkShlLogicImm(Node))
4656       return;
4657     if (Opcode == ISD::OR && tryMatchBitSelect(Node))
4658       return;
4659     if (tryVPTERNLOG(Node))
4660       return;
4661 
4662     LLVM_FALLTHROUGH;
4663   case ISD::ADD:
4664   case ISD::SUB: {
4665     // Try to avoid folding immediates with multiple uses for optsize.
4666     // This code tries to select to register form directly to avoid going
4667     // through the isel table which might fold the immediate. We can't change
4668     // the patterns on the add/sub/and/or/xor with immediate paterns in the
4669     // tablegen files to check immediate use count without making the patterns
4670     // unavailable to the fast-isel table.
4671     if (!CurDAG->shouldOptForSize())
4672       break;
4673 
4674     // Only handle i8/i16/i32/i64.
4675     if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64)
4676       break;
4677 
4678     SDValue N0 = Node->getOperand(0);
4679     SDValue N1 = Node->getOperand(1);
4680 
4681     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
4682     if (!Cst)
4683       break;
4684 
4685     int64_t Val = Cst->getSExtValue();
4686 
4687     // Make sure its an immediate that is considered foldable.
4688     // FIXME: Handle unsigned 32 bit immediates for 64-bit AND.
4689     if (!isInt<8>(Val) && !isInt<32>(Val))
4690       break;
4691 
4692     // If this can match to INC/DEC, let it go.
4693     if (Opcode == ISD::ADD && (Val == 1 || Val == -1))
4694       break;
4695 
4696     // Check if we should avoid folding this immediate.
4697     if (!shouldAvoidImmediateInstFormsForSize(N1.getNode()))
4698       break;
4699 
4700     // We should not fold the immediate. So we need a register form instead.
4701     unsigned ROpc, MOpc;
4702     switch (NVT.SimpleTy) {
4703     default: llvm_unreachable("Unexpected VT!");
4704     case MVT::i8:
4705       switch (Opcode) {
4706       default: llvm_unreachable("Unexpected opcode!");
4707       case ISD::ADD: ROpc = X86::ADD8rr; MOpc = X86::ADD8rm; break;
4708       case ISD::SUB: ROpc = X86::SUB8rr; MOpc = X86::SUB8rm; break;
4709       case ISD::AND: ROpc = X86::AND8rr; MOpc = X86::AND8rm; break;
4710       case ISD::OR:  ROpc = X86::OR8rr;  MOpc = X86::OR8rm;  break;
4711       case ISD::XOR: ROpc = X86::XOR8rr; MOpc = X86::XOR8rm; break;
4712       }
4713       break;
4714     case MVT::i16:
4715       switch (Opcode) {
4716       default: llvm_unreachable("Unexpected opcode!");
4717       case ISD::ADD: ROpc = X86::ADD16rr; MOpc = X86::ADD16rm; break;
4718       case ISD::SUB: ROpc = X86::SUB16rr; MOpc = X86::SUB16rm; break;
4719       case ISD::AND: ROpc = X86::AND16rr; MOpc = X86::AND16rm; break;
4720       case ISD::OR:  ROpc = X86::OR16rr;  MOpc = X86::OR16rm;  break;
4721       case ISD::XOR: ROpc = X86::XOR16rr; MOpc = X86::XOR16rm; break;
4722       }
4723       break;
4724     case MVT::i32:
4725       switch (Opcode) {
4726       default: llvm_unreachable("Unexpected opcode!");
4727       case ISD::ADD: ROpc = X86::ADD32rr; MOpc = X86::ADD32rm; break;
4728       case ISD::SUB: ROpc = X86::SUB32rr; MOpc = X86::SUB32rm; break;
4729       case ISD::AND: ROpc = X86::AND32rr; MOpc = X86::AND32rm; break;
4730       case ISD::OR:  ROpc = X86::OR32rr;  MOpc = X86::OR32rm;  break;
4731       case ISD::XOR: ROpc = X86::XOR32rr; MOpc = X86::XOR32rm; break;
4732       }
4733       break;
4734     case MVT::i64:
4735       switch (Opcode) {
4736       default: llvm_unreachable("Unexpected opcode!");
4737       case ISD::ADD: ROpc = X86::ADD64rr; MOpc = X86::ADD64rm; break;
4738       case ISD::SUB: ROpc = X86::SUB64rr; MOpc = X86::SUB64rm; break;
4739       case ISD::AND: ROpc = X86::AND64rr; MOpc = X86::AND64rm; break;
4740       case ISD::OR:  ROpc = X86::OR64rr;  MOpc = X86::OR64rm;  break;
4741       case ISD::XOR: ROpc = X86::XOR64rr; MOpc = X86::XOR64rm; break;
4742       }
4743       break;
4744     }
4745 
4746     // Ok this is a AND/OR/XOR/ADD/SUB with constant.
4747 
4748     // If this is a not a subtract, we can still try to fold a load.
4749     if (Opcode != ISD::SUB) {
4750       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4751       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4752         SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
4753         SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
4754         MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4755         // Update the chain.
4756         ReplaceUses(N0.getValue(1), SDValue(CNode, 2));
4757         // Record the mem-refs
4758         CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()});
4759         ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4760         CurDAG->RemoveDeadNode(Node);
4761         return;
4762       }
4763     }
4764 
4765     CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1);
4766     return;
4767   }
4768 
4769   case X86ISD::SMUL:
4770     // i16/i32/i64 are handled with isel patterns.
4771     if (NVT != MVT::i8)
4772       break;
4773     LLVM_FALLTHROUGH;
4774   case X86ISD::UMUL: {
4775     SDValue N0 = Node->getOperand(0);
4776     SDValue N1 = Node->getOperand(1);
4777 
4778     unsigned LoReg, ROpc, MOpc;
4779     switch (NVT.SimpleTy) {
4780     default: llvm_unreachable("Unsupported VT!");
4781     case MVT::i8:
4782       LoReg = X86::AL;
4783       ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;
4784       MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;
4785       break;
4786     case MVT::i16:
4787       LoReg = X86::AX;
4788       ROpc = X86::MUL16r;
4789       MOpc = X86::MUL16m;
4790       break;
4791     case MVT::i32:
4792       LoReg = X86::EAX;
4793       ROpc = X86::MUL32r;
4794       MOpc = X86::MUL32m;
4795       break;
4796     case MVT::i64:
4797       LoReg = X86::RAX;
4798       ROpc = X86::MUL64r;
4799       MOpc = X86::MUL64m;
4800       break;
4801     }
4802 
4803     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4804     bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4805     // Multiply is commutative.
4806     if (!FoldedLoad) {
4807       FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4808       if (FoldedLoad)
4809         std::swap(N0, N1);
4810     }
4811 
4812     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
4813                                           N0, SDValue()).getValue(1);
4814 
4815     MachineSDNode *CNode;
4816     if (FoldedLoad) {
4817       // i16/i32/i64 use an instruction that produces a low and high result even
4818       // though only the low result is used.
4819       SDVTList VTs;
4820       if (NVT == MVT::i8)
4821         VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
4822       else
4823         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);
4824 
4825       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4826                         InFlag };
4827       CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4828 
4829       // Update the chain.
4830       ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));
4831       // Record the mem-refs
4832       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4833     } else {
4834       // i16/i32/i64 use an instruction that produces a low and high result even
4835       // though only the low result is used.
4836       SDVTList VTs;
4837       if (NVT == MVT::i8)
4838         VTs = CurDAG->getVTList(NVT, MVT::i32);
4839       else
4840         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
4841 
4842       CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InFlag});
4843     }
4844 
4845     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4846     ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));
4847     CurDAG->RemoveDeadNode(Node);
4848     return;
4849   }
4850 
4851   case ISD::SMUL_LOHI:
4852   case ISD::UMUL_LOHI: {
4853     SDValue N0 = Node->getOperand(0);
4854     SDValue N1 = Node->getOperand(1);
4855 
4856     unsigned Opc, MOpc;
4857     unsigned LoReg, HiReg;
4858     bool IsSigned = Opcode == ISD::SMUL_LOHI;
4859     bool UseMULX = !IsSigned && Subtarget->hasBMI2();
4860     bool UseMULXHi = UseMULX && SDValue(Node, 0).use_empty();
4861     switch (NVT.SimpleTy) {
4862     default: llvm_unreachable("Unsupported VT!");
4863     case MVT::i32:
4864       Opc  = UseMULXHi ? X86::MULX32Hrr :
4865              UseMULX ? X86::MULX32rr :
4866              IsSigned ? X86::IMUL32r : X86::MUL32r;
4867       MOpc = UseMULXHi ? X86::MULX32Hrm :
4868              UseMULX ? X86::MULX32rm :
4869              IsSigned ? X86::IMUL32m : X86::MUL32m;
4870       LoReg = UseMULX ? X86::EDX : X86::EAX;
4871       HiReg = X86::EDX;
4872       break;
4873     case MVT::i64:
4874       Opc  = UseMULXHi ? X86::MULX64Hrr :
4875              UseMULX ? X86::MULX64rr :
4876              IsSigned ? X86::IMUL64r : X86::MUL64r;
4877       MOpc = UseMULXHi ? X86::MULX64Hrm :
4878              UseMULX ? X86::MULX64rm :
4879              IsSigned ? X86::IMUL64m : X86::MUL64m;
4880       LoReg = UseMULX ? X86::RDX : X86::RAX;
4881       HiReg = X86::RDX;
4882       break;
4883     }
4884 
4885     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4886     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4887     // Multiply is commmutative.
4888     if (!foldedLoad) {
4889       foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4890       if (foldedLoad)
4891         std::swap(N0, N1);
4892     }
4893 
4894     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
4895                                           N0, SDValue()).getValue(1);
4896     SDValue ResHi, ResLo;
4897     if (foldedLoad) {
4898       SDValue Chain;
4899       MachineSDNode *CNode = nullptr;
4900       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4901                         InFlag };
4902       if (UseMULXHi) {
4903         SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
4904         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4905         ResHi = SDValue(CNode, 0);
4906         Chain = SDValue(CNode, 1);
4907       } else if (UseMULX) {
4908         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other);
4909         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4910         ResHi = SDValue(CNode, 0);
4911         ResLo = SDValue(CNode, 1);
4912         Chain = SDValue(CNode, 2);
4913       } else {
4914         SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
4915         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4916         Chain = SDValue(CNode, 0);
4917         InFlag = SDValue(CNode, 1);
4918       }
4919 
4920       // Update the chain.
4921       ReplaceUses(N1.getValue(1), Chain);
4922       // Record the mem-refs
4923       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4924     } else {
4925       SDValue Ops[] = { N1, InFlag };
4926       if (UseMULXHi) {
4927         SDVTList VTs = CurDAG->getVTList(NVT);
4928         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4929         ResHi = SDValue(CNode, 0);
4930       } else if (UseMULX) {
4931         SDVTList VTs = CurDAG->getVTList(NVT, NVT);
4932         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4933         ResHi = SDValue(CNode, 0);
4934         ResLo = SDValue(CNode, 1);
4935       } else {
4936         SDVTList VTs = CurDAG->getVTList(MVT::Glue);
4937         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4938         InFlag = SDValue(CNode, 0);
4939       }
4940     }
4941 
4942     // Copy the low half of the result, if it is needed.
4943     if (!SDValue(Node, 0).use_empty()) {
4944       if (!ResLo) {
4945         assert(LoReg && "Register for low half is not defined!");
4946         ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,
4947                                        NVT, InFlag);
4948         InFlag = ResLo.getValue(2);
4949       }
4950       ReplaceUses(SDValue(Node, 0), ResLo);
4951       LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
4952                  dbgs() << '\n');
4953     }
4954     // Copy the high half of the result, if it is needed.
4955     if (!SDValue(Node, 1).use_empty()) {
4956       if (!ResHi) {
4957         assert(HiReg && "Register for high half is not defined!");
4958         ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,
4959                                        NVT, InFlag);
4960         InFlag = ResHi.getValue(2);
4961       }
4962       ReplaceUses(SDValue(Node, 1), ResHi);
4963       LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
4964                  dbgs() << '\n');
4965     }
4966 
4967     CurDAG->RemoveDeadNode(Node);
4968     return;
4969   }
4970 
4971   case ISD::SDIVREM:
4972   case ISD::UDIVREM: {
4973     SDValue N0 = Node->getOperand(0);
4974     SDValue N1 = Node->getOperand(1);
4975 
4976     unsigned ROpc, MOpc;
4977     bool isSigned = Opcode == ISD::SDIVREM;
4978     if (!isSigned) {
4979       switch (NVT.SimpleTy) {
4980       default: llvm_unreachable("Unsupported VT!");
4981       case MVT::i8:  ROpc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
4982       case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break;
4983       case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break;
4984       case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break;
4985       }
4986     } else {
4987       switch (NVT.SimpleTy) {
4988       default: llvm_unreachable("Unsupported VT!");
4989       case MVT::i8:  ROpc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
4990       case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
4991       case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
4992       case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
4993       }
4994     }
4995 
4996     unsigned LoReg, HiReg, ClrReg;
4997     unsigned SExtOpcode;
4998     switch (NVT.SimpleTy) {
4999     default: llvm_unreachable("Unsupported VT!");
5000     case MVT::i8:
5001       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
5002       SExtOpcode = 0; // Not used.
5003       break;
5004     case MVT::i16:
5005       LoReg = X86::AX;  HiReg = X86::DX;
5006       ClrReg = X86::DX;
5007       SExtOpcode = X86::CWD;
5008       break;
5009     case MVT::i32:
5010       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
5011       SExtOpcode = X86::CDQ;
5012       break;
5013     case MVT::i64:
5014       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
5015       SExtOpcode = X86::CQO;
5016       break;
5017     }
5018 
5019     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
5020     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
5021     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
5022 
5023     SDValue InFlag;
5024     if (NVT == MVT::i8) {
5025       // Special case for div8, just use a move with zero extension to AX to
5026       // clear the upper 8 bits (AH).
5027       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
5028       MachineSDNode *Move;
5029       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
5030         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
5031         unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm8
5032                                                     : X86::MOVZX16rm8;
5033         Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops);
5034         Chain = SDValue(Move, 1);
5035         ReplaceUses(N0.getValue(1), Chain);
5036         // Record the mem-refs
5037         CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
5038       } else {
5039         unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr8
5040                                                     : X86::MOVZX16rr8;
5041         Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0);
5042         Chain = CurDAG->getEntryNode();
5043       }
5044       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0),
5045                                     SDValue());
5046       InFlag = Chain.getValue(1);
5047     } else {
5048       InFlag =
5049         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
5050                              LoReg, N0, SDValue()).getValue(1);
5051       if (isSigned && !signBitIsZero) {
5052         // Sign extend the low part into the high part.
5053         InFlag =
5054           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
5055       } else {
5056         // Zero out the high part, effectively zero extending the input.
5057         SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
5058         SDValue ClrNode =
5059             SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, None), 0);
5060         switch (NVT.SimpleTy) {
5061         case MVT::i16:
5062           ClrNode =
5063               SDValue(CurDAG->getMachineNode(
5064                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
5065                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
5066                                                     MVT::i32)),
5067                       0);
5068           break;
5069         case MVT::i32:
5070           break;
5071         case MVT::i64:
5072           ClrNode =
5073               SDValue(CurDAG->getMachineNode(
5074                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
5075                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
5076                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
5077                                                     MVT::i32)),
5078                       0);
5079           break;
5080         default:
5081           llvm_unreachable("Unexpected division source");
5082         }
5083 
5084         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
5085                                       ClrNode, InFlag).getValue(1);
5086       }
5087     }
5088 
5089     if (foldedLoad) {
5090       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
5091                         InFlag };
5092       MachineSDNode *CNode =
5093         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
5094       InFlag = SDValue(CNode, 1);
5095       // Update the chain.
5096       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
5097       // Record the mem-refs
5098       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
5099     } else {
5100       InFlag =
5101         SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InFlag), 0);
5102     }
5103 
5104     // Prevent use of AH in a REX instruction by explicitly copying it to
5105     // an ABCD_L register.
5106     //
5107     // The current assumption of the register allocator is that isel
5108     // won't generate explicit references to the GR8_ABCD_H registers. If
5109     // the allocator and/or the backend get enhanced to be more robust in
5110     // that regard, this can be, and should be, removed.
5111     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
5112       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
5113       unsigned AHExtOpcode =
5114           isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
5115 
5116       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
5117                                              MVT::Glue, AHCopy, InFlag);
5118       SDValue Result(RNode, 0);
5119       InFlag = SDValue(RNode, 1);
5120 
5121       Result =
5122           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
5123 
5124       ReplaceUses(SDValue(Node, 1), Result);
5125       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
5126                  dbgs() << '\n');
5127     }
5128     // Copy the division (low) result, if it is needed.
5129     if (!SDValue(Node, 0).use_empty()) {
5130       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
5131                                                 LoReg, NVT, InFlag);
5132       InFlag = Result.getValue(2);
5133       ReplaceUses(SDValue(Node, 0), Result);
5134       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
5135                  dbgs() << '\n');
5136     }
5137     // Copy the remainder (high) result, if it is needed.
5138     if (!SDValue(Node, 1).use_empty()) {
5139       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
5140                                               HiReg, NVT, InFlag);
5141       InFlag = Result.getValue(2);
5142       ReplaceUses(SDValue(Node, 1), Result);
5143       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
5144                  dbgs() << '\n');
5145     }
5146     CurDAG->RemoveDeadNode(Node);
5147     return;
5148   }
5149 
5150   case X86ISD::FCMP:
5151   case X86ISD::STRICT_FCMP:
5152   case X86ISD::STRICT_FCMPS: {
5153     bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP ||
5154                        Node->getOpcode() == X86ISD::STRICT_FCMPS;
5155     SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0);
5156     SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1);
5157 
5158     // Save the original VT of the compare.
5159     MVT CmpVT = N0.getSimpleValueType();
5160 
5161     // Floating point needs special handling if we don't have FCOMI.
5162     if (Subtarget->hasCMov())
5163       break;
5164 
5165     bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS;
5166 
5167     unsigned Opc;
5168     switch (CmpVT.SimpleTy) {
5169     default: llvm_unreachable("Unexpected type!");
5170     case MVT::f32:
5171       Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32;
5172       break;
5173     case MVT::f64:
5174       Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64;
5175       break;
5176     case MVT::f80:
5177       Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80;
5178       break;
5179     }
5180 
5181     SDValue Cmp;
5182     SDValue Chain =
5183         IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode();
5184     if (IsStrictCmp) {
5185       SDVTList VTs = CurDAG->getVTList(MVT::i16, MVT::Other);
5186       Cmp = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0);
5187       Chain = Cmp.getValue(1);
5188     } else {
5189       Cmp = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i16, N0, N1), 0);
5190     }
5191 
5192     // Move FPSW to AX.
5193     SDValue FPSW = CurDAG->getCopyToReg(Chain, dl, X86::FPSW, Cmp, SDValue());
5194     Chain = FPSW;
5195     SDValue FNSTSW =
5196         SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, FPSW,
5197                                        FPSW.getValue(1)),
5198                 0);
5199 
5200     // Extract upper 8-bits of AX.
5201     SDValue Extract =
5202         CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW);
5203 
5204     // Move AH into flags.
5205     // Some 64-bit targets lack SAHF support, but they do support FCOMI.
5206     assert(Subtarget->hasLAHFSAHF() &&
5207            "Target doesn't support SAHF or FCOMI?");
5208     SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue());
5209     Chain = AH;
5210     SDValue SAHF = SDValue(
5211         CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0);
5212 
5213     if (IsStrictCmp)
5214       ReplaceUses(SDValue(Node, 1), Chain);
5215 
5216     ReplaceUses(SDValue(Node, 0), SAHF);
5217     CurDAG->RemoveDeadNode(Node);
5218     return;
5219   }
5220 
5221   case X86ISD::CMP: {
5222     SDValue N0 = Node->getOperand(0);
5223     SDValue N1 = Node->getOperand(1);
5224 
5225     // Optimizations for TEST compares.
5226     if (!isNullConstant(N1))
5227       break;
5228 
5229     // Save the original VT of the compare.
5230     MVT CmpVT = N0.getSimpleValueType();
5231 
5232     // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
5233     // by a test instruction. The test should be removed later by
5234     // analyzeCompare if we are using only the zero flag.
5235     // TODO: Should we check the users and use the BEXTR flags directly?
5236     if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5237       if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
5238         unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
5239                                              : X86::TEST32rr;
5240         SDValue BEXTR = SDValue(NewNode, 0);
5241         NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
5242         ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
5243         CurDAG->RemoveDeadNode(Node);
5244         return;
5245       }
5246     }
5247 
5248     // We can peek through truncates, but we need to be careful below.
5249     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
5250       N0 = N0.getOperand(0);
5251 
5252     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
5253     // use a smaller encoding.
5254     // Look past the truncate if CMP is the only use of it.
5255     if (N0.getOpcode() == ISD::AND &&
5256         N0.getNode()->hasOneUse() &&
5257         N0.getValueType() != MVT::i8) {
5258       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5259       if (!C) break;
5260       uint64_t Mask = C->getZExtValue();
5261 
5262       // Check if we can replace AND+IMM64 with a shift. This is possible for
5263       // masks/ like 0xFF000000 or 0x00FFFFFF and if we care only about the zero
5264       // flag.
5265       if (CmpVT == MVT::i64 && !isInt<32>(Mask) &&
5266           onlyUsesZeroFlag(SDValue(Node, 0))) {
5267         if (isMask_64(~Mask)) {
5268           unsigned TrailingZeros = countTrailingZeros(Mask);
5269           SDValue Imm = CurDAG->getTargetConstant(TrailingZeros, dl, MVT::i64);
5270           SDValue Shift =
5271             SDValue(CurDAG->getMachineNode(X86::SHR64ri, dl, MVT::i64, MVT::i32,
5272                                            N0.getOperand(0), Imm), 0);
5273           MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
5274                                                        MVT::i32, Shift, Shift);
5275           ReplaceNode(Node, Test);
5276           return;
5277         }
5278         if (isMask_64(Mask)) {
5279           unsigned LeadingZeros = countLeadingZeros(Mask);
5280           SDValue Imm = CurDAG->getTargetConstant(LeadingZeros, dl, MVT::i64);
5281           SDValue Shift =
5282             SDValue(CurDAG->getMachineNode(X86::SHL64ri, dl, MVT::i64, MVT::i32,
5283                                            N0.getOperand(0), Imm), 0);
5284           MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
5285                                                        MVT::i32, Shift, Shift);
5286           ReplaceNode(Node, Test);
5287           return;
5288         }
5289       }
5290 
5291       MVT VT;
5292       int SubRegOp;
5293       unsigned ROpc, MOpc;
5294 
5295       // For each of these checks we need to be careful if the sign flag is
5296       // being used. It is only safe to use the sign flag in two conditions,
5297       // either the sign bit in the shrunken mask is zero or the final test
5298       // size is equal to the original compare size.
5299 
5300       if (isUInt<8>(Mask) &&
5301           (!(Mask & 0x80) || CmpVT == MVT::i8 ||
5302            hasNoSignFlagUses(SDValue(Node, 0)))) {
5303         // For example, convert "testl %eax, $8" to "testb %al, $8"
5304         VT = MVT::i8;
5305         SubRegOp = X86::sub_8bit;
5306         ROpc = X86::TEST8ri;
5307         MOpc = X86::TEST8mi;
5308       } else if (OptForMinSize && isUInt<16>(Mask) &&
5309                  (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
5310                   hasNoSignFlagUses(SDValue(Node, 0)))) {
5311         // For example, "testl %eax, $32776" to "testw %ax, $32776".
5312         // NOTE: We only want to form TESTW instructions if optimizing for
5313         // min size. Otherwise we only save one byte and possibly get a length
5314         // changing prefix penalty in the decoders.
5315         VT = MVT::i16;
5316         SubRegOp = X86::sub_16bit;
5317         ROpc = X86::TEST16ri;
5318         MOpc = X86::TEST16mi;
5319       } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
5320                  ((!(Mask & 0x80000000) &&
5321                    // Without minsize 16-bit Cmps can get here so we need to
5322                    // be sure we calculate the correct sign flag if needed.
5323                    (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
5324                   CmpVT == MVT::i32 ||
5325                   hasNoSignFlagUses(SDValue(Node, 0)))) {
5326         // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
5327         // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
5328         // Otherwize, we find ourselves in a position where we have to do
5329         // promotion. If previous passes did not promote the and, we assume
5330         // they had a good reason not to and do not promote here.
5331         VT = MVT::i32;
5332         SubRegOp = X86::sub_32bit;
5333         ROpc = X86::TEST32ri;
5334         MOpc = X86::TEST32mi;
5335       } else {
5336         // No eligible transformation was found.
5337         break;
5338       }
5339 
5340       SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
5341       SDValue Reg = N0.getOperand(0);
5342 
5343       // Emit a testl or testw.
5344       MachineSDNode *NewNode;
5345       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
5346       if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
5347         if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) {
5348           if (!LoadN->isSimple()) {
5349             unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits();
5350             if (MOpc == X86::TEST8mi && NumVolBits != 8)
5351               break;
5352             else if (MOpc == X86::TEST16mi && NumVolBits != 16)
5353               break;
5354             else if (MOpc == X86::TEST32mi && NumVolBits != 32)
5355               break;
5356           }
5357         }
5358         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
5359                           Reg.getOperand(0) };
5360         NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
5361         // Update the chain.
5362         ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
5363         // Record the mem-refs
5364         CurDAG->setNodeMemRefs(NewNode,
5365                                {cast<LoadSDNode>(Reg)->getMemOperand()});
5366       } else {
5367         // Extract the subregister if necessary.
5368         if (N0.getValueType() != VT)
5369           Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
5370 
5371         NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
5372       }
5373       // Replace CMP with TEST.
5374       ReplaceNode(Node, NewNode);
5375       return;
5376     }
5377     break;
5378   }
5379   case X86ISD::PCMPISTR: {
5380     if (!Subtarget->hasSSE42())
5381       break;
5382 
5383     bool NeedIndex = !SDValue(Node, 0).use_empty();
5384     bool NeedMask = !SDValue(Node, 1).use_empty();
5385     // We can't fold a load if we are going to make two instructions.
5386     bool MayFoldLoad = !NeedIndex || !NeedMask;
5387 
5388     MachineSDNode *CNode;
5389     if (NeedMask) {
5390       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
5391       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
5392       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
5393       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
5394     }
5395     if (NeedIndex || !NeedMask) {
5396       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
5397       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
5398       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
5399       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
5400     }
5401 
5402     // Connect the flag usage to the last instruction created.
5403     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
5404     CurDAG->RemoveDeadNode(Node);
5405     return;
5406   }
5407   case X86ISD::PCMPESTR: {
5408     if (!Subtarget->hasSSE42())
5409       break;
5410 
5411     // Copy the two implicit register inputs.
5412     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
5413                                           Node->getOperand(1),
5414                                           SDValue()).getValue(1);
5415     InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
5416                                   Node->getOperand(3), InFlag).getValue(1);
5417 
5418     bool NeedIndex = !SDValue(Node, 0).use_empty();
5419     bool NeedMask = !SDValue(Node, 1).use_empty();
5420     // We can't fold a load if we are going to make two instructions.
5421     bool MayFoldLoad = !NeedIndex || !NeedMask;
5422 
5423     MachineSDNode *CNode;
5424     if (NeedMask) {
5425       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
5426       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
5427       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
5428                            InFlag);
5429       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
5430     }
5431     if (NeedIndex || !NeedMask) {
5432       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
5433       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
5434       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
5435       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
5436     }
5437     // Connect the flag usage to the last instruction created.
5438     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
5439     CurDAG->RemoveDeadNode(Node);
5440     return;
5441   }
5442 
5443   case ISD::SETCC: {
5444     if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue()))
5445       return;
5446 
5447     break;
5448   }
5449 
5450   case ISD::STORE:
5451     if (foldLoadStoreIntoMemOperand(Node))
5452       return;
5453     break;
5454 
5455   case X86ISD::SETCC_CARRY: {
5456     // We have to do this manually because tblgen will put the eflags copy in
5457     // the wrong place if we use an extract_subreg in the pattern.
5458     MVT VT = Node->getSimpleValueType(0);
5459 
5460     // Copy flags to the EFLAGS register and glue it to next node.
5461     SDValue EFLAGS =
5462         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
5463                              Node->getOperand(1), SDValue());
5464 
5465     // Create a 64-bit instruction if the result is 64-bits otherwise use the
5466     // 32-bit version.
5467     unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r;
5468     MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
5469     SDValue Result = SDValue(
5470         CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)), 0);
5471 
5472     // For less than 32-bits we need to extract from the 32-bit node.
5473     if (VT == MVT::i8 || VT == MVT::i16) {
5474       int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
5475       Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
5476     }
5477 
5478     ReplaceUses(SDValue(Node, 0), Result);
5479     CurDAG->RemoveDeadNode(Node);
5480     return;
5481   }
5482   case X86ISD::SBB: {
5483     if (isNullConstant(Node->getOperand(0)) &&
5484         isNullConstant(Node->getOperand(1))) {
5485       MVT VT = Node->getSimpleValueType(0);
5486 
5487       // Create zero.
5488       SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
5489       SDValue Zero =
5490           SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, None), 0);
5491       if (VT == MVT::i64) {
5492         Zero = SDValue(
5493             CurDAG->getMachineNode(
5494                 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
5495                 CurDAG->getTargetConstant(0, dl, MVT::i64), Zero,
5496                 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
5497             0);
5498       }
5499 
5500       // Copy flags to the EFLAGS register and glue it to next node.
5501       SDValue EFLAGS =
5502           CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
5503                                Node->getOperand(2), SDValue());
5504 
5505       // Create a 64-bit instruction if the result is 64-bits otherwise use the
5506       // 32-bit version.
5507       unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr;
5508       MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
5509       VTs = CurDAG->getVTList(SBBVT, MVT::i32);
5510       SDValue Result =
5511           SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {Zero, Zero, EFLAGS,
5512                                          EFLAGS.getValue(1)}),
5513                   0);
5514 
5515       // Replace the flag use.
5516       ReplaceUses(SDValue(Node, 1), Result.getValue(1));
5517 
5518       // Replace the result use.
5519       if (!SDValue(Node, 0).use_empty()) {
5520         // For less than 32-bits we need to extract from the 32-bit node.
5521         if (VT == MVT::i8 || VT == MVT::i16) {
5522           int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
5523           Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
5524         }
5525         ReplaceUses(SDValue(Node, 0), Result);
5526       }
5527 
5528       CurDAG->RemoveDeadNode(Node);
5529       return;
5530     }
5531     break;
5532   }
5533   case X86ISD::MGATHER: {
5534     auto *Mgt = cast<X86MaskedGatherSDNode>(Node);
5535     SDValue IndexOp = Mgt->getIndex();
5536     SDValue Mask = Mgt->getMask();
5537     MVT IndexVT = IndexOp.getSimpleValueType();
5538     MVT ValueVT = Node->getSimpleValueType(0);
5539     MVT MaskVT = Mask.getSimpleValueType();
5540 
5541     // This is just to prevent crashes if the nodes are malformed somehow. We're
5542     // otherwise only doing loose type checking in here based on type what
5543     // a type constraint would say just like table based isel.
5544     if (!ValueVT.isVector() || !MaskVT.isVector())
5545       break;
5546 
5547     unsigned NumElts = ValueVT.getVectorNumElements();
5548     MVT ValueSVT = ValueVT.getVectorElementType();
5549 
5550     bool IsFP = ValueSVT.isFloatingPoint();
5551     unsigned EltSize = ValueSVT.getSizeInBits();
5552 
5553     unsigned Opc = 0;
5554     bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1;
5555     if (AVX512Gather) {
5556       if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
5557         Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm;
5558       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
5559         Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm;
5560       else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
5561         Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm;
5562       else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
5563         Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm;
5564       else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
5565         Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm;
5566       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
5567         Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm;
5568       else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
5569         Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm;
5570       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
5571         Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm;
5572       else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
5573         Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm;
5574       else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
5575         Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm;
5576       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
5577         Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm;
5578       else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
5579         Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm;
5580     } else {
5581       assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() &&
5582              "Unexpected mask VT!");
5583       if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
5584         Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm;
5585       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
5586         Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm;
5587       else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
5588         Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm;
5589       else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
5590         Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm;
5591       else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
5592         Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm;
5593       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
5594         Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm;
5595       else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
5596         Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm;
5597       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
5598         Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm;
5599     }
5600 
5601     if (!Opc)
5602       break;
5603 
5604     SDValue Base, Scale, Index, Disp, Segment;
5605     if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(),
5606                           Base, Scale, Index, Disp, Segment))
5607       break;
5608 
5609     SDValue PassThru = Mgt->getPassThru();
5610     SDValue Chain = Mgt->getChain();
5611     // Gather instructions have a mask output not in the ISD node.
5612     SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other);
5613 
5614     MachineSDNode *NewNode;
5615     if (AVX512Gather) {
5616       SDValue Ops[] = {PassThru, Mask, Base,    Scale,
5617                        Index,    Disp, Segment, Chain};
5618       NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
5619     } else {
5620       SDValue Ops[] = {PassThru, Base,    Scale, Index,
5621                        Disp,     Segment, Mask,  Chain};
5622       NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
5623     }
5624     CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()});
5625     ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
5626     ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2));
5627     CurDAG->RemoveDeadNode(Node);
5628     return;
5629   }
5630   case X86ISD::MSCATTER: {
5631     auto *Sc = cast<X86MaskedScatterSDNode>(Node);
5632     SDValue Value = Sc->getValue();
5633     SDValue IndexOp = Sc->getIndex();
5634     MVT IndexVT = IndexOp.getSimpleValueType();
5635     MVT ValueVT = Value.getSimpleValueType();
5636 
5637     // This is just to prevent crashes if the nodes are malformed somehow. We're
5638     // otherwise only doing loose type checking in here based on type what
5639     // a type constraint would say just like table based isel.
5640     if (!ValueVT.isVector())
5641       break;
5642 
5643     unsigned NumElts = ValueVT.getVectorNumElements();
5644     MVT ValueSVT = ValueVT.getVectorElementType();
5645 
5646     bool IsFP = ValueSVT.isFloatingPoint();
5647     unsigned EltSize = ValueSVT.getSizeInBits();
5648 
5649     unsigned Opc;
5650     if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
5651       Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr;
5652     else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
5653       Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr;
5654     else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
5655       Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr;
5656     else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
5657       Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr;
5658     else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
5659       Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr;
5660     else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
5661       Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr;
5662     else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
5663       Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr;
5664     else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
5665       Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr;
5666     else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
5667       Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr;
5668     else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
5669       Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr;
5670     else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
5671       Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr;
5672     else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
5673       Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr;
5674     else
5675       break;
5676 
5677     SDValue Base, Scale, Index, Disp, Segment;
5678     if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(),
5679                           Base, Scale, Index, Disp, Segment))
5680       break;
5681 
5682     SDValue Mask = Sc->getMask();
5683     SDValue Chain = Sc->getChain();
5684     // Scatter instructions have a mask output not in the ISD node.
5685     SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other);
5686     SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain};
5687 
5688     MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
5689     CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()});
5690     ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1));
5691     CurDAG->RemoveDeadNode(Node);
5692     return;
5693   }
5694   case ISD::PREALLOCATED_SETUP: {
5695     auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5696     auto CallId = MFI->getPreallocatedIdForCallSite(
5697         cast<SrcValueSDNode>(Node->getOperand(1))->getValue());
5698     SDValue Chain = Node->getOperand(0);
5699     SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);
5700     MachineSDNode *New = CurDAG->getMachineNode(
5701         TargetOpcode::PREALLOCATED_SETUP, dl, MVT::Other, CallIdValue, Chain);
5702     ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Chain
5703     CurDAG->RemoveDeadNode(Node);
5704     return;
5705   }
5706   case ISD::PREALLOCATED_ARG: {
5707     auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5708     auto CallId = MFI->getPreallocatedIdForCallSite(
5709         cast<SrcValueSDNode>(Node->getOperand(1))->getValue());
5710     SDValue Chain = Node->getOperand(0);
5711     SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);
5712     SDValue ArgIndex = Node->getOperand(2);
5713     SDValue Ops[3];
5714     Ops[0] = CallIdValue;
5715     Ops[1] = ArgIndex;
5716     Ops[2] = Chain;
5717     MachineSDNode *New = CurDAG->getMachineNode(
5718         TargetOpcode::PREALLOCATED_ARG, dl,
5719         CurDAG->getVTList(TLI->getPointerTy(CurDAG->getDataLayout()),
5720                           MVT::Other),
5721         Ops);
5722     ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Arg pointer
5723     ReplaceUses(SDValue(Node, 1), SDValue(New, 1)); // Chain
5724     CurDAG->RemoveDeadNode(Node);
5725     return;
5726   }
5727   }
5728 
5729   SelectCode(Node);
5730 }
5731 
5732 bool X86DAGToDAGISel::
5733 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
5734                              std::vector<SDValue> &OutOps) {
5735   SDValue Op0, Op1, Op2, Op3, Op4;
5736   switch (ConstraintID) {
5737   default:
5738     llvm_unreachable("Unexpected asm memory constraint");
5739   case InlineAsm::Constraint_o: // offsetable        ??
5740   case InlineAsm::Constraint_v: // not offsetable    ??
5741   case InlineAsm::Constraint_m: // memory
5742   case InlineAsm::Constraint_X:
5743     if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
5744       return true;
5745     break;
5746   }
5747 
5748   OutOps.push_back(Op0);
5749   OutOps.push_back(Op1);
5750   OutOps.push_back(Op2);
5751   OutOps.push_back(Op3);
5752   OutOps.push_back(Op4);
5753   return false;
5754 }
5755 
5756 /// This pass converts a legalized DAG into a X86-specific DAG,
5757 /// ready for instruction scheduling.
5758 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
5759                                      CodeGenOpt::Level OptLevel) {
5760   return new X86DAGToDAGISel(TM, OptLevel);
5761 }
5762