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