xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines a DAG pattern matching instruction selector for X86,
100b57cec5SDimitry Andric // converting from a legalized dag to a X86 dag.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
14*0fca6ea1SDimitry Andric #include "X86ISelDAGToDAG.h"
150b57cec5SDimitry Andric #include "X86.h"
160b57cec5SDimitry Andric #include "X86MachineFunctionInfo.h"
170b57cec5SDimitry Andric #include "X86RegisterInfo.h"
180b57cec5SDimitry Andric #include "X86Subtarget.h"
190b57cec5SDimitry Andric #include "X86TargetMachine.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
21e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAGISel.h"
230b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
240b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
250b57cec5SDimitry Andric #include "llvm/IR/Function.h"
260b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
270b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
28480093f4SDimitry Andric #include "llvm/IR/IntrinsicsX86.h"
29*0fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
300b57cec5SDimitry Andric #include "llvm/IR/Type.h"
310b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
320b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
330b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
340b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
35fe6060f1SDimitry Andric #include <cstdint>
36fe6060f1SDimitry Andric 
370b57cec5SDimitry Andric using namespace llvm;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric #define DEBUG_TYPE "x86-isel"
40bdd1243dSDimitry Andric #define PASS_NAME "X86 DAG->DAG Instruction Selection"
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
450b57cec5SDimitry Andric     cl::desc("Enable setting constant bits to reduce size of mask immediates"),
460b57cec5SDimitry Andric     cl::Hidden);
470b57cec5SDimitry Andric 
485ffd83dbSDimitry Andric static cl::opt<bool> EnablePromoteAnyextLoad(
495ffd83dbSDimitry Andric     "x86-promote-anyext-load", cl::init(true),
505ffd83dbSDimitry Andric     cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden);
515ffd83dbSDimitry Andric 
52e8d8bef9SDimitry Andric extern cl::opt<bool> IndirectBranchTracking;
53e8d8bef9SDimitry Andric 
540b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
550b57cec5SDimitry Andric //                      Pattern Matcher Implementation
560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric namespace {
590b57cec5SDimitry Andric   /// This corresponds to X86AddressMode, but uses SDValue's instead of register
600b57cec5SDimitry Andric   /// numbers for the leaves of the matched tree.
610b57cec5SDimitry Andric   struct X86ISelAddressMode {
620b57cec5SDimitry Andric     enum {
630b57cec5SDimitry Andric       RegBase,
640b57cec5SDimitry Andric       FrameIndexBase
6581ad6265SDimitry Andric     } BaseType = RegBase;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric     // This is really a union, discriminated by BaseType!
680b57cec5SDimitry Andric     SDValue Base_Reg;
6981ad6265SDimitry Andric     int Base_FrameIndex = 0;
700b57cec5SDimitry Andric 
7181ad6265SDimitry Andric     unsigned Scale = 1;
720b57cec5SDimitry Andric     SDValue IndexReg;
7381ad6265SDimitry Andric     int32_t Disp = 0;
740b57cec5SDimitry Andric     SDValue Segment;
7581ad6265SDimitry Andric     const GlobalValue *GV = nullptr;
7681ad6265SDimitry Andric     const Constant *CP = nullptr;
7781ad6265SDimitry Andric     const BlockAddress *BlockAddr = nullptr;
7881ad6265SDimitry Andric     const char *ES = nullptr;
7981ad6265SDimitry Andric     MCSymbol *MCSym = nullptr;
8081ad6265SDimitry Andric     int JT = -1;
815ffd83dbSDimitry Andric     Align Alignment;            // CP alignment.
8281ad6265SDimitry Andric     unsigned char SymbolFlags = X86II::MO_NO_FLAG;  // X86II::MO_*
830b57cec5SDimitry Andric     bool NegateIndex = false;
840b57cec5SDimitry Andric 
8581ad6265SDimitry Andric     X86ISelAddressMode() = default;
860b57cec5SDimitry Andric 
hasSymbolicDisplacement__anon5504e2c90111::X86ISelAddressMode870b57cec5SDimitry Andric     bool hasSymbolicDisplacement() const {
880b57cec5SDimitry Andric       return GV != nullptr || CP != nullptr || ES != nullptr ||
890b57cec5SDimitry Andric              MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
900b57cec5SDimitry Andric     }
910b57cec5SDimitry Andric 
hasBaseOrIndexReg__anon5504e2c90111::X86ISelAddressMode920b57cec5SDimitry Andric     bool hasBaseOrIndexReg() const {
930b57cec5SDimitry Andric       return BaseType == FrameIndexBase ||
940b57cec5SDimitry Andric              IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
950b57cec5SDimitry Andric     }
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric     /// Return true if this addressing mode is already RIP-relative.
isRIPRelative__anon5504e2c90111::X86ISelAddressMode980b57cec5SDimitry Andric     bool isRIPRelative() const {
990b57cec5SDimitry Andric       if (BaseType != RegBase) return false;
1000b57cec5SDimitry Andric       if (RegisterSDNode *RegNode =
1010b57cec5SDimitry Andric             dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
1020b57cec5SDimitry Andric         return RegNode->getReg() == X86::RIP;
1030b57cec5SDimitry Andric       return false;
1040b57cec5SDimitry Andric     }
1050b57cec5SDimitry Andric 
setBaseReg__anon5504e2c90111::X86ISelAddressMode1060b57cec5SDimitry Andric     void setBaseReg(SDValue Reg) {
1070b57cec5SDimitry Andric       BaseType = RegBase;
1080b57cec5SDimitry Andric       Base_Reg = Reg;
1090b57cec5SDimitry Andric     }
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump__anon5504e2c90111::X86ISelAddressMode1120b57cec5SDimitry Andric     void dump(SelectionDAG *DAG = nullptr) {
1130b57cec5SDimitry Andric       dbgs() << "X86ISelAddressMode " << this << '\n';
1140b57cec5SDimitry Andric       dbgs() << "Base_Reg ";
1150b57cec5SDimitry Andric       if (Base_Reg.getNode())
1160b57cec5SDimitry Andric         Base_Reg.getNode()->dump(DAG);
1170b57cec5SDimitry Andric       else
1180b57cec5SDimitry Andric         dbgs() << "nul\n";
1190b57cec5SDimitry Andric       if (BaseType == FrameIndexBase)
1200b57cec5SDimitry Andric         dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
1210b57cec5SDimitry Andric       dbgs() << " Scale " << Scale << '\n'
1220b57cec5SDimitry Andric              << "IndexReg ";
1230b57cec5SDimitry Andric       if (NegateIndex)
1240b57cec5SDimitry Andric         dbgs() << "negate ";
1250b57cec5SDimitry Andric       if (IndexReg.getNode())
1260b57cec5SDimitry Andric         IndexReg.getNode()->dump(DAG);
1270b57cec5SDimitry Andric       else
1280b57cec5SDimitry Andric         dbgs() << "nul\n";
1290b57cec5SDimitry Andric       dbgs() << " Disp " << Disp << '\n'
1300b57cec5SDimitry Andric              << "GV ";
1310b57cec5SDimitry Andric       if (GV)
1320b57cec5SDimitry Andric         GV->dump();
1330b57cec5SDimitry Andric       else
1340b57cec5SDimitry Andric         dbgs() << "nul";
1350b57cec5SDimitry Andric       dbgs() << " CP ";
1360b57cec5SDimitry Andric       if (CP)
1370b57cec5SDimitry Andric         CP->dump();
1380b57cec5SDimitry Andric       else
1390b57cec5SDimitry Andric         dbgs() << "nul";
1400b57cec5SDimitry Andric       dbgs() << '\n'
1410b57cec5SDimitry Andric              << "ES ";
1420b57cec5SDimitry Andric       if (ES)
1430b57cec5SDimitry Andric         dbgs() << ES;
1440b57cec5SDimitry Andric       else
1450b57cec5SDimitry Andric         dbgs() << "nul";
1460b57cec5SDimitry Andric       dbgs() << " MCSym ";
1470b57cec5SDimitry Andric       if (MCSym)
1480b57cec5SDimitry Andric         dbgs() << MCSym;
1490b57cec5SDimitry Andric       else
1500b57cec5SDimitry Andric         dbgs() << "nul";
1515ffd83dbSDimitry Andric       dbgs() << " JT" << JT << " Align" << Alignment.value() << '\n';
1520b57cec5SDimitry Andric     }
1530b57cec5SDimitry Andric #endif
1540b57cec5SDimitry Andric   };
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric namespace {
1580b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
1590b57cec5SDimitry Andric   /// ISel - X86-specific code to select X86 machine instructions for
1600b57cec5SDimitry Andric   /// SelectionDAG operations.
1610b57cec5SDimitry Andric   ///
1620b57cec5SDimitry Andric   class X86DAGToDAGISel final : public SelectionDAGISel {
1630b57cec5SDimitry Andric     /// Keep a pointer to the X86Subtarget around so that we can
1640b57cec5SDimitry Andric     /// make the right decision when generating code for different targets.
1650b57cec5SDimitry Andric     const X86Subtarget *Subtarget;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric     /// If true, selector should try to optimize for minimum code size.
1680b57cec5SDimitry Andric     bool OptForMinSize;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric     /// Disable direct TLS access through segment registers.
1710b57cec5SDimitry Andric     bool IndirectTlsSegRefs;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   public:
174bdd1243dSDimitry Andric     X86DAGToDAGISel() = delete;
175bdd1243dSDimitry Andric 
X86DAGToDAGISel(X86TargetMachine & tm,CodeGenOptLevel OptLevel)1765f757f3fSDimitry Andric     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOptLevel OptLevel)
177*0fca6ea1SDimitry Andric         : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr),
178bdd1243dSDimitry Andric           OptForMinSize(false), IndirectTlsSegRefs(false) {}
1790b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)1800b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override {
1810b57cec5SDimitry Andric       // Reset the subtarget each time through.
1820b57cec5SDimitry Andric       Subtarget = &MF.getSubtarget<X86Subtarget>();
1830b57cec5SDimitry Andric       IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
1840b57cec5SDimitry Andric                              "indirect-tls-seg-refs");
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric       // OptFor[Min]Size are used in pattern predicates that isel is matching.
1870b57cec5SDimitry Andric       OptForMinSize = MF.getFunction().hasMinSize();
1885ffd83dbSDimitry Andric       assert((!OptForMinSize || MF.getFunction().hasOptSize()) &&
1890b57cec5SDimitry Andric              "OptForMinSize implies OptForSize");
190*0fca6ea1SDimitry Andric       return SelectionDAGISel::runOnMachineFunction(MF);
1910b57cec5SDimitry Andric     }
1920b57cec5SDimitry Andric 
1935ffd83dbSDimitry Andric     void emitFunctionEntryCode() override;
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric     void PreprocessISelDAG() override;
1980b57cec5SDimitry Andric     void PostprocessISelDAG() override;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric // Include the pieces autogenerated from the target description.
2010b57cec5SDimitry Andric #include "X86GenDAGISel.inc"
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric   private:
2040b57cec5SDimitry Andric     void Select(SDNode *N) override;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric     bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
207e8d8bef9SDimitry Andric     bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,
208e8d8bef9SDimitry Andric                             bool AllowSegmentRegForX32 = false);
2090b57cec5SDimitry Andric     bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
2100b57cec5SDimitry Andric     bool matchAddress(SDValue N, X86ISelAddressMode &AM);
2110b57cec5SDimitry Andric     bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
2120b57cec5SDimitry Andric     bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);
2135f757f3fSDimitry Andric     SDValue matchIndexRecursively(SDValue N, X86ISelAddressMode &AM,
2145f757f3fSDimitry Andric                                   unsigned Depth);
2150b57cec5SDimitry Andric     bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
2160b57cec5SDimitry Andric                                  unsigned Depth);
217349cc55cSDimitry Andric     bool matchVectorAddressRecursively(SDValue N, X86ISelAddressMode &AM,
218349cc55cSDimitry Andric                                        unsigned Depth);
2190b57cec5SDimitry Andric     bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
2200b57cec5SDimitry Andric     bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
2210b57cec5SDimitry Andric                     SDValue &Scale, SDValue &Index, SDValue &Disp,
2220b57cec5SDimitry Andric                     SDValue &Segment);
2235ffd83dbSDimitry Andric     bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp,
2245ffd83dbSDimitry Andric                           SDValue ScaleOp, SDValue &Base, SDValue &Scale,
2255ffd83dbSDimitry Andric                           SDValue &Index, SDValue &Disp, SDValue &Segment);
2260b57cec5SDimitry Andric     bool selectMOV64Imm32(SDValue N, SDValue &Imm);
2270b57cec5SDimitry Andric     bool selectLEAAddr(SDValue N, SDValue &Base,
2280b57cec5SDimitry Andric                        SDValue &Scale, SDValue &Index, SDValue &Disp,
2290b57cec5SDimitry Andric                        SDValue &Segment);
2300b57cec5SDimitry Andric     bool selectLEA64_32Addr(SDValue N, SDValue &Base,
2310b57cec5SDimitry Andric                             SDValue &Scale, SDValue &Index, SDValue &Disp,
2320b57cec5SDimitry Andric                             SDValue &Segment);
2330b57cec5SDimitry Andric     bool selectTLSADDRAddr(SDValue N, SDValue &Base,
2340b57cec5SDimitry Andric                            SDValue &Scale, SDValue &Index, SDValue &Disp,
2350b57cec5SDimitry Andric                            SDValue &Segment);
2360b57cec5SDimitry Andric     bool selectRelocImm(SDValue N, SDValue &Op);
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric     bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
2390b57cec5SDimitry Andric                      SDValue &Base, SDValue &Scale,
2400b57cec5SDimitry Andric                      SDValue &Index, SDValue &Disp,
2410b57cec5SDimitry Andric                      SDValue &Segment);
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric     // Convenience method where P is also root.
tryFoldLoad(SDNode * P,SDValue N,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)2440b57cec5SDimitry Andric     bool tryFoldLoad(SDNode *P, SDValue N,
2450b57cec5SDimitry Andric                      SDValue &Base, SDValue &Scale,
2460b57cec5SDimitry Andric                      SDValue &Index, SDValue &Disp,
2470b57cec5SDimitry Andric                      SDValue &Segment) {
2480b57cec5SDimitry Andric       return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
2490b57cec5SDimitry Andric     }
2500b57cec5SDimitry Andric 
2518bcb0991SDimitry Andric     bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
2528bcb0991SDimitry Andric                           SDValue &Base, SDValue &Scale,
2538bcb0991SDimitry Andric                           SDValue &Index, SDValue &Disp,
2548bcb0991SDimitry Andric                           SDValue &Segment);
2558bcb0991SDimitry Andric 
2565ffd83dbSDimitry Andric     bool isProfitableToFormMaskedOp(SDNode *N) const;
2575ffd83dbSDimitry Andric 
2580b57cec5SDimitry Andric     /// Implement addressing mode selection for inline asm expressions.
2590b57cec5SDimitry Andric     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
2605f757f3fSDimitry Andric                                       InlineAsm::ConstraintCode ConstraintID,
2610b57cec5SDimitry Andric                                       std::vector<SDValue> &OutOps) override;
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     void emitSpecialCodeForMain();
2640b57cec5SDimitry Andric 
getAddressOperands(X86ISelAddressMode & AM,const SDLoc & DL,MVT VT,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)2650b57cec5SDimitry Andric     inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
2660b57cec5SDimitry Andric                                    MVT VT, SDValue &Base, SDValue &Scale,
2670b57cec5SDimitry Andric                                    SDValue &Index, SDValue &Disp,
2680b57cec5SDimitry Andric                                    SDValue &Segment) {
2690b57cec5SDimitry Andric       if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2700b57cec5SDimitry Andric         Base = CurDAG->getTargetFrameIndex(
2710b57cec5SDimitry Andric             AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));
2720b57cec5SDimitry Andric       else if (AM.Base_Reg.getNode())
2730b57cec5SDimitry Andric         Base = AM.Base_Reg;
2740b57cec5SDimitry Andric       else
2750b57cec5SDimitry Andric         Base = CurDAG->getRegister(0, VT);
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric       Scale = getI8Imm(AM.Scale, DL);
2780b57cec5SDimitry Andric 
279*0fca6ea1SDimitry Andric #define GET_ND_IF_ENABLED(OPC) (Subtarget->hasNDD() ? OPC##_ND : OPC)
2800b57cec5SDimitry Andric       // Negate the index if needed.
2810b57cec5SDimitry Andric       if (AM.NegateIndex) {
282*0fca6ea1SDimitry Andric         unsigned NegOpc = VT == MVT::i64 ? GET_ND_IF_ENABLED(X86::NEG64r)
283*0fca6ea1SDimitry Andric                                          : GET_ND_IF_ENABLED(X86::NEG32r);
2840b57cec5SDimitry Andric         SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,
2850b57cec5SDimitry Andric                                                      AM.IndexReg), 0);
2860b57cec5SDimitry Andric         AM.IndexReg = Neg;
2870b57cec5SDimitry Andric       }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric       if (AM.IndexReg.getNode())
2900b57cec5SDimitry Andric         Index = AM.IndexReg;
2910b57cec5SDimitry Andric       else
2920b57cec5SDimitry Andric         Index = CurDAG->getRegister(0, VT);
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric       // These are 32-bit even in 64-bit mode since RIP-relative offset
2950b57cec5SDimitry Andric       // is 32-bit.
2960b57cec5SDimitry Andric       if (AM.GV)
2970b57cec5SDimitry Andric         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
2980b57cec5SDimitry Andric                                               MVT::i32, AM.Disp,
2990b57cec5SDimitry Andric                                               AM.SymbolFlags);
3000b57cec5SDimitry Andric       else if (AM.CP)
3015ffd83dbSDimitry Andric         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Alignment,
3025ffd83dbSDimitry Andric                                              AM.Disp, AM.SymbolFlags);
3030b57cec5SDimitry Andric       else if (AM.ES) {
3040b57cec5SDimitry Andric         assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
3050b57cec5SDimitry Andric         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
3060b57cec5SDimitry Andric       } else if (AM.MCSym) {
3070b57cec5SDimitry Andric         assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
3080b57cec5SDimitry Andric         assert(AM.SymbolFlags == 0 && "oo");
3090b57cec5SDimitry Andric         Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
3100b57cec5SDimitry Andric       } else if (AM.JT != -1) {
3110b57cec5SDimitry Andric         assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
3120b57cec5SDimitry Andric         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
3130b57cec5SDimitry Andric       } else if (AM.BlockAddr)
3140b57cec5SDimitry Andric         Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
3150b57cec5SDimitry Andric                                              AM.SymbolFlags);
3160b57cec5SDimitry Andric       else
3170b57cec5SDimitry Andric         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric       if (AM.Segment.getNode())
3200b57cec5SDimitry Andric         Segment = AM.Segment;
3210b57cec5SDimitry Andric       else
3220b57cec5SDimitry Andric         Segment = CurDAG->getRegister(0, MVT::i16);
3230b57cec5SDimitry Andric     }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric     // Utility function to determine whether we should avoid selecting
3260b57cec5SDimitry Andric     // immediate forms of instructions for better code size or not.
3270b57cec5SDimitry Andric     // At a high level, we'd like to avoid such instructions when
3280b57cec5SDimitry Andric     // we have similar constants used within the same basic block
3290b57cec5SDimitry Andric     // that can be kept in a register.
3300b57cec5SDimitry Andric     //
shouldAvoidImmediateInstFormsForSize(SDNode * N) const3310b57cec5SDimitry Andric     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
3320b57cec5SDimitry Andric       uint32_t UseCount = 0;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric       // Do not want to hoist if we're not optimizing for size.
3350b57cec5SDimitry Andric       // TODO: We'd like to remove this restriction.
3360b57cec5SDimitry Andric       // See the comment in X86InstrInfo.td for more info.
337480093f4SDimitry Andric       if (!CurDAG->shouldOptForSize())
3380b57cec5SDimitry Andric         return false;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric       // Walk all the users of the immediate.
341349cc55cSDimitry Andric       for (const SDNode *User : N->uses()) {
342349cc55cSDimitry Andric         if (UseCount >= 2)
343349cc55cSDimitry Andric           break;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric         // This user is already selected. Count it as a legitimate use and
3460b57cec5SDimitry Andric         // move on.
3470b57cec5SDimitry Andric         if (User->isMachineOpcode()) {
3480b57cec5SDimitry Andric           UseCount++;
3490b57cec5SDimitry Andric           continue;
3500b57cec5SDimitry Andric         }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric         // We want to count stores of immediates as real uses.
3530b57cec5SDimitry Andric         if (User->getOpcode() == ISD::STORE &&
3540b57cec5SDimitry Andric             User->getOperand(1).getNode() == N) {
3550b57cec5SDimitry Andric           UseCount++;
3560b57cec5SDimitry Andric           continue;
3570b57cec5SDimitry Andric         }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric         // We don't currently match users that have > 2 operands (except
3600b57cec5SDimitry Andric         // for stores, which are handled above)
3610b57cec5SDimitry Andric         // Those instruction won't match in ISEL, for now, and would
3620b57cec5SDimitry Andric         // be counted incorrectly.
3630b57cec5SDimitry Andric         // This may change in the future as we add additional instruction
3640b57cec5SDimitry Andric         // types.
3650b57cec5SDimitry Andric         if (User->getNumOperands() != 2)
3660b57cec5SDimitry Andric           continue;
3670b57cec5SDimitry Andric 
3685ffd83dbSDimitry Andric         // If this is a sign-extended 8-bit integer immediate used in an ALU
3695ffd83dbSDimitry Andric         // instruction, there is probably an opcode encoding to save space.
3705ffd83dbSDimitry Andric         auto *C = dyn_cast<ConstantSDNode>(N);
3715ffd83dbSDimitry Andric         if (C && isInt<8>(C->getSExtValue()))
3728bcb0991SDimitry Andric           continue;
3738bcb0991SDimitry Andric 
3740b57cec5SDimitry Andric         // Immediates that are used for offsets as part of stack
3750b57cec5SDimitry Andric         // manipulation should be left alone. These are typically
3760b57cec5SDimitry Andric         // used to indicate SP offsets for argument passing and
3770b57cec5SDimitry Andric         // will get pulled into stores/pushes (implicitly).
3780b57cec5SDimitry Andric         if (User->getOpcode() == X86ISD::ADD ||
3790b57cec5SDimitry Andric             User->getOpcode() == ISD::ADD    ||
3800b57cec5SDimitry Andric             User->getOpcode() == X86ISD::SUB ||
3810b57cec5SDimitry Andric             User->getOpcode() == ISD::SUB) {
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric           // Find the other operand of the add/sub.
3840b57cec5SDimitry Andric           SDValue OtherOp = User->getOperand(0);
3850b57cec5SDimitry Andric           if (OtherOp.getNode() == N)
3860b57cec5SDimitry Andric             OtherOp = User->getOperand(1);
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric           // Don't count if the other operand is SP.
3890b57cec5SDimitry Andric           RegisterSDNode *RegNode;
3900b57cec5SDimitry Andric           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
3910b57cec5SDimitry Andric               (RegNode = dyn_cast_or_null<RegisterSDNode>(
3920b57cec5SDimitry Andric                  OtherOp->getOperand(1).getNode())))
3930b57cec5SDimitry Andric             if ((RegNode->getReg() == X86::ESP) ||
3940b57cec5SDimitry Andric                 (RegNode->getReg() == X86::RSP))
3950b57cec5SDimitry Andric               continue;
3960b57cec5SDimitry Andric         }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric         // ... otherwise, count this and move on.
3990b57cec5SDimitry Andric         UseCount++;
4000b57cec5SDimitry Andric       }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric       // If we have more than 1 use, then recommend for hoisting.
4030b57cec5SDimitry Andric       return (UseCount > 1);
4040b57cec5SDimitry Andric     }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     /// Return a target constant with the specified value of type i8.
getI8Imm(unsigned Imm,const SDLoc & DL)4070b57cec5SDimitry Andric     inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
4080b57cec5SDimitry Andric       return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
4090b57cec5SDimitry Andric     }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric     /// Return a target constant with the specified value, of type i32.
getI32Imm(unsigned Imm,const SDLoc & DL)4120b57cec5SDimitry Andric     inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
4130b57cec5SDimitry Andric       return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
4140b57cec5SDimitry Andric     }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric     /// Return a target constant with the specified value, of type i64.
getI64Imm(uint64_t Imm,const SDLoc & DL)4170b57cec5SDimitry Andric     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
4180b57cec5SDimitry Andric       return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
4190b57cec5SDimitry Andric     }
4200b57cec5SDimitry Andric 
getExtractVEXTRACTImmediate(SDNode * N,unsigned VecWidth,const SDLoc & DL)4210b57cec5SDimitry Andric     SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
4220b57cec5SDimitry Andric                                         const SDLoc &DL) {
4230b57cec5SDimitry Andric       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
4240b57cec5SDimitry Andric       uint64_t Index = N->getConstantOperandVal(1);
4250b57cec5SDimitry Andric       MVT VecVT = N->getOperand(0).getSimpleValueType();
4260b57cec5SDimitry Andric       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
4270b57cec5SDimitry Andric     }
4280b57cec5SDimitry Andric 
getInsertVINSERTImmediate(SDNode * N,unsigned VecWidth,const SDLoc & DL)4290b57cec5SDimitry Andric     SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
4300b57cec5SDimitry Andric                                       const SDLoc &DL) {
4310b57cec5SDimitry Andric       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
4320b57cec5SDimitry Andric       uint64_t Index = N->getConstantOperandVal(2);
4330b57cec5SDimitry Andric       MVT VecVT = N->getSimpleValueType(0);
4340b57cec5SDimitry Andric       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
4350b57cec5SDimitry Andric     }
4360b57cec5SDimitry Andric 
getPermuteVINSERTCommutedImmediate(SDNode * N,unsigned VecWidth,const SDLoc & DL)437349cc55cSDimitry Andric     SDValue getPermuteVINSERTCommutedImmediate(SDNode *N, unsigned VecWidth,
438349cc55cSDimitry Andric                                                const SDLoc &DL) {
439349cc55cSDimitry Andric       assert(VecWidth == 128 && "Unexpected vector width");
440349cc55cSDimitry Andric       uint64_t Index = N->getConstantOperandVal(2);
441349cc55cSDimitry Andric       MVT VecVT = N->getSimpleValueType(0);
442349cc55cSDimitry Andric       uint64_t InsertIdx = (Index * VecVT.getScalarSizeInBits()) / VecWidth;
443349cc55cSDimitry Andric       assert((InsertIdx == 0 || InsertIdx == 1) && "Bad insertf128 index");
444349cc55cSDimitry Andric       // vinsert(0,sub,vec) -> [sub0][vec1] -> vperm2x128(0x30,vec,sub)
445349cc55cSDimitry Andric       // vinsert(1,sub,vec) -> [vec0][sub0] -> vperm2x128(0x02,vec,sub)
446349cc55cSDimitry Andric       return getI8Imm(InsertIdx ? 0x02 : 0x30, DL);
447349cc55cSDimitry Andric     }
448349cc55cSDimitry Andric 
getSBBZero(SDNode * N)44981ad6265SDimitry Andric     SDValue getSBBZero(SDNode *N) {
45081ad6265SDimitry Andric       SDLoc dl(N);
45181ad6265SDimitry Andric       MVT VT = N->getSimpleValueType(0);
45281ad6265SDimitry Andric 
45381ad6265SDimitry Andric       // Create zero.
45481ad6265SDimitry Andric       SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
455bdd1243dSDimitry Andric       SDValue Zero = SDValue(
456bdd1243dSDimitry Andric           CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, std::nullopt), 0);
45781ad6265SDimitry Andric       if (VT == MVT::i64) {
45881ad6265SDimitry Andric         Zero = SDValue(
45981ad6265SDimitry Andric             CurDAG->getMachineNode(
46081ad6265SDimitry Andric                 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
46181ad6265SDimitry Andric                 CurDAG->getTargetConstant(0, dl, MVT::i64), Zero,
46281ad6265SDimitry Andric                 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
46381ad6265SDimitry Andric             0);
46481ad6265SDimitry Andric       }
46581ad6265SDimitry Andric 
46681ad6265SDimitry Andric       // Copy flags to the EFLAGS register and glue it to next node.
46781ad6265SDimitry Andric       unsigned Opcode = N->getOpcode();
46881ad6265SDimitry Andric       assert((Opcode == X86ISD::SBB || Opcode == X86ISD::SETCC_CARRY) &&
46981ad6265SDimitry Andric              "Unexpected opcode for SBB materialization");
47081ad6265SDimitry Andric       unsigned FlagOpIndex = Opcode == X86ISD::SBB ? 2 : 1;
47181ad6265SDimitry Andric       SDValue EFLAGS =
47281ad6265SDimitry Andric           CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
47381ad6265SDimitry Andric                                N->getOperand(FlagOpIndex), SDValue());
47481ad6265SDimitry Andric 
47581ad6265SDimitry Andric       // Create a 64-bit instruction if the result is 64-bits otherwise use the
47681ad6265SDimitry Andric       // 32-bit version.
47781ad6265SDimitry Andric       unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr;
47881ad6265SDimitry Andric       MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
47981ad6265SDimitry Andric       VTs = CurDAG->getVTList(SBBVT, MVT::i32);
48081ad6265SDimitry Andric       return SDValue(
48181ad6265SDimitry Andric           CurDAG->getMachineNode(Opc, dl, VTs,
48281ad6265SDimitry Andric                                  {Zero, Zero, EFLAGS, EFLAGS.getValue(1)}),
48381ad6265SDimitry Andric           0);
48481ad6265SDimitry Andric     }
48581ad6265SDimitry Andric 
4860b57cec5SDimitry Andric     // Helper to detect unneeded and instructions on shift amounts. Called
4870b57cec5SDimitry Andric     // from PatFrags in tablegen.
isUnneededShiftMask(SDNode * N,unsigned Width) const4880b57cec5SDimitry Andric     bool isUnneededShiftMask(SDNode *N, unsigned Width) const {
4890b57cec5SDimitry Andric       assert(N->getOpcode() == ISD::AND && "Unexpected opcode");
490647cbc5dSDimitry Andric       const APInt &Val = N->getConstantOperandAPInt(1);
4910b57cec5SDimitry Andric 
49206c3fb27SDimitry Andric       if (Val.countr_one() >= Width)
4930b57cec5SDimitry Andric         return true;
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric       APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;
49606c3fb27SDimitry Andric       return Mask.countr_one() >= Width;
4970b57cec5SDimitry Andric     }
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric     /// Return an SDNode that returns the value of the global base register.
5000b57cec5SDimitry Andric     /// Output instructions required to initialize the global base register,
5010b57cec5SDimitry Andric     /// if necessary.
5020b57cec5SDimitry Andric     SDNode *getGlobalBaseReg();
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric     /// Return a reference to the TargetMachine, casted to the target-specific
5050b57cec5SDimitry Andric     /// type.
getTargetMachine() const5060b57cec5SDimitry Andric     const X86TargetMachine &getTargetMachine() const {
5070b57cec5SDimitry Andric       return static_cast<const X86TargetMachine &>(TM);
5080b57cec5SDimitry Andric     }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric     /// Return a reference to the TargetInstrInfo, casted to the target-specific
5110b57cec5SDimitry Andric     /// type.
getInstrInfo() const5120b57cec5SDimitry Andric     const X86InstrInfo *getInstrInfo() const {
5130b57cec5SDimitry Andric       return Subtarget->getInstrInfo();
5140b57cec5SDimitry Andric     }
5150b57cec5SDimitry Andric 
51681ad6265SDimitry Andric     /// Return a condition code of the given SDNode
51781ad6265SDimitry Andric     X86::CondCode getCondFromNode(SDNode *N) const;
51881ad6265SDimitry Andric 
5190b57cec5SDimitry Andric     /// Address-mode matching performs shift-of-and to and-of-shift
5200b57cec5SDimitry Andric     /// reassociation in order to expose more scaled addressing
5210b57cec5SDimitry Andric     /// opportunities.
ComplexPatternFuncMutatesDAG() const5220b57cec5SDimitry Andric     bool ComplexPatternFuncMutatesDAG() const override {
5230b57cec5SDimitry Andric       return true;
5240b57cec5SDimitry Andric     }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric     bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric     // Indicates we should prefer to use a non-temporal load for this load.
useNonTemporalLoad(LoadSDNode * N) const5290b57cec5SDimitry Andric     bool useNonTemporalLoad(LoadSDNode *N) const {
5300b57cec5SDimitry Andric       if (!N->isNonTemporal())
5310b57cec5SDimitry Andric         return false;
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric       unsigned StoreSize = N->getMemoryVT().getStoreSize();
5340b57cec5SDimitry Andric 
53581ad6265SDimitry Andric       if (N->getAlign().value() < StoreSize)
5360b57cec5SDimitry Andric         return false;
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric       switch (StoreSize) {
5390b57cec5SDimitry Andric       default: llvm_unreachable("Unsupported store size");
5400b57cec5SDimitry Andric       case 4:
5410b57cec5SDimitry Andric       case 8:
5420b57cec5SDimitry Andric         return false;
5430b57cec5SDimitry Andric       case 16:
5440b57cec5SDimitry Andric         return Subtarget->hasSSE41();
5450b57cec5SDimitry Andric       case 32:
5460b57cec5SDimitry Andric         return Subtarget->hasAVX2();
5470b57cec5SDimitry Andric       case 64:
5480b57cec5SDimitry Andric         return Subtarget->hasAVX512();
5490b57cec5SDimitry Andric       }
5500b57cec5SDimitry Andric     }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric     bool foldLoadStoreIntoMemOperand(SDNode *Node);
5530b57cec5SDimitry Andric     MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
5540b57cec5SDimitry Andric     bool matchBitExtract(SDNode *Node);
5550b57cec5SDimitry Andric     bool shrinkAndImmediate(SDNode *N);
5560b57cec5SDimitry Andric     bool isMaskZeroExtended(SDNode *N) const;
5570b57cec5SDimitry Andric     bool tryShiftAmountMod(SDNode *N);
5580b57cec5SDimitry Andric     bool tryShrinkShlLogicImm(SDNode *N);
5595ffd83dbSDimitry Andric     bool tryVPTERNLOG(SDNode *N);
560349cc55cSDimitry Andric     bool matchVPTERNLOG(SDNode *Root, SDNode *ParentA, SDNode *ParentB,
561349cc55cSDimitry Andric                         SDNode *ParentC, SDValue A, SDValue B, SDValue C,
562349cc55cSDimitry Andric                         uint8_t Imm);
5630b57cec5SDimitry Andric     bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);
5648bcb0991SDimitry Andric     bool tryMatchBitSelect(SDNode *N);
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric     MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
5670b57cec5SDimitry Andric                                 const SDLoc &dl, MVT VT, SDNode *Node);
5680b57cec5SDimitry Andric     MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
5690b57cec5SDimitry Andric                                 const SDLoc &dl, MVT VT, SDNode *Node,
57006c3fb27SDimitry Andric                                 SDValue &InGlue);
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric     bool tryOptimizeRem8Extend(SDNode *N);
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric     bool onlyUsesZeroFlag(SDValue Flags) const;
5750b57cec5SDimitry Andric     bool hasNoSignFlagUses(SDValue Flags) const;
5760b57cec5SDimitry Andric     bool hasNoCarryFlagUses(SDValue Flags) const;
5770b57cec5SDimitry Andric   };
578*0fca6ea1SDimitry Andric 
579*0fca6ea1SDimitry Andric   class X86DAGToDAGISelLegacy : public SelectionDAGISelLegacy {
580*0fca6ea1SDimitry Andric   public:
581*0fca6ea1SDimitry Andric     static char ID;
X86DAGToDAGISelLegacy(X86TargetMachine & tm,CodeGenOptLevel OptLevel)582*0fca6ea1SDimitry Andric     explicit X86DAGToDAGISelLegacy(X86TargetMachine &tm,
583*0fca6ea1SDimitry Andric                                    CodeGenOptLevel OptLevel)
584*0fca6ea1SDimitry Andric         : SelectionDAGISelLegacy(
585*0fca6ea1SDimitry Andric               ID, std::make_unique<X86DAGToDAGISel>(tm, OptLevel)) {}
586*0fca6ea1SDimitry Andric   };
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
589*0fca6ea1SDimitry Andric char X86DAGToDAGISelLegacy::ID = 0;
590bdd1243dSDimitry Andric 
INITIALIZE_PASS(X86DAGToDAGISelLegacy,DEBUG_TYPE,PASS_NAME,false,false)591*0fca6ea1SDimitry Andric INITIALIZE_PASS(X86DAGToDAGISelLegacy, DEBUG_TYPE, PASS_NAME, false, false)
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric // Returns true if this masked compare can be implemented legally with this
5940b57cec5SDimitry Andric // type.
5950b57cec5SDimitry Andric static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
5960b57cec5SDimitry Andric   unsigned Opcode = N->getOpcode();
597e8d8bef9SDimitry Andric   if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMM ||
598e8d8bef9SDimitry Andric       Opcode == X86ISD::STRICT_CMPM || Opcode == ISD::SETCC ||
599e8d8bef9SDimitry Andric       Opcode == X86ISD::CMPMM_SAE || Opcode == X86ISD::VFPCLASS) {
6000b57cec5SDimitry Andric     // We can get 256-bit 8 element types here without VLX being enabled. When
6010b57cec5SDimitry Andric     // this happens we will use 512-bit operations and the mask will not be
6020b57cec5SDimitry Andric     // zero extended.
6030b57cec5SDimitry Andric     EVT OpVT = N->getOperand(0).getValueType();
604480093f4SDimitry Andric     // The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the
605480093f4SDimitry Andric     // second operand.
606480093f4SDimitry Andric     if (Opcode == X86ISD::STRICT_CMPM)
607480093f4SDimitry Andric       OpVT = N->getOperand(1).getValueType();
6080b57cec5SDimitry Andric     if (OpVT.is256BitVector() || OpVT.is128BitVector())
6090b57cec5SDimitry Andric       return Subtarget->hasVLX();
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric     return true;
6120b57cec5SDimitry Andric   }
6130b57cec5SDimitry Andric   // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
6140b57cec5SDimitry Andric   if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
6150b57cec5SDimitry Andric       Opcode == X86ISD::FSETCCM_SAE)
6160b57cec5SDimitry Andric     return true;
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric   return false;
6190b57cec5SDimitry Andric }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric // Returns true if we can assume the writer of the mask has zero extended it
6220b57cec5SDimitry Andric // for us.
isMaskZeroExtended(SDNode * N) const6230b57cec5SDimitry Andric bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
6240b57cec5SDimitry Andric   // If this is an AND, check if we have a compare on either side. As long as
6250b57cec5SDimitry Andric   // one side guarantees the mask is zero extended, the AND will preserve those
6260b57cec5SDimitry Andric   // zeros.
6270b57cec5SDimitry Andric   if (N->getOpcode() == ISD::AND)
6280b57cec5SDimitry Andric     return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
6290b57cec5SDimitry Andric            isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric   return isLegalMaskCompare(N, Subtarget);
6320b57cec5SDimitry Andric }
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric bool
IsProfitableToFold(SDValue N,SDNode * U,SDNode * Root) const6350b57cec5SDimitry Andric X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
6365f757f3fSDimitry Andric   if (OptLevel == CodeGenOptLevel::None)
6375f757f3fSDimitry Andric     return false;
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   if (!N.hasOneUse())
6400b57cec5SDimitry Andric     return false;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   if (N.getOpcode() != ISD::LOAD)
6430b57cec5SDimitry Andric     return true;
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   // Don't fold non-temporal loads if we have an instruction for them.
6460b57cec5SDimitry Andric   if (useNonTemporalLoad(cast<LoadSDNode>(N)))
6470b57cec5SDimitry Andric     return false;
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   // If N is a load, do additional profitability checks.
6500b57cec5SDimitry Andric   if (U == Root) {
6510b57cec5SDimitry Andric     switch (U->getOpcode()) {
6520b57cec5SDimitry Andric     default: break;
6530b57cec5SDimitry Andric     case X86ISD::ADD:
6540b57cec5SDimitry Andric     case X86ISD::ADC:
6550b57cec5SDimitry Andric     case X86ISD::SUB:
6560b57cec5SDimitry Andric     case X86ISD::SBB:
6570b57cec5SDimitry Andric     case X86ISD::AND:
6580b57cec5SDimitry Andric     case X86ISD::XOR:
6590b57cec5SDimitry Andric     case X86ISD::OR:
6600b57cec5SDimitry Andric     case ISD::ADD:
66106c3fb27SDimitry Andric     case ISD::UADDO_CARRY:
6620b57cec5SDimitry Andric     case ISD::AND:
6630b57cec5SDimitry Andric     case ISD::OR:
6640b57cec5SDimitry Andric     case ISD::XOR: {
6650b57cec5SDimitry Andric       SDValue Op1 = U->getOperand(1);
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric       // If the other operand is a 8-bit immediate we should fold the immediate
6680b57cec5SDimitry Andric       // instead. This reduces code size.
6690b57cec5SDimitry Andric       // e.g.
6700b57cec5SDimitry Andric       // movl 4(%esp), %eax
6710b57cec5SDimitry Andric       // addl $4, %eax
6720b57cec5SDimitry Andric       // vs.
6730b57cec5SDimitry Andric       // movl $4, %eax
6740b57cec5SDimitry Andric       // addl 4(%esp), %eax
6750b57cec5SDimitry Andric       // The former is 2 bytes shorter. In case where the increment is 1, then
6760b57cec5SDimitry Andric       // the saving can be 4 bytes (by using incl %eax).
677bdd1243dSDimitry Andric       if (auto *Imm = dyn_cast<ConstantSDNode>(Op1)) {
6780b57cec5SDimitry Andric         if (Imm->getAPIntValue().isSignedIntN(8))
6790b57cec5SDimitry Andric           return false;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric         // If this is a 64-bit AND with an immediate that fits in 32-bits,
6820b57cec5SDimitry Andric         // prefer using the smaller and over folding the load. This is needed to
6830b57cec5SDimitry Andric         // make sure immediates created by shrinkAndImmediate are always folded.
6840b57cec5SDimitry Andric         // Ideally we would narrow the load during DAG combine and get the
6850b57cec5SDimitry Andric         // best of both worlds.
6860b57cec5SDimitry Andric         if (U->getOpcode() == ISD::AND &&
6870b57cec5SDimitry Andric             Imm->getAPIntValue().getBitWidth() == 64 &&
6880b57cec5SDimitry Andric             Imm->getAPIntValue().isIntN(32))
6890b57cec5SDimitry Andric           return false;
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric         // If this really a zext_inreg that can be represented with a movzx
6920b57cec5SDimitry Andric         // instruction, prefer that.
6930b57cec5SDimitry Andric         // TODO: We could shrink the load and fold if it is non-volatile.
6940b57cec5SDimitry Andric         if (U->getOpcode() == ISD::AND &&
6950b57cec5SDimitry Andric             (Imm->getAPIntValue() == UINT8_MAX ||
6960b57cec5SDimitry Andric              Imm->getAPIntValue() == UINT16_MAX ||
6970b57cec5SDimitry Andric              Imm->getAPIntValue() == UINT32_MAX))
6980b57cec5SDimitry Andric           return false;
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric         // ADD/SUB with can negate the immediate and use the opposite operation
7010b57cec5SDimitry Andric         // to fit 128 into a sign extended 8 bit immediate.
7020b57cec5SDimitry Andric         if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&
7030b57cec5SDimitry Andric             (-Imm->getAPIntValue()).isSignedIntN(8))
7040b57cec5SDimitry Andric           return false;
7055ffd83dbSDimitry Andric 
7065ffd83dbSDimitry Andric         if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) &&
7075ffd83dbSDimitry Andric             (-Imm->getAPIntValue()).isSignedIntN(8) &&
7085ffd83dbSDimitry Andric             hasNoCarryFlagUses(SDValue(U, 1)))
7095ffd83dbSDimitry Andric           return false;
7100b57cec5SDimitry Andric       }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric       // If the other operand is a TLS address, we should fold it instead.
7130b57cec5SDimitry Andric       // This produces
7140b57cec5SDimitry Andric       // movl    %gs:0, %eax
7150b57cec5SDimitry Andric       // leal    i@NTPOFF(%eax), %eax
7160b57cec5SDimitry Andric       // instead of
7170b57cec5SDimitry Andric       // movl    $i@NTPOFF, %eax
7180b57cec5SDimitry Andric       // addl    %gs:0, %eax
7190b57cec5SDimitry Andric       // if the block also has an access to a second TLS address this will save
7200b57cec5SDimitry Andric       // a load.
7210b57cec5SDimitry Andric       // FIXME: This is probably also true for non-TLS addresses.
7220b57cec5SDimitry Andric       if (Op1.getOpcode() == X86ISD::Wrapper) {
7230b57cec5SDimitry Andric         SDValue Val = Op1.getOperand(0);
7240b57cec5SDimitry Andric         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
7250b57cec5SDimitry Andric           return false;
7260b57cec5SDimitry Andric       }
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric       // Don't fold load if this matches the BTS/BTR/BTC patterns.
7290b57cec5SDimitry Andric       // BTS: (or X, (shl 1, n))
7300b57cec5SDimitry Andric       // BTR: (and X, (rotl -2, n))
7310b57cec5SDimitry Andric       // BTC: (xor X, (shl 1, n))
7320b57cec5SDimitry Andric       if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
7330b57cec5SDimitry Andric         if (U->getOperand(0).getOpcode() == ISD::SHL &&
7340b57cec5SDimitry Andric             isOneConstant(U->getOperand(0).getOperand(0)))
7350b57cec5SDimitry Andric           return false;
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric         if (U->getOperand(1).getOpcode() == ISD::SHL &&
7380b57cec5SDimitry Andric             isOneConstant(U->getOperand(1).getOperand(0)))
7390b57cec5SDimitry Andric           return false;
7400b57cec5SDimitry Andric       }
7410b57cec5SDimitry Andric       if (U->getOpcode() == ISD::AND) {
7420b57cec5SDimitry Andric         SDValue U0 = U->getOperand(0);
7430b57cec5SDimitry Andric         SDValue U1 = U->getOperand(1);
7440b57cec5SDimitry Andric         if (U0.getOpcode() == ISD::ROTL) {
7450b57cec5SDimitry Andric           auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
7460b57cec5SDimitry Andric           if (C && C->getSExtValue() == -2)
7470b57cec5SDimitry Andric             return false;
7480b57cec5SDimitry Andric         }
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric         if (U1.getOpcode() == ISD::ROTL) {
7510b57cec5SDimitry Andric           auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
7520b57cec5SDimitry Andric           if (C && C->getSExtValue() == -2)
7530b57cec5SDimitry Andric             return false;
7540b57cec5SDimitry Andric         }
7550b57cec5SDimitry Andric       }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric       break;
7580b57cec5SDimitry Andric     }
7590b57cec5SDimitry Andric     case ISD::SHL:
7600b57cec5SDimitry Andric     case ISD::SRA:
7610b57cec5SDimitry Andric     case ISD::SRL:
7620b57cec5SDimitry Andric       // Don't fold a load into a shift by immediate. The BMI2 instructions
7630b57cec5SDimitry Andric       // support folding a load, but not an immediate. The legacy instructions
7640b57cec5SDimitry Andric       // support folding an immediate, but can't fold a load. Folding an
7650b57cec5SDimitry Andric       // immediate is preferable to folding a load.
7660b57cec5SDimitry Andric       if (isa<ConstantSDNode>(U->getOperand(1)))
7670b57cec5SDimitry Andric         return false;
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric       break;
7700b57cec5SDimitry Andric     }
7710b57cec5SDimitry Andric   }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   // Prevent folding a load if this can implemented with an insert_subreg or
7740b57cec5SDimitry Andric   // a move that implicitly zeroes.
7750b57cec5SDimitry Andric   if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
7760b57cec5SDimitry Andric       isNullConstant(Root->getOperand(2)) &&
7770b57cec5SDimitry Andric       (Root->getOperand(0).isUndef() ||
7780b57cec5SDimitry Andric        ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
7790b57cec5SDimitry Andric     return false;
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   return true;
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7845ffd83dbSDimitry Andric // Indicates it is profitable to form an AVX512 masked operation. Returning
7855ffd83dbSDimitry Andric // false will favor a masked register-register masked move or vblendm and the
7865ffd83dbSDimitry Andric // operation will be selected separately.
isProfitableToFormMaskedOp(SDNode * N) const7875ffd83dbSDimitry Andric bool X86DAGToDAGISel::isProfitableToFormMaskedOp(SDNode *N) const {
7885ffd83dbSDimitry Andric   assert(
7895ffd83dbSDimitry Andric       (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::SELECTS) &&
7905ffd83dbSDimitry Andric       "Unexpected opcode!");
7915ffd83dbSDimitry Andric 
7925ffd83dbSDimitry Andric   // If the operation has additional users, the operation will be duplicated.
7935ffd83dbSDimitry Andric   // Check the use count to prevent that.
7945ffd83dbSDimitry Andric   // FIXME: Are there cheap opcodes we might want to duplicate?
7955ffd83dbSDimitry Andric   return N->getOperand(1).hasOneUse();
7965ffd83dbSDimitry Andric }
7975ffd83dbSDimitry Andric 
7980b57cec5SDimitry Andric /// Replace the original chain operand of the call with
7990b57cec5SDimitry Andric /// load's chain operand and move load below the call's chain operand.
moveBelowOrigChain(SelectionDAG * CurDAG,SDValue Load,SDValue Call,SDValue OrigChain)8000b57cec5SDimitry Andric static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
8010b57cec5SDimitry Andric                                SDValue Call, SDValue OrigChain) {
8020b57cec5SDimitry Andric   SmallVector<SDValue, 8> Ops;
8030b57cec5SDimitry Andric   SDValue Chain = OrigChain.getOperand(0);
8040b57cec5SDimitry Andric   if (Chain.getNode() == Load.getNode())
8050b57cec5SDimitry Andric     Ops.push_back(Load.getOperand(0));
8060b57cec5SDimitry Andric   else {
8070b57cec5SDimitry Andric     assert(Chain.getOpcode() == ISD::TokenFactor &&
8080b57cec5SDimitry Andric            "Unexpected chain operand");
8090b57cec5SDimitry Andric     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
8100b57cec5SDimitry Andric       if (Chain.getOperand(i).getNode() == Load.getNode())
8110b57cec5SDimitry Andric         Ops.push_back(Load.getOperand(0));
8120b57cec5SDimitry Andric       else
8130b57cec5SDimitry Andric         Ops.push_back(Chain.getOperand(i));
8140b57cec5SDimitry Andric     SDValue NewChain =
8150b57cec5SDimitry Andric       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
8160b57cec5SDimitry Andric     Ops.clear();
8170b57cec5SDimitry Andric     Ops.push_back(NewChain);
8180b57cec5SDimitry Andric   }
8190b57cec5SDimitry Andric   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
8200b57cec5SDimitry Andric   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
8210b57cec5SDimitry Andric   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
8220b57cec5SDimitry Andric                              Load.getOperand(1), Load.getOperand(2));
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   Ops.clear();
8250b57cec5SDimitry Andric   Ops.push_back(SDValue(Load.getNode(), 1));
8260b57cec5SDimitry Andric   Ops.append(Call->op_begin() + 1, Call->op_end());
8270b57cec5SDimitry Andric   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric /// Return true if call address is a load and it can be
8310b57cec5SDimitry Andric /// moved below CALLSEQ_START and the chains leading up to the call.
8320b57cec5SDimitry Andric /// Return the CALLSEQ_START by reference as a second output.
8330b57cec5SDimitry Andric /// In the case of a tail call, there isn't a callseq node between the call
8340b57cec5SDimitry Andric /// chain and the load.
isCalleeLoad(SDValue Callee,SDValue & Chain,bool HasCallSeq)8350b57cec5SDimitry Andric static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
8360b57cec5SDimitry Andric   // The transformation is somewhat dangerous if the call's chain was glued to
8370b57cec5SDimitry Andric   // the call. After MoveBelowOrigChain the load is moved between the call and
8380b57cec5SDimitry Andric   // the chain, this can create a cycle if the load is not folded. So it is
8390b57cec5SDimitry Andric   // *really* important that we are sure the load will be folded.
8400b57cec5SDimitry Andric   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
8410b57cec5SDimitry Andric     return false;
842bdd1243dSDimitry Andric   auto *LD = dyn_cast<LoadSDNode>(Callee.getNode());
8430b57cec5SDimitry Andric   if (!LD ||
8448bcb0991SDimitry Andric       !LD->isSimple() ||
8450b57cec5SDimitry Andric       LD->getAddressingMode() != ISD::UNINDEXED ||
8460b57cec5SDimitry Andric       LD->getExtensionType() != ISD::NON_EXTLOAD)
8470b57cec5SDimitry Andric     return false;
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   // Now let's find the callseq_start.
8500b57cec5SDimitry Andric   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
8510b57cec5SDimitry Andric     if (!Chain.hasOneUse())
8520b57cec5SDimitry Andric       return false;
8530b57cec5SDimitry Andric     Chain = Chain.getOperand(0);
8540b57cec5SDimitry Andric   }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   if (!Chain.getNumOperands())
8570b57cec5SDimitry Andric     return false;
8580b57cec5SDimitry Andric   // Since we are not checking for AA here, conservatively abort if the chain
8590b57cec5SDimitry Andric   // writes to memory. It's not safe to move the callee (a load) across a store.
8600b57cec5SDimitry Andric   if (isa<MemSDNode>(Chain.getNode()) &&
8610b57cec5SDimitry Andric       cast<MemSDNode>(Chain.getNode())->writeMem())
8620b57cec5SDimitry Andric     return false;
8630b57cec5SDimitry Andric   if (Chain.getOperand(0).getNode() == Callee.getNode())
8640b57cec5SDimitry Andric     return true;
8650b57cec5SDimitry Andric   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
8660b57cec5SDimitry Andric       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
8670b57cec5SDimitry Andric       Callee.getValue(1).hasOneUse())
8680b57cec5SDimitry Andric     return true;
8690b57cec5SDimitry Andric   return false;
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
isEndbrImm64(uint64_t Imm)872e8d8bef9SDimitry Andric static bool isEndbrImm64(uint64_t Imm) {
873e8d8bef9SDimitry Andric // There may be some other prefix bytes between 0xF3 and 0x0F1EFA.
874e8d8bef9SDimitry Andric // i.g: 0xF3660F1EFA, 0xF3670F1EFA
875e8d8bef9SDimitry Andric   if ((Imm & 0x00FFFFFF) != 0x0F1EFA)
876e8d8bef9SDimitry Andric     return false;
877e8d8bef9SDimitry Andric 
878e8d8bef9SDimitry Andric   uint8_t OptionalPrefixBytes [] = {0x26, 0x2e, 0x36, 0x3e, 0x64,
879e8d8bef9SDimitry Andric                                     0x65, 0x66, 0x67, 0xf0, 0xf2};
880e8d8bef9SDimitry Andric   int i = 24; // 24bit 0x0F1EFA has matched
881e8d8bef9SDimitry Andric   while (i < 64) {
882e8d8bef9SDimitry Andric     uint8_t Byte = (Imm >> i) & 0xFF;
883e8d8bef9SDimitry Andric     if (Byte == 0xF3)
884e8d8bef9SDimitry Andric       return true;
885e8d8bef9SDimitry Andric     if (!llvm::is_contained(OptionalPrefixBytes, Byte))
886e8d8bef9SDimitry Andric       return false;
887e8d8bef9SDimitry Andric     i += 8;
888e8d8bef9SDimitry Andric   }
889e8d8bef9SDimitry Andric 
890e8d8bef9SDimitry Andric   return false;
891e8d8bef9SDimitry Andric }
892e8d8bef9SDimitry Andric 
needBWI(MVT VT)8935f757f3fSDimitry Andric static bool needBWI(MVT VT) {
8945f757f3fSDimitry Andric   return (VT == MVT::v32i16 || VT == MVT::v32f16 || VT == MVT::v64i8);
8955f757f3fSDimitry Andric }
8965f757f3fSDimitry Andric 
PreprocessISelDAG()8970b57cec5SDimitry Andric void X86DAGToDAGISel::PreprocessISelDAG() {
8985ffd83dbSDimitry Andric   bool MadeChange = false;
8990b57cec5SDimitry Andric   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
9000b57cec5SDimitry Andric        E = CurDAG->allnodes_end(); I != E; ) {
9010b57cec5SDimitry Andric     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
9020b57cec5SDimitry Andric 
903e8d8bef9SDimitry Andric     // This is for CET enhancement.
904e8d8bef9SDimitry Andric     //
905e8d8bef9SDimitry Andric     // ENDBR32 and ENDBR64 have specific opcodes:
906e8d8bef9SDimitry Andric     // ENDBR32: F3 0F 1E FB
907e8d8bef9SDimitry Andric     // ENDBR64: F3 0F 1E FA
908e8d8bef9SDimitry Andric     // And we want that attackers won’t find unintended ENDBR32/64
909e8d8bef9SDimitry Andric     // opcode matches in the binary
910e8d8bef9SDimitry Andric     // Here’s an example:
911e8d8bef9SDimitry Andric     // If the compiler had to generate asm for the following code:
912e8d8bef9SDimitry Andric     // a = 0xF30F1EFA
913e8d8bef9SDimitry Andric     // it could, for example, generate:
914e8d8bef9SDimitry Andric     // mov 0xF30F1EFA, dword ptr[a]
915e8d8bef9SDimitry Andric     // In such a case, the binary would include a gadget that starts
916e8d8bef9SDimitry Andric     // with a fake ENDBR64 opcode. Therefore, we split such generation
917e8d8bef9SDimitry Andric     // into multiple operations, let it not shows in the binary
918e8d8bef9SDimitry Andric     if (N->getOpcode() == ISD::Constant) {
919e8d8bef9SDimitry Andric       MVT VT = N->getSimpleValueType(0);
920e8d8bef9SDimitry Andric       int64_t Imm = cast<ConstantSDNode>(N)->getSExtValue();
921e8d8bef9SDimitry Andric       int32_t EndbrImm = Subtarget->is64Bit() ? 0xF30F1EFA : 0xF30F1EFB;
922e8d8bef9SDimitry Andric       if (Imm == EndbrImm || isEndbrImm64(Imm)) {
923e8d8bef9SDimitry Andric         // Check that the cf-protection-branch is enabled.
924e8d8bef9SDimitry Andric         Metadata *CFProtectionBranch =
925*0fca6ea1SDimitry Andric             MF->getFunction().getParent()->getModuleFlag(
926*0fca6ea1SDimitry Andric                 "cf-protection-branch");
927e8d8bef9SDimitry Andric         if (CFProtectionBranch || IndirectBranchTracking) {
928e8d8bef9SDimitry Andric           SDLoc dl(N);
929e8d8bef9SDimitry Andric           SDValue Complement = CurDAG->getConstant(~Imm, dl, VT, false, true);
930e8d8bef9SDimitry Andric           Complement = CurDAG->getNOT(dl, Complement, VT);
931e8d8bef9SDimitry Andric           --I;
932e8d8bef9SDimitry Andric           CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Complement);
933e8d8bef9SDimitry Andric           ++I;
934e8d8bef9SDimitry Andric           MadeChange = true;
935e8d8bef9SDimitry Andric           continue;
936e8d8bef9SDimitry Andric         }
937e8d8bef9SDimitry Andric       }
938e8d8bef9SDimitry Andric     }
939e8d8bef9SDimitry Andric 
9400b57cec5SDimitry Andric     // If this is a target specific AND node with no flag usages, turn it back
9410b57cec5SDimitry Andric     // into ISD::AND to enable test instruction matching.
9420b57cec5SDimitry Andric     if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
9430b57cec5SDimitry Andric       SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
9440b57cec5SDimitry Andric                                     N->getOperand(0), N->getOperand(1));
9450b57cec5SDimitry Andric       --I;
9460b57cec5SDimitry Andric       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
9470b57cec5SDimitry Andric       ++I;
9485ffd83dbSDimitry Andric       MadeChange = true;
9490b57cec5SDimitry Andric       continue;
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
952349cc55cSDimitry Andric     // Convert vector increment or decrement to sub/add with an all-ones
953349cc55cSDimitry Andric     // constant:
954349cc55cSDimitry Andric     // add X, <1, 1...> --> sub X, <-1, -1...>
955349cc55cSDimitry Andric     // sub X, <1, 1...> --> add X, <-1, -1...>
956349cc55cSDimitry Andric     // The all-ones vector constant can be materialized using a pcmpeq
957349cc55cSDimitry Andric     // instruction that is commonly recognized as an idiom (has no register
958349cc55cSDimitry Andric     // dependency), so that's better/smaller than loading a splat 1 constant.
959349cc55cSDimitry Andric     //
960349cc55cSDimitry Andric     // But don't do this if it would inhibit a potentially profitable load
961349cc55cSDimitry Andric     // folding opportunity for the other operand. That only occurs with the
962349cc55cSDimitry Andric     // intersection of:
963349cc55cSDimitry Andric     // (1) The other operand (op0) is load foldable.
964349cc55cSDimitry Andric     // (2) The op is an add (otherwise, we are *creating* an add and can still
965349cc55cSDimitry Andric     //     load fold the other op).
966349cc55cSDimitry Andric     // (3) The target has AVX (otherwise, we have a destructive add and can't
967349cc55cSDimitry Andric     //     load fold the other op without killing the constant op).
968349cc55cSDimitry Andric     // (4) The constant 1 vector has multiple uses (so it is profitable to load
969349cc55cSDimitry Andric     //     into a register anyway).
970349cc55cSDimitry Andric     auto mayPreventLoadFold = [&]() {
971349cc55cSDimitry Andric       return X86::mayFoldLoad(N->getOperand(0), *Subtarget) &&
972349cc55cSDimitry Andric              N->getOpcode() == ISD::ADD && Subtarget->hasAVX() &&
973349cc55cSDimitry Andric              !N->getOperand(1).hasOneUse();
974349cc55cSDimitry Andric     };
9755ffd83dbSDimitry Andric     if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
976349cc55cSDimitry Andric         N->getSimpleValueType(0).isVector() && !mayPreventLoadFold()) {
9775ffd83dbSDimitry Andric       APInt SplatVal;
9785ffd83dbSDimitry Andric       if (X86::isConstantSplat(N->getOperand(1), SplatVal) &&
979349cc55cSDimitry Andric           SplatVal.isOne()) {
9805ffd83dbSDimitry Andric         SDLoc DL(N);
9815ffd83dbSDimitry Andric 
9825ffd83dbSDimitry Andric         MVT VT = N->getSimpleValueType(0);
9835ffd83dbSDimitry Andric         unsigned NumElts = VT.getSizeInBits() / 32;
9845ffd83dbSDimitry Andric         SDValue AllOnes =
9855ffd83dbSDimitry Andric             CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts));
9865ffd83dbSDimitry Andric         AllOnes = CurDAG->getBitcast(VT, AllOnes);
9875ffd83dbSDimitry Andric 
9885ffd83dbSDimitry Andric         unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
9895ffd83dbSDimitry Andric         SDValue Res =
9905ffd83dbSDimitry Andric             CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes);
9915ffd83dbSDimitry Andric         --I;
9925ffd83dbSDimitry Andric         CurDAG->ReplaceAllUsesWith(N, Res.getNode());
9935ffd83dbSDimitry Andric         ++I;
9945ffd83dbSDimitry Andric         MadeChange = true;
9955ffd83dbSDimitry Andric         continue;
9965ffd83dbSDimitry Andric       }
9975ffd83dbSDimitry Andric     }
9985ffd83dbSDimitry Andric 
9990b57cec5SDimitry Andric     switch (N->getOpcode()) {
10005ffd83dbSDimitry Andric     case X86ISD::VBROADCAST: {
10015ffd83dbSDimitry Andric       MVT VT = N->getSimpleValueType(0);
10025ffd83dbSDimitry Andric       // Emulate v32i16/v64i8 broadcast without BWI.
10035f757f3fSDimitry Andric       if (!Subtarget->hasBWI() && needBWI(VT)) {
10045f757f3fSDimitry Andric         MVT NarrowVT = VT.getHalfNumVectorElementsVT();
10055ffd83dbSDimitry Andric         SDLoc dl(N);
10065ffd83dbSDimitry Andric         SDValue NarrowBCast =
10075ffd83dbSDimitry Andric             CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0));
10085ffd83dbSDimitry Andric         SDValue Res =
10095ffd83dbSDimitry Andric             CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
10105ffd83dbSDimitry Andric                             NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
10115f757f3fSDimitry Andric         unsigned Index = NarrowVT.getVectorMinNumElements();
10125ffd83dbSDimitry Andric         Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
10135ffd83dbSDimitry Andric                               CurDAG->getIntPtrConstant(Index, dl));
10145ffd83dbSDimitry Andric 
10155ffd83dbSDimitry Andric         --I;
10165ffd83dbSDimitry Andric         CurDAG->ReplaceAllUsesWith(N, Res.getNode());
10175ffd83dbSDimitry Andric         ++I;
10185ffd83dbSDimitry Andric         MadeChange = true;
10195ffd83dbSDimitry Andric         continue;
10205ffd83dbSDimitry Andric       }
10215ffd83dbSDimitry Andric 
10225ffd83dbSDimitry Andric       break;
10235ffd83dbSDimitry Andric     }
10245ffd83dbSDimitry Andric     case X86ISD::VBROADCAST_LOAD: {
10255ffd83dbSDimitry Andric       MVT VT = N->getSimpleValueType(0);
10265ffd83dbSDimitry Andric       // Emulate v32i16/v64i8 broadcast without BWI.
10275f757f3fSDimitry Andric       if (!Subtarget->hasBWI() && needBWI(VT)) {
10285f757f3fSDimitry Andric         MVT NarrowVT = VT.getHalfNumVectorElementsVT();
10295ffd83dbSDimitry Andric         auto *MemNode = cast<MemSDNode>(N);
10305ffd83dbSDimitry Andric         SDLoc dl(N);
10315ffd83dbSDimitry Andric         SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other);
10325ffd83dbSDimitry Andric         SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()};
10335ffd83dbSDimitry Andric         SDValue NarrowBCast = CurDAG->getMemIntrinsicNode(
10345ffd83dbSDimitry Andric             X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(),
10355ffd83dbSDimitry Andric             MemNode->getMemOperand());
10365ffd83dbSDimitry Andric         SDValue Res =
10375ffd83dbSDimitry Andric             CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
10385ffd83dbSDimitry Andric                             NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
10395f757f3fSDimitry Andric         unsigned Index = NarrowVT.getVectorMinNumElements();
10405ffd83dbSDimitry Andric         Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
10415ffd83dbSDimitry Andric                               CurDAG->getIntPtrConstant(Index, dl));
10425ffd83dbSDimitry Andric 
10435ffd83dbSDimitry Andric         --I;
10445ffd83dbSDimitry Andric         SDValue To[] = {Res, NarrowBCast.getValue(1)};
10455ffd83dbSDimitry Andric         CurDAG->ReplaceAllUsesWith(N, To);
10465ffd83dbSDimitry Andric         ++I;
10475ffd83dbSDimitry Andric         MadeChange = true;
10485ffd83dbSDimitry Andric         continue;
10495ffd83dbSDimitry Andric       }
10505ffd83dbSDimitry Andric 
10515ffd83dbSDimitry Andric       break;
10525ffd83dbSDimitry Andric     }
10535f757f3fSDimitry Andric     case ISD::LOAD: {
10545f757f3fSDimitry Andric       // If this is a XMM/YMM load of the same lower bits as another YMM/ZMM
10555f757f3fSDimitry Andric       // load, then just extract the lower subvector and avoid the second load.
10565f757f3fSDimitry Andric       auto *Ld = cast<LoadSDNode>(N);
10575f757f3fSDimitry Andric       MVT VT = N->getSimpleValueType(0);
10585f757f3fSDimitry Andric       if (!ISD::isNormalLoad(Ld) || !Ld->isSimple() ||
10595f757f3fSDimitry Andric           !(VT.is128BitVector() || VT.is256BitVector()))
10605f757f3fSDimitry Andric         break;
10615f757f3fSDimitry Andric 
10625f757f3fSDimitry Andric       MVT MaxVT = VT;
10635f757f3fSDimitry Andric       SDNode *MaxLd = nullptr;
10645f757f3fSDimitry Andric       SDValue Ptr = Ld->getBasePtr();
10655f757f3fSDimitry Andric       SDValue Chain = Ld->getChain();
10665f757f3fSDimitry Andric       for (SDNode *User : Ptr->uses()) {
10675f757f3fSDimitry Andric         auto *UserLd = dyn_cast<LoadSDNode>(User);
10685f757f3fSDimitry Andric         MVT UserVT = User->getSimpleValueType(0);
10695f757f3fSDimitry Andric         if (User != N && UserLd && ISD::isNormalLoad(User) &&
10705f757f3fSDimitry Andric             UserLd->getBasePtr() == Ptr && UserLd->getChain() == Chain &&
10715f757f3fSDimitry Andric             !User->hasAnyUseOfValue(1) &&
10725f757f3fSDimitry Andric             (UserVT.is256BitVector() || UserVT.is512BitVector()) &&
10735f757f3fSDimitry Andric             UserVT.getSizeInBits() > VT.getSizeInBits() &&
10745f757f3fSDimitry Andric             (!MaxLd || UserVT.getSizeInBits() > MaxVT.getSizeInBits())) {
10755f757f3fSDimitry Andric           MaxLd = User;
10765f757f3fSDimitry Andric           MaxVT = UserVT;
10775f757f3fSDimitry Andric         }
10785f757f3fSDimitry Andric       }
10795f757f3fSDimitry Andric       if (MaxLd) {
10805f757f3fSDimitry Andric         SDLoc dl(N);
10815f757f3fSDimitry Andric         unsigned NumSubElts = VT.getSizeInBits() / MaxVT.getScalarSizeInBits();
10825f757f3fSDimitry Andric         MVT SubVT = MVT::getVectorVT(MaxVT.getScalarType(), NumSubElts);
10835f757f3fSDimitry Andric         SDValue Extract = CurDAG->getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT,
10845f757f3fSDimitry Andric                                           SDValue(MaxLd, 0),
10855f757f3fSDimitry Andric                                           CurDAG->getIntPtrConstant(0, dl));
10865f757f3fSDimitry Andric         SDValue Res = CurDAG->getBitcast(VT, Extract);
10875f757f3fSDimitry Andric 
10885f757f3fSDimitry Andric         --I;
10895f757f3fSDimitry Andric         SDValue To[] = {Res, SDValue(MaxLd, 1)};
10905f757f3fSDimitry Andric         CurDAG->ReplaceAllUsesWith(N, To);
10915f757f3fSDimitry Andric         ++I;
10925f757f3fSDimitry Andric         MadeChange = true;
10935f757f3fSDimitry Andric         continue;
10945f757f3fSDimitry Andric       }
10955f757f3fSDimitry Andric       break;
10965f757f3fSDimitry Andric     }
10975ffd83dbSDimitry Andric     case ISD::VSELECT: {
109806c3fb27SDimitry Andric       // Replace VSELECT with non-mask conditions with with BLENDV/VPTERNLOG.
109906c3fb27SDimitry Andric       EVT EleVT = N->getOperand(0).getValueType().getVectorElementType();
110006c3fb27SDimitry Andric       if (EleVT == MVT::i1)
11015ffd83dbSDimitry Andric         break;
11025ffd83dbSDimitry Andric 
11035ffd83dbSDimitry Andric       assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!");
110406c3fb27SDimitry Andric       assert(N->getValueType(0).getVectorElementType() != MVT::i16 &&
110506c3fb27SDimitry Andric              "We can't replace VSELECT with BLENDV in vXi16!");
110606c3fb27SDimitry Andric       SDValue R;
110706c3fb27SDimitry Andric       if (Subtarget->hasVLX() && CurDAG->ComputeNumSignBits(N->getOperand(0)) ==
110806c3fb27SDimitry Andric                                      EleVT.getSizeInBits()) {
110906c3fb27SDimitry Andric         R = CurDAG->getNode(X86ISD::VPTERNLOG, SDLoc(N), N->getValueType(0),
111006c3fb27SDimitry Andric                             N->getOperand(0), N->getOperand(1), N->getOperand(2),
111106c3fb27SDimitry Andric                             CurDAG->getTargetConstant(0xCA, SDLoc(N), MVT::i8));
111206c3fb27SDimitry Andric       } else {
111306c3fb27SDimitry Andric         R = CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),
111406c3fb27SDimitry Andric                             N->getOperand(0), N->getOperand(1),
111506c3fb27SDimitry Andric                             N->getOperand(2));
111606c3fb27SDimitry Andric       }
11175ffd83dbSDimitry Andric       --I;
111806c3fb27SDimitry Andric       CurDAG->ReplaceAllUsesWith(N, R.getNode());
11195ffd83dbSDimitry Andric       ++I;
11205ffd83dbSDimitry Andric       MadeChange = true;
11215ffd83dbSDimitry Andric       continue;
11225ffd83dbSDimitry Andric     }
1123480093f4SDimitry Andric     case ISD::FP_ROUND:
1124480093f4SDimitry Andric     case ISD::STRICT_FP_ROUND:
11250b57cec5SDimitry Andric     case ISD::FP_TO_SINT:
1126480093f4SDimitry Andric     case ISD::FP_TO_UINT:
1127480093f4SDimitry Andric     case ISD::STRICT_FP_TO_SINT:
1128480093f4SDimitry Andric     case ISD::STRICT_FP_TO_UINT: {
11290b57cec5SDimitry Andric       // Replace vector fp_to_s/uint with their X86 specific equivalent so we
11300b57cec5SDimitry Andric       // don't need 2 sets of patterns.
11310b57cec5SDimitry Andric       if (!N->getSimpleValueType(0).isVector())
11320b57cec5SDimitry Andric         break;
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric       unsigned NewOpc;
11350b57cec5SDimitry Andric       switch (N->getOpcode()) {
11360b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
1137480093f4SDimitry Andric       case ISD::FP_ROUND:          NewOpc = X86ISD::VFPROUND;        break;
1138480093f4SDimitry Andric       case ISD::STRICT_FP_ROUND:   NewOpc = X86ISD::STRICT_VFPROUND; break;
1139480093f4SDimitry Andric       case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break;
11400b57cec5SDimitry Andric       case ISD::FP_TO_SINT:        NewOpc = X86ISD::CVTTP2SI;        break;
1141480093f4SDimitry Andric       case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break;
11420b57cec5SDimitry Andric       case ISD::FP_TO_UINT:        NewOpc = X86ISD::CVTTP2UI;        break;
11430b57cec5SDimitry Andric       }
1144480093f4SDimitry Andric       SDValue Res;
1145480093f4SDimitry Andric       if (N->isStrictFPOpcode())
1146480093f4SDimitry Andric         Res =
1147480093f4SDimitry Andric             CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other},
1148480093f4SDimitry Andric                             {N->getOperand(0), N->getOperand(1)});
1149480093f4SDimitry Andric       else
1150480093f4SDimitry Andric         Res =
1151480093f4SDimitry Andric             CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
11520b57cec5SDimitry Andric                             N->getOperand(0));
11530b57cec5SDimitry Andric       --I;
1154480093f4SDimitry Andric       CurDAG->ReplaceAllUsesWith(N, Res.getNode());
11550b57cec5SDimitry Andric       ++I;
11565ffd83dbSDimitry Andric       MadeChange = true;
11570b57cec5SDimitry Andric       continue;
11580b57cec5SDimitry Andric     }
11590b57cec5SDimitry Andric     case ISD::SHL:
11600b57cec5SDimitry Andric     case ISD::SRA:
11610b57cec5SDimitry Andric     case ISD::SRL: {
11620b57cec5SDimitry Andric       // Replace vector shifts with their X86 specific equivalent so we don't
11630b57cec5SDimitry Andric       // need 2 sets of patterns.
11640b57cec5SDimitry Andric       if (!N->getValueType(0).isVector())
11650b57cec5SDimitry Andric         break;
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric       unsigned NewOpc;
11680b57cec5SDimitry Andric       switch (N->getOpcode()) {
11690b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
11700b57cec5SDimitry Andric       case ISD::SHL: NewOpc = X86ISD::VSHLV; break;
11710b57cec5SDimitry Andric       case ISD::SRA: NewOpc = X86ISD::VSRAV; break;
11720b57cec5SDimitry Andric       case ISD::SRL: NewOpc = X86ISD::VSRLV; break;
11730b57cec5SDimitry Andric       }
11740b57cec5SDimitry Andric       SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
11750b57cec5SDimitry Andric                                     N->getOperand(0), N->getOperand(1));
11760b57cec5SDimitry Andric       --I;
11770b57cec5SDimitry Andric       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
11780b57cec5SDimitry Andric       ++I;
11795ffd83dbSDimitry Andric       MadeChange = true;
11800b57cec5SDimitry Andric       continue;
11810b57cec5SDimitry Andric     }
11820b57cec5SDimitry Andric     case ISD::ANY_EXTEND:
11830b57cec5SDimitry Andric     case ISD::ANY_EXTEND_VECTOR_INREG: {
11840b57cec5SDimitry Andric       // Replace vector any extend with the zero extend equivalents so we don't
11850b57cec5SDimitry Andric       // need 2 sets of patterns. Ignore vXi1 extensions.
11865ffd83dbSDimitry Andric       if (!N->getValueType(0).isVector())
11870b57cec5SDimitry Andric         break;
11880b57cec5SDimitry Andric 
11895ffd83dbSDimitry Andric       unsigned NewOpc;
11905ffd83dbSDimitry Andric       if (N->getOperand(0).getScalarValueSizeInBits() == 1) {
11915ffd83dbSDimitry Andric         assert(N->getOpcode() == ISD::ANY_EXTEND &&
11925ffd83dbSDimitry Andric                "Unexpected opcode for mask vector!");
11935ffd83dbSDimitry Andric         NewOpc = ISD::SIGN_EXTEND;
11945ffd83dbSDimitry Andric       } else {
11955ffd83dbSDimitry Andric         NewOpc = N->getOpcode() == ISD::ANY_EXTEND
11960b57cec5SDimitry Andric                               ? ISD::ZERO_EXTEND
11970b57cec5SDimitry Andric                               : ISD::ZERO_EXTEND_VECTOR_INREG;
11985ffd83dbSDimitry Andric       }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric       SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
12010b57cec5SDimitry Andric                                     N->getOperand(0));
12020b57cec5SDimitry Andric       --I;
12030b57cec5SDimitry Andric       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
12040b57cec5SDimitry Andric       ++I;
12055ffd83dbSDimitry Andric       MadeChange = true;
12060b57cec5SDimitry Andric       continue;
12070b57cec5SDimitry Andric     }
12080b57cec5SDimitry Andric     case ISD::FCEIL:
1209480093f4SDimitry Andric     case ISD::STRICT_FCEIL:
12100b57cec5SDimitry Andric     case ISD::FFLOOR:
1211480093f4SDimitry Andric     case ISD::STRICT_FFLOOR:
12120b57cec5SDimitry Andric     case ISD::FTRUNC:
1213480093f4SDimitry Andric     case ISD::STRICT_FTRUNC:
1214e8d8bef9SDimitry Andric     case ISD::FROUNDEVEN:
1215e8d8bef9SDimitry Andric     case ISD::STRICT_FROUNDEVEN:
12160b57cec5SDimitry Andric     case ISD::FNEARBYINT:
1217480093f4SDimitry Andric     case ISD::STRICT_FNEARBYINT:
1218480093f4SDimitry Andric     case ISD::FRINT:
1219480093f4SDimitry Andric     case ISD::STRICT_FRINT: {
12200b57cec5SDimitry Andric       // Replace fp rounding with their X86 specific equivalent so we don't
12210b57cec5SDimitry Andric       // need 2 sets of patterns.
12220b57cec5SDimitry Andric       unsigned Imm;
12230b57cec5SDimitry Andric       switch (N->getOpcode()) {
12240b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
1225480093f4SDimitry Andric       case ISD::STRICT_FCEIL:
12260b57cec5SDimitry Andric       case ISD::FCEIL:      Imm = 0xA; break;
1227480093f4SDimitry Andric       case ISD::STRICT_FFLOOR:
12280b57cec5SDimitry Andric       case ISD::FFLOOR:     Imm = 0x9; break;
1229480093f4SDimitry Andric       case ISD::STRICT_FTRUNC:
12300b57cec5SDimitry Andric       case ISD::FTRUNC:     Imm = 0xB; break;
1231e8d8bef9SDimitry Andric       case ISD::STRICT_FROUNDEVEN:
1232e8d8bef9SDimitry Andric       case ISD::FROUNDEVEN: Imm = 0x8; break;
1233480093f4SDimitry Andric       case ISD::STRICT_FNEARBYINT:
12340b57cec5SDimitry Andric       case ISD::FNEARBYINT: Imm = 0xC; break;
1235480093f4SDimitry Andric       case ISD::STRICT_FRINT:
12360b57cec5SDimitry Andric       case ISD::FRINT:      Imm = 0x4; break;
12370b57cec5SDimitry Andric       }
12380b57cec5SDimitry Andric       SDLoc dl(N);
1239480093f4SDimitry Andric       bool IsStrict = N->isStrictFPOpcode();
1240480093f4SDimitry Andric       SDValue Res;
1241480093f4SDimitry Andric       if (IsStrict)
1242480093f4SDimitry Andric         Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl,
1243480093f4SDimitry Andric                               {N->getValueType(0), MVT::Other},
1244480093f4SDimitry Andric                               {N->getOperand(0), N->getOperand(1),
1245e8d8bef9SDimitry Andric                                CurDAG->getTargetConstant(Imm, dl, MVT::i32)});
1246480093f4SDimitry Andric       else
1247480093f4SDimitry Andric         Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0),
1248480093f4SDimitry Andric                               N->getOperand(0),
1249e8d8bef9SDimitry Andric                               CurDAG->getTargetConstant(Imm, dl, MVT::i32));
12500b57cec5SDimitry Andric       --I;
1251480093f4SDimitry Andric       CurDAG->ReplaceAllUsesWith(N, Res.getNode());
12520b57cec5SDimitry Andric       ++I;
12535ffd83dbSDimitry Andric       MadeChange = true;
12540b57cec5SDimitry Andric       continue;
12550b57cec5SDimitry Andric     }
12560b57cec5SDimitry Andric     case X86ISD::FANDN:
12570b57cec5SDimitry Andric     case X86ISD::FAND:
12580b57cec5SDimitry Andric     case X86ISD::FOR:
12590b57cec5SDimitry Andric     case X86ISD::FXOR: {
12600b57cec5SDimitry Andric       // Widen scalar fp logic ops to vector to reduce isel patterns.
12610b57cec5SDimitry Andric       // FIXME: Can we do this during lowering/combine.
12620b57cec5SDimitry Andric       MVT VT = N->getSimpleValueType(0);
12630b57cec5SDimitry Andric       if (VT.isVector() || VT == MVT::f128)
12640b57cec5SDimitry Andric         break;
12650b57cec5SDimitry Andric 
1266349cc55cSDimitry Andric       MVT VecVT = VT == MVT::f64   ? MVT::v2f64
1267349cc55cSDimitry Andric                   : VT == MVT::f32 ? MVT::v4f32
1268349cc55cSDimitry Andric                                    : MVT::v8f16;
1269349cc55cSDimitry Andric 
12700b57cec5SDimitry Andric       SDLoc dl(N);
12710b57cec5SDimitry Andric       SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
12720b57cec5SDimitry Andric                                     N->getOperand(0));
12730b57cec5SDimitry Andric       SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
12740b57cec5SDimitry Andric                                     N->getOperand(1));
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric       SDValue Res;
12770b57cec5SDimitry Andric       if (Subtarget->hasSSE2()) {
12780b57cec5SDimitry Andric         EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger();
12790b57cec5SDimitry Andric         Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0);
12800b57cec5SDimitry Andric         Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1);
12810b57cec5SDimitry Andric         unsigned Opc;
12820b57cec5SDimitry Andric         switch (N->getOpcode()) {
12830b57cec5SDimitry Andric         default: llvm_unreachable("Unexpected opcode!");
12840b57cec5SDimitry Andric         case X86ISD::FANDN: Opc = X86ISD::ANDNP; break;
12850b57cec5SDimitry Andric         case X86ISD::FAND:  Opc = ISD::AND;      break;
12860b57cec5SDimitry Andric         case X86ISD::FOR:   Opc = ISD::OR;       break;
12870b57cec5SDimitry Andric         case X86ISD::FXOR:  Opc = ISD::XOR;      break;
12880b57cec5SDimitry Andric         }
12890b57cec5SDimitry Andric         Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1);
12900b57cec5SDimitry Andric         Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res);
12910b57cec5SDimitry Andric       } else {
12920b57cec5SDimitry Andric         Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1);
12930b57cec5SDimitry Andric       }
12940b57cec5SDimitry Andric       Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res,
12950b57cec5SDimitry Andric                             CurDAG->getIntPtrConstant(0, dl));
12960b57cec5SDimitry Andric       --I;
12970b57cec5SDimitry Andric       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
12980b57cec5SDimitry Andric       ++I;
12995ffd83dbSDimitry Andric       MadeChange = true;
13000b57cec5SDimitry Andric       continue;
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric     }
13030b57cec5SDimitry Andric 
13045f757f3fSDimitry Andric     if (OptLevel != CodeGenOptLevel::None &&
13050b57cec5SDimitry Andric         // Only do this when the target can fold the load into the call or
13060b57cec5SDimitry Andric         // jmp.
13070946e70aSDimitry Andric         !Subtarget->useIndirectThunkCalls() &&
13080b57cec5SDimitry Andric         ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
13090b57cec5SDimitry Andric          (N->getOpcode() == X86ISD::TC_RETURN &&
13100b57cec5SDimitry Andric           (Subtarget->is64Bit() ||
13110b57cec5SDimitry Andric            !getTargetMachine().isPositionIndependent())))) {
13120b57cec5SDimitry Andric       /// Also try moving call address load from outside callseq_start to just
13130b57cec5SDimitry Andric       /// before the call to allow it to be folded.
13140b57cec5SDimitry Andric       ///
13150b57cec5SDimitry Andric       ///     [Load chain]
13160b57cec5SDimitry Andric       ///         ^
13170b57cec5SDimitry Andric       ///         |
13180b57cec5SDimitry Andric       ///       [Load]
13190b57cec5SDimitry Andric       ///       ^    ^
13200b57cec5SDimitry Andric       ///       |    |
13210b57cec5SDimitry Andric       ///      /      \--
13220b57cec5SDimitry Andric       ///     /          |
13230b57cec5SDimitry Andric       ///[CALLSEQ_START] |
13240b57cec5SDimitry Andric       ///     ^          |
13250b57cec5SDimitry Andric       ///     |          |
13260b57cec5SDimitry Andric       /// [LOAD/C2Reg]   |
13270b57cec5SDimitry Andric       ///     |          |
13280b57cec5SDimitry Andric       ///      \        /
13290b57cec5SDimitry Andric       ///       \      /
13300b57cec5SDimitry Andric       ///       [CALL]
13310b57cec5SDimitry Andric       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
13320b57cec5SDimitry Andric       SDValue Chain = N->getOperand(0);
13330b57cec5SDimitry Andric       SDValue Load  = N->getOperand(1);
13340b57cec5SDimitry Andric       if (!isCalleeLoad(Load, Chain, HasCallSeq))
13350b57cec5SDimitry Andric         continue;
13360b57cec5SDimitry Andric       moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
13370b57cec5SDimitry Andric       ++NumLoadMoved;
13385ffd83dbSDimitry Andric       MadeChange = true;
13390b57cec5SDimitry Andric       continue;
13400b57cec5SDimitry Andric     }
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric     // Lower fpround and fpextend nodes that target the FP stack to be store and
13430b57cec5SDimitry Andric     // load to the stack.  This is a gross hack.  We would like to simply mark
13440b57cec5SDimitry Andric     // these as being illegal, but when we do that, legalize produces these when
13450b57cec5SDimitry Andric     // it expands calls, then expands these in the same legalize pass.  We would
13460b57cec5SDimitry Andric     // like dag combine to be able to hack on these between the call expansion
13470b57cec5SDimitry Andric     // and the node legalization.  As such this pass basically does "really
13480b57cec5SDimitry Andric     // late" legalization of these inline with the X86 isel pass.
13490b57cec5SDimitry Andric     // FIXME: This should only happen when not compiled with -O0.
13500b57cec5SDimitry Andric     switch (N->getOpcode()) {
13510b57cec5SDimitry Andric     default: continue;
13520b57cec5SDimitry Andric     case ISD::FP_ROUND:
13530b57cec5SDimitry Andric     case ISD::FP_EXTEND:
13540b57cec5SDimitry Andric     {
13550b57cec5SDimitry Andric       MVT SrcVT = N->getOperand(0).getSimpleValueType();
13560b57cec5SDimitry Andric       MVT DstVT = N->getSimpleValueType(0);
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric       // If any of the sources are vectors, no fp stack involved.
13590b57cec5SDimitry Andric       if (SrcVT.isVector() || DstVT.isVector())
13600b57cec5SDimitry Andric         continue;
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric       // If the source and destination are SSE registers, then this is a legal
13630b57cec5SDimitry Andric       // conversion that should not be lowered.
13640b57cec5SDimitry Andric       const X86TargetLowering *X86Lowering =
13650b57cec5SDimitry Andric           static_cast<const X86TargetLowering *>(TLI);
13660b57cec5SDimitry Andric       bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
13670b57cec5SDimitry Andric       bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
13680b57cec5SDimitry Andric       if (SrcIsSSE && DstIsSSE)
13690b57cec5SDimitry Andric         continue;
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric       if (!SrcIsSSE && !DstIsSSE) {
13720b57cec5SDimitry Andric         // If this is an FPStack extension, it is a noop.
13730b57cec5SDimitry Andric         if (N->getOpcode() == ISD::FP_EXTEND)
13740b57cec5SDimitry Andric           continue;
13750b57cec5SDimitry Andric         // If this is a value-preserving FPStack truncation, it is a noop.
13760b57cec5SDimitry Andric         if (N->getConstantOperandVal(1))
13770b57cec5SDimitry Andric           continue;
13780b57cec5SDimitry Andric       }
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric       // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
13810b57cec5SDimitry Andric       // FPStack has extload and truncstore.  SSE can fold direct loads into other
13820b57cec5SDimitry Andric       // operations.  Based on this, decide what we want to do.
1383480093f4SDimitry Andric       MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT;
13840b57cec5SDimitry Andric       SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
13855ffd83dbSDimitry Andric       int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
13865ffd83dbSDimitry Andric       MachinePointerInfo MPI =
13875ffd83dbSDimitry Andric           MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
13880b57cec5SDimitry Andric       SDLoc dl(N);
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric       // FIXME: optimize the case where the src/dest is a load or store?
13910b57cec5SDimitry Andric 
13925ffd83dbSDimitry Andric       SDValue Store = CurDAG->getTruncStore(
13935ffd83dbSDimitry Andric           CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT);
13945ffd83dbSDimitry Andric       SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store,
13955ffd83dbSDimitry Andric                                           MemTmp, MPI, MemVT);
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric       // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
13980b57cec5SDimitry Andric       // extload we created.  This will cause general havok on the dag because
13990b57cec5SDimitry Andric       // anything below the conversion could be folded into other existing nodes.
14000b57cec5SDimitry Andric       // To avoid invalidating 'I', back it up to the convert node.
14010b57cec5SDimitry Andric       --I;
14020b57cec5SDimitry Andric       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
14030b57cec5SDimitry Andric       break;
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric     //The sequence of events for lowering STRICT_FP versions of these nodes requires
14070b57cec5SDimitry Andric     //dealing with the chain differently, as there is already a preexisting chain.
14080b57cec5SDimitry Andric     case ISD::STRICT_FP_ROUND:
14090b57cec5SDimitry Andric     case ISD::STRICT_FP_EXTEND:
14100b57cec5SDimitry Andric     {
14110b57cec5SDimitry Andric       MVT SrcVT = N->getOperand(1).getSimpleValueType();
14120b57cec5SDimitry Andric       MVT DstVT = N->getSimpleValueType(0);
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric       // If any of the sources are vectors, no fp stack involved.
14150b57cec5SDimitry Andric       if (SrcVT.isVector() || DstVT.isVector())
14160b57cec5SDimitry Andric         continue;
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric       // If the source and destination are SSE registers, then this is a legal
14190b57cec5SDimitry Andric       // conversion that should not be lowered.
14200b57cec5SDimitry Andric       const X86TargetLowering *X86Lowering =
14210b57cec5SDimitry Andric           static_cast<const X86TargetLowering *>(TLI);
14220b57cec5SDimitry Andric       bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
14230b57cec5SDimitry Andric       bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
14240b57cec5SDimitry Andric       if (SrcIsSSE && DstIsSSE)
14250b57cec5SDimitry Andric         continue;
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric       if (!SrcIsSSE && !DstIsSSE) {
14280b57cec5SDimitry Andric         // If this is an FPStack extension, it is a noop.
14290b57cec5SDimitry Andric         if (N->getOpcode() == ISD::STRICT_FP_EXTEND)
14300b57cec5SDimitry Andric           continue;
14310b57cec5SDimitry Andric         // If this is a value-preserving FPStack truncation, it is a noop.
14320b57cec5SDimitry Andric         if (N->getConstantOperandVal(2))
14330b57cec5SDimitry Andric           continue;
14340b57cec5SDimitry Andric       }
14350b57cec5SDimitry Andric 
14360b57cec5SDimitry Andric       // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
14370b57cec5SDimitry Andric       // FPStack has extload and truncstore.  SSE can fold direct loads into other
14380b57cec5SDimitry Andric       // operations.  Based on this, decide what we want to do.
1439480093f4SDimitry Andric       MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT;
14400b57cec5SDimitry Andric       SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
14415ffd83dbSDimitry Andric       int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
14425ffd83dbSDimitry Andric       MachinePointerInfo MPI =
14435ffd83dbSDimitry Andric           MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
14440b57cec5SDimitry Andric       SDLoc dl(N);
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric       // FIXME: optimize the case where the src/dest is a load or store?
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric       //Since the operation is StrictFP, use the preexisting chain.
1449480093f4SDimitry Andric       SDValue Store, Result;
1450480093f4SDimitry Andric       if (!SrcIsSSE) {
1451480093f4SDimitry Andric         SDVTList VTs = CurDAG->getVTList(MVT::Other);
1452480093f4SDimitry Andric         SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp};
1453480093f4SDimitry Andric         Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT,
1454bdd1243dSDimitry Andric                                             MPI, /*Align*/ std::nullopt,
1455480093f4SDimitry Andric                                             MachineMemOperand::MOStore);
1456480093f4SDimitry Andric         if (N->getFlags().hasNoFPExcept()) {
1457480093f4SDimitry Andric           SDNodeFlags Flags = Store->getFlags();
1458480093f4SDimitry Andric           Flags.setNoFPExcept(true);
1459480093f4SDimitry Andric           Store->setFlags(Flags);
1460480093f4SDimitry Andric         }
1461480093f4SDimitry Andric       } else {
1462480093f4SDimitry Andric         assert(SrcVT == MemVT && "Unexpected VT!");
1463480093f4SDimitry Andric         Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp,
14645ffd83dbSDimitry Andric                                  MPI);
1465480093f4SDimitry Andric       }
1466480093f4SDimitry Andric 
1467480093f4SDimitry Andric       if (!DstIsSSE) {
1468480093f4SDimitry Andric         SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other);
1469480093f4SDimitry Andric         SDValue Ops[] = {Store, MemTmp};
14705ffd83dbSDimitry Andric         Result = CurDAG->getMemIntrinsicNode(
14715ffd83dbSDimitry Andric             X86ISD::FLD, dl, VTs, Ops, MemVT, MPI,
1472bdd1243dSDimitry Andric             /*Align*/ std::nullopt, MachineMemOperand::MOLoad);
1473480093f4SDimitry Andric         if (N->getFlags().hasNoFPExcept()) {
1474480093f4SDimitry Andric           SDNodeFlags Flags = Result->getFlags();
1475480093f4SDimitry Andric           Flags.setNoFPExcept(true);
1476480093f4SDimitry Andric           Result->setFlags(Flags);
1477480093f4SDimitry Andric         }
1478480093f4SDimitry Andric       } else {
1479480093f4SDimitry Andric         assert(DstVT == MemVT && "Unexpected VT!");
14805ffd83dbSDimitry Andric         Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI);
1481480093f4SDimitry Andric       }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric       // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
14840b57cec5SDimitry Andric       // extload we created.  This will cause general havok on the dag because
14850b57cec5SDimitry Andric       // anything below the conversion could be folded into other existing nodes.
14860b57cec5SDimitry Andric       // To avoid invalidating 'I', back it up to the convert node.
14870b57cec5SDimitry Andric       --I;
14880b57cec5SDimitry Andric       CurDAG->ReplaceAllUsesWith(N, Result.getNode());
14890b57cec5SDimitry Andric       break;
14900b57cec5SDimitry Andric     }
14910b57cec5SDimitry Andric     }
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric     // Now that we did that, the node is dead.  Increment the iterator to the
14950b57cec5SDimitry Andric     // next node to process, then delete N.
14960b57cec5SDimitry Andric     ++I;
14975ffd83dbSDimitry Andric     MadeChange = true;
14980b57cec5SDimitry Andric   }
14990b57cec5SDimitry Andric 
15005ffd83dbSDimitry Andric   // Remove any dead nodes that may have been left behind.
15015ffd83dbSDimitry Andric   if (MadeChange)
15020b57cec5SDimitry Andric     CurDAG->RemoveDeadNodes();
15030b57cec5SDimitry Andric }
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric // Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
tryOptimizeRem8Extend(SDNode * N)15060b57cec5SDimitry Andric bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
15070b57cec5SDimitry Andric   unsigned Opc = N->getMachineOpcode();
15080b57cec5SDimitry Andric   if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
15090b57cec5SDimitry Andric       Opc != X86::MOVSX64rr8)
15100b57cec5SDimitry Andric     return false;
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric   SDValue N0 = N->getOperand(0);
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   // We need to be extracting the lower bit of an extend.
15150b57cec5SDimitry Andric   if (!N0.isMachineOpcode() ||
15160b57cec5SDimitry Andric       N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
15170b57cec5SDimitry Andric       N0.getConstantOperandVal(1) != X86::sub_8bit)
15180b57cec5SDimitry Andric     return false;
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric   // We're looking for either a movsx or movzx to match the original opcode.
15210b57cec5SDimitry Andric   unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
15220b57cec5SDimitry Andric                                                 : X86::MOVSX32rr8_NOREX;
15230b57cec5SDimitry Andric   SDValue N00 = N0.getOperand(0);
15240b57cec5SDimitry Andric   if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
15250b57cec5SDimitry Andric     return false;
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric   if (Opc == X86::MOVSX64rr8) {
15280b57cec5SDimitry Andric     // If we had a sign extend from 8 to 64 bits. We still need to go from 32
15290b57cec5SDimitry Andric     // to 64.
15300b57cec5SDimitry Andric     MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
15310b57cec5SDimitry Andric                                                    MVT::i64, N00);
15320b57cec5SDimitry Andric     ReplaceUses(N, Extend);
15330b57cec5SDimitry Andric   } else {
15340b57cec5SDimitry Andric     // Ok we can drop this extend and just use the original extend.
15350b57cec5SDimitry Andric     ReplaceUses(N, N00.getNode());
15360b57cec5SDimitry Andric   }
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric   return true;
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric 
PostprocessISelDAG()15410b57cec5SDimitry Andric void X86DAGToDAGISel::PostprocessISelDAG() {
15420b57cec5SDimitry Andric   // Skip peepholes at -O0.
15435f757f3fSDimitry Andric   if (TM.getOptLevel() == CodeGenOptLevel::None)
15440b57cec5SDimitry Andric     return;
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric   bool MadeChange = false;
15490b57cec5SDimitry Andric   while (Position != CurDAG->allnodes_begin()) {
15500b57cec5SDimitry Andric     SDNode *N = &*--Position;
15510b57cec5SDimitry Andric     // Skip dead nodes and any non-machine opcodes.
15520b57cec5SDimitry Andric     if (N->use_empty() || !N->isMachineOpcode())
15530b57cec5SDimitry Andric       continue;
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric     if (tryOptimizeRem8Extend(N)) {
15560b57cec5SDimitry Andric       MadeChange = true;
15570b57cec5SDimitry Andric       continue;
15580b57cec5SDimitry Andric     }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric     unsigned Opc = N->getMachineOpcode();
1561*0fca6ea1SDimitry Andric     switch (Opc) {
1562*0fca6ea1SDimitry Andric     default:
1563*0fca6ea1SDimitry Andric       continue;
1564*0fca6ea1SDimitry Andric     // ANDrr/rm + TESTrr+ -> TESTrr/TESTmr
1565*0fca6ea1SDimitry Andric     case X86::TEST8rr:
1566*0fca6ea1SDimitry Andric     case X86::TEST16rr:
1567*0fca6ea1SDimitry Andric     case X86::TEST32rr:
1568*0fca6ea1SDimitry Andric     case X86::TEST64rr:
1569*0fca6ea1SDimitry Andric     // ANDrr/rm + CTESTrr -> CTESTrr/CTESTmr
1570*0fca6ea1SDimitry Andric     case X86::CTEST8rr:
1571*0fca6ea1SDimitry Andric     case X86::CTEST16rr:
1572*0fca6ea1SDimitry Andric     case X86::CTEST32rr:
1573*0fca6ea1SDimitry Andric     case X86::CTEST64rr: {
1574*0fca6ea1SDimitry Andric       auto &Op0 = N->getOperand(0);
1575*0fca6ea1SDimitry Andric       if (Op0 != N->getOperand(1) || !Op0->hasNUsesOfValue(2, Op0.getResNo()) ||
1576*0fca6ea1SDimitry Andric           !Op0.isMachineOpcode())
1577*0fca6ea1SDimitry Andric         continue;
15780b57cec5SDimitry Andric       SDValue And = N->getOperand(0);
1579*0fca6ea1SDimitry Andric #define CASE_ND(OP)                                                            \
1580*0fca6ea1SDimitry Andric   case X86::OP:                                                                \
1581*0fca6ea1SDimitry Andric   case X86::OP##_ND:
1582*0fca6ea1SDimitry Andric       switch (And.getMachineOpcode()) {
1583*0fca6ea1SDimitry Andric       default:
1584*0fca6ea1SDimitry Andric         continue;
1585*0fca6ea1SDimitry Andric         CASE_ND(AND8rr)
1586*0fca6ea1SDimitry Andric         CASE_ND(AND16rr)
1587*0fca6ea1SDimitry Andric         CASE_ND(AND32rr)
1588*0fca6ea1SDimitry Andric         CASE_ND(AND64rr) {
1589*0fca6ea1SDimitry Andric           if (And->hasAnyUseOfValue(1))
1590*0fca6ea1SDimitry Andric             continue;
1591*0fca6ea1SDimitry Andric           SmallVector<SDValue> Ops(N->op_values());
1592*0fca6ea1SDimitry Andric           Ops[0] = And.getOperand(0);
1593*0fca6ea1SDimitry Andric           Ops[1] = And.getOperand(1);
1594*0fca6ea1SDimitry Andric           MachineSDNode *Test =
1595*0fca6ea1SDimitry Andric               CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i32, Ops);
15960b57cec5SDimitry Andric           ReplaceUses(N, Test);
15970b57cec5SDimitry Andric           MadeChange = true;
15980b57cec5SDimitry Andric           continue;
15990b57cec5SDimitry Andric         }
1600*0fca6ea1SDimitry Andric         CASE_ND(AND8rm)
1601*0fca6ea1SDimitry Andric         CASE_ND(AND16rm)
1602*0fca6ea1SDimitry Andric         CASE_ND(AND32rm)
1603*0fca6ea1SDimitry Andric         CASE_ND(AND64rm) {
1604*0fca6ea1SDimitry Andric           if (And->hasAnyUseOfValue(1))
1605*0fca6ea1SDimitry Andric             continue;
16060b57cec5SDimitry Andric           unsigned NewOpc;
1607*0fca6ea1SDimitry Andric           bool IsCTESTCC = X86::isCTESTCC(Opc);
1608*0fca6ea1SDimitry Andric #define FROM_TO(A, B)                                                          \
1609*0fca6ea1SDimitry Andric   CASE_ND(A) NewOpc = IsCTESTCC ? X86::C##B : X86::B;                          \
1610*0fca6ea1SDimitry Andric   break;
1611*0fca6ea1SDimitry Andric           switch (And.getMachineOpcode()) {
1612*0fca6ea1SDimitry Andric             FROM_TO(AND8rm, TEST8mr);
1613*0fca6ea1SDimitry Andric             FROM_TO(AND16rm, TEST16mr);
1614*0fca6ea1SDimitry Andric             FROM_TO(AND32rm, TEST32mr);
1615*0fca6ea1SDimitry Andric             FROM_TO(AND64rm, TEST64mr);
16160b57cec5SDimitry Andric           }
1617*0fca6ea1SDimitry Andric #undef FROM_TO
1618*0fca6ea1SDimitry Andric #undef CASE_ND
16190b57cec5SDimitry Andric           // Need to swap the memory and register operand.
1620*0fca6ea1SDimitry Andric           SmallVector<SDValue> Ops = {And.getOperand(1), And.getOperand(2),
1621*0fca6ea1SDimitry Andric                                       And.getOperand(3), And.getOperand(4),
1622*0fca6ea1SDimitry Andric                                       And.getOperand(5), And.getOperand(0)};
1623*0fca6ea1SDimitry Andric           // CC, Cflags.
1624*0fca6ea1SDimitry Andric           if (IsCTESTCC) {
1625*0fca6ea1SDimitry Andric             Ops.push_back(N->getOperand(2));
1626*0fca6ea1SDimitry Andric             Ops.push_back(N->getOperand(3));
1627*0fca6ea1SDimitry Andric           }
1628*0fca6ea1SDimitry Andric           // Chain of memory load
1629*0fca6ea1SDimitry Andric           Ops.push_back(And.getOperand(6));
1630*0fca6ea1SDimitry Andric           // Glue
1631*0fca6ea1SDimitry Andric           if (IsCTESTCC)
1632*0fca6ea1SDimitry Andric             Ops.push_back(N->getOperand(4));
1633*0fca6ea1SDimitry Andric 
1634*0fca6ea1SDimitry Andric           MachineSDNode *Test = CurDAG->getMachineNode(
1635*0fca6ea1SDimitry Andric               NewOpc, SDLoc(N), MVT::i32, MVT::Other, Ops);
16365ffd83dbSDimitry Andric           CurDAG->setNodeMemRefs(
16375ffd83dbSDimitry Andric               Test, cast<MachineSDNode>(And.getNode())->memoperands());
1638bdd1243dSDimitry Andric           ReplaceUses(And.getValue(2), SDValue(Test, 1));
1639bdd1243dSDimitry Andric           ReplaceUses(SDValue(N, 0), SDValue(Test, 0));
16400b57cec5SDimitry Andric           MadeChange = true;
16410b57cec5SDimitry Andric           continue;
16420b57cec5SDimitry Andric         }
16430b57cec5SDimitry Andric       }
1644*0fca6ea1SDimitry Andric     }
16450b57cec5SDimitry Andric     // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
16460b57cec5SDimitry Andric     // used. We're doing this late so we can prefer to fold the AND into masked
16470b57cec5SDimitry Andric     // comparisons. Doing that can be better for the live range of the mask
16480b57cec5SDimitry Andric     // register.
1649*0fca6ea1SDimitry Andric     case X86::KORTESTBrr:
1650*0fca6ea1SDimitry Andric     case X86::KORTESTWrr:
1651*0fca6ea1SDimitry Andric     case X86::KORTESTDrr:
1652*0fca6ea1SDimitry Andric     case X86::KORTESTQrr: {
1653*0fca6ea1SDimitry Andric       SDValue Op0 = N->getOperand(0);
1654*0fca6ea1SDimitry Andric       if (Op0 != N->getOperand(1) || !N->isOnlyUserOf(Op0.getNode()) ||
1655*0fca6ea1SDimitry Andric           !Op0.isMachineOpcode() || !onlyUsesZeroFlag(SDValue(N, 0)))
1656*0fca6ea1SDimitry Andric         continue;
1657*0fca6ea1SDimitry Andric #define CASE(A)                                                                \
1658*0fca6ea1SDimitry Andric   case X86::A:                                                                 \
1659*0fca6ea1SDimitry Andric     break;
1660*0fca6ea1SDimitry Andric       switch (Op0.getMachineOpcode()) {
1661*0fca6ea1SDimitry Andric       default:
1662*0fca6ea1SDimitry Andric         continue;
1663*0fca6ea1SDimitry Andric         CASE(KANDBrr)
1664*0fca6ea1SDimitry Andric         CASE(KANDWrr)
1665*0fca6ea1SDimitry Andric         CASE(KANDDrr)
1666*0fca6ea1SDimitry Andric         CASE(KANDQrr)
1667*0fca6ea1SDimitry Andric       }
1668*0fca6ea1SDimitry Andric       unsigned NewOpc;
1669*0fca6ea1SDimitry Andric #define FROM_TO(A, B)                                                          \
1670*0fca6ea1SDimitry Andric   case X86::A:                                                                 \
1671*0fca6ea1SDimitry Andric     NewOpc = X86::B;                                                           \
1672*0fca6ea1SDimitry Andric     break;
1673*0fca6ea1SDimitry Andric       switch (Opc) {
1674*0fca6ea1SDimitry Andric         FROM_TO(KORTESTBrr, KTESTBrr)
1675*0fca6ea1SDimitry Andric         FROM_TO(KORTESTWrr, KTESTWrr)
1676*0fca6ea1SDimitry Andric         FROM_TO(KORTESTDrr, KTESTDrr)
1677*0fca6ea1SDimitry Andric         FROM_TO(KORTESTQrr, KTESTQrr)
1678*0fca6ea1SDimitry Andric       }
16790b57cec5SDimitry Andric       // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
16800b57cec5SDimitry Andric       // KAND instructions and KTEST use the same ISA feature.
1681*0fca6ea1SDimitry Andric       if (NewOpc == X86::KTESTWrr && !Subtarget->hasDQI())
1682*0fca6ea1SDimitry Andric         continue;
1683*0fca6ea1SDimitry Andric #undef FROM_TO
1684*0fca6ea1SDimitry Andric       MachineSDNode *KTest = CurDAG->getMachineNode(
1685*0fca6ea1SDimitry Andric           NewOpc, SDLoc(N), MVT::i32, Op0.getOperand(0), Op0.getOperand(1));
16860b57cec5SDimitry Andric       ReplaceUses(N, KTest);
16870b57cec5SDimitry Andric       MadeChange = true;
16880b57cec5SDimitry Andric       continue;
16890b57cec5SDimitry Andric     }
16900b57cec5SDimitry Andric     // Attempt to remove vectors moves that were inserted to zero upper bits.
1691*0fca6ea1SDimitry Andric     case TargetOpcode::SUBREG_TO_REG: {
16920b57cec5SDimitry Andric       unsigned SubRegIdx = N->getConstantOperandVal(2);
16930b57cec5SDimitry Andric       if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
16940b57cec5SDimitry Andric         continue;
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric       SDValue Move = N->getOperand(1);
16970b57cec5SDimitry Andric       if (!Move.isMachineOpcode())
16980b57cec5SDimitry Andric         continue;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric       // Make sure its one of the move opcodes we recognize.
17010b57cec5SDimitry Andric       switch (Move.getMachineOpcode()) {
17020b57cec5SDimitry Andric       default:
17030b57cec5SDimitry Andric         continue;
1704*0fca6ea1SDimitry Andric         CASE(VMOVAPDrr)       CASE(VMOVUPDrr)
1705*0fca6ea1SDimitry Andric         CASE(VMOVAPSrr)       CASE(VMOVUPSrr)
1706*0fca6ea1SDimitry Andric         CASE(VMOVDQArr)       CASE(VMOVDQUrr)
1707*0fca6ea1SDimitry Andric         CASE(VMOVAPDYrr)      CASE(VMOVUPDYrr)
1708*0fca6ea1SDimitry Andric         CASE(VMOVAPSYrr)      CASE(VMOVUPSYrr)
1709*0fca6ea1SDimitry Andric         CASE(VMOVDQAYrr)      CASE(VMOVDQUYrr)
1710*0fca6ea1SDimitry Andric         CASE(VMOVAPDZ128rr)   CASE(VMOVUPDZ128rr)
1711*0fca6ea1SDimitry Andric         CASE(VMOVAPSZ128rr)   CASE(VMOVUPSZ128rr)
1712*0fca6ea1SDimitry Andric         CASE(VMOVDQA32Z128rr) CASE(VMOVDQU32Z128rr)
1713*0fca6ea1SDimitry Andric         CASE(VMOVDQA64Z128rr) CASE(VMOVDQU64Z128rr)
1714*0fca6ea1SDimitry Andric         CASE(VMOVAPDZ256rr)   CASE(VMOVUPDZ256rr)
1715*0fca6ea1SDimitry Andric         CASE(VMOVAPSZ256rr)   CASE(VMOVUPSZ256rr)
1716*0fca6ea1SDimitry Andric         CASE(VMOVDQA32Z256rr) CASE(VMOVDQU32Z256rr)
1717*0fca6ea1SDimitry Andric         CASE(VMOVDQA64Z256rr) CASE(VMOVDQU64Z256rr)
17180b57cec5SDimitry Andric       }
1719*0fca6ea1SDimitry Andric #undef CASE
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric     SDValue In = Move.getOperand(0);
17220b57cec5SDimitry Andric     if (!In.isMachineOpcode() ||
17230b57cec5SDimitry Andric         In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
17240b57cec5SDimitry Andric       continue;
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric     // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
17270b57cec5SDimitry Andric     // the SHA instructions which use a legacy encoding.
17280b57cec5SDimitry Andric     uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
17290b57cec5SDimitry Andric     if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
17300b57cec5SDimitry Andric         (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
17310b57cec5SDimitry Andric         (TSFlags & X86II::EncodingMask) != X86II::XOP)
17320b57cec5SDimitry Andric       continue;
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric     // Producing instruction is another vector instruction. We can drop the
17350b57cec5SDimitry Andric     // move.
17360b57cec5SDimitry Andric     CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
17370b57cec5SDimitry Andric     MadeChange = true;
17380b57cec5SDimitry Andric     }
1739*0fca6ea1SDimitry Andric     }
1740*0fca6ea1SDimitry Andric   }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric   if (MadeChange)
17430b57cec5SDimitry Andric     CurDAG->RemoveDeadNodes();
17440b57cec5SDimitry Andric }
17450b57cec5SDimitry Andric 
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric /// Emit any code that needs to be executed only in the main function.
emitSpecialCodeForMain()17480b57cec5SDimitry Andric void X86DAGToDAGISel::emitSpecialCodeForMain() {
17490b57cec5SDimitry Andric   if (Subtarget->isTargetCygMing()) {
17500b57cec5SDimitry Andric     TargetLowering::ArgListTy Args;
17510b57cec5SDimitry Andric     auto &DL = CurDAG->getDataLayout();
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric     TargetLowering::CallLoweringInfo CLI(*CurDAG);
17540b57cec5SDimitry Andric     CLI.setChain(CurDAG->getRoot())
17550b57cec5SDimitry Andric         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
17560b57cec5SDimitry Andric                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
17570b57cec5SDimitry Andric                    std::move(Args));
17580b57cec5SDimitry Andric     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
17590b57cec5SDimitry Andric     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
17600b57cec5SDimitry Andric     CurDAG->setRoot(Result.second);
17610b57cec5SDimitry Andric   }
17620b57cec5SDimitry Andric }
17630b57cec5SDimitry Andric 
emitFunctionEntryCode()17645ffd83dbSDimitry Andric void X86DAGToDAGISel::emitFunctionEntryCode() {
17650b57cec5SDimitry Andric   // If this is main, emit special code for main.
17660b57cec5SDimitry Andric   const Function &F = MF->getFunction();
17670b57cec5SDimitry Andric   if (F.hasExternalLinkage() && F.getName() == "main")
17680b57cec5SDimitry Andric     emitSpecialCodeForMain();
17690b57cec5SDimitry Andric }
17700b57cec5SDimitry Andric 
isDispSafeForFrameIndex(int64_t Val)17710b57cec5SDimitry Andric static bool isDispSafeForFrameIndex(int64_t Val) {
17720b57cec5SDimitry Andric   // On 64-bit platforms, we can run into an issue where a frame index
17730b57cec5SDimitry Andric   // includes a displacement that, when added to the explicit displacement,
17740b57cec5SDimitry Andric   // will overflow the displacement field. Assuming that the frame index
17750b57cec5SDimitry Andric   // displacement fits into a 31-bit integer  (which is only slightly more
17760b57cec5SDimitry Andric   // aggressive than the current fundamental assumption that it fits into
17770b57cec5SDimitry Andric   // a 32-bit integer), a 31-bit disp should always be safe.
17780b57cec5SDimitry Andric   return isInt<31>(Val);
17790b57cec5SDimitry Andric }
17800b57cec5SDimitry Andric 
foldOffsetIntoAddress(uint64_t Offset,X86ISelAddressMode & AM)17810b57cec5SDimitry Andric bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
17820b57cec5SDimitry Andric                                             X86ISelAddressMode &AM) {
17835ffd83dbSDimitry Andric   // We may have already matched a displacement and the caller just added the
17845ffd83dbSDimitry Andric   // symbolic displacement. So we still need to do the checks even if Offset
17855ffd83dbSDimitry Andric   // is zero.
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   int64_t Val = AM.Disp + Offset;
17885ffd83dbSDimitry Andric 
17895ffd83dbSDimitry Andric   // Cannot combine ExternalSymbol displacements with integer offsets.
17905ffd83dbSDimitry Andric   if (Val != 0 && (AM.ES || AM.MCSym))
17915ffd83dbSDimitry Andric     return true;
17925ffd83dbSDimitry Andric 
17930b57cec5SDimitry Andric   CodeModel::Model M = TM.getCodeModel();
17940b57cec5SDimitry Andric   if (Subtarget->is64Bit()) {
17955ffd83dbSDimitry Andric     if (Val != 0 &&
17965ffd83dbSDimitry Andric         !X86::isOffsetSuitableForCodeModel(Val, M,
17970b57cec5SDimitry Andric                                            AM.hasSymbolicDisplacement()))
17980b57cec5SDimitry Andric       return true;
17990b57cec5SDimitry Andric     // In addition to the checks required for a register base, check that
18000b57cec5SDimitry Andric     // we do not try to use an unsafe Disp with a frame index.
18010b57cec5SDimitry Andric     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
18020b57cec5SDimitry Andric         !isDispSafeForFrameIndex(Val))
18030b57cec5SDimitry Andric       return true;
18045f757f3fSDimitry Andric     // In ILP32 (x32) mode, pointers are 32 bits and need to be zero-extended to
18055f757f3fSDimitry Andric     // 64 bits. Instructions with 32-bit register addresses perform this zero
18065f757f3fSDimitry Andric     // extension for us and we can safely ignore the high bits of Offset.
18075f757f3fSDimitry Andric     // Instructions with only a 32-bit immediate address do not, though: they
18085f757f3fSDimitry Andric     // sign extend instead. This means only address the low 2GB of address space
18095f757f3fSDimitry Andric     // is directly addressable, we need indirect addressing for the high 2GB of
18105f757f3fSDimitry Andric     // address space.
18115f757f3fSDimitry Andric     // TODO: Some of the earlier checks may be relaxed for ILP32 mode as the
18125f757f3fSDimitry Andric     // implicit zero extension of instructions would cover up any problem.
18135f757f3fSDimitry Andric     // However, we have asserts elsewhere that get triggered if we do, so keep
18145f757f3fSDimitry Andric     // the checks for now.
18155f757f3fSDimitry Andric     // TODO: We would actually be able to accept these, as well as the same
18165f757f3fSDimitry Andric     // addresses in LP64 mode, by adding the EIZ pseudo-register as an operand
18175f757f3fSDimitry Andric     // to get an address size override to be emitted. However, this
18185f757f3fSDimitry Andric     // pseudo-register is not part of any register class and therefore causes
18195f757f3fSDimitry Andric     // MIR verification to fail.
18205f757f3fSDimitry Andric     if (Subtarget->isTarget64BitILP32() && !isUInt<31>(Val) &&
18215f757f3fSDimitry Andric         !AM.hasBaseOrIndexReg())
18225f757f3fSDimitry Andric       return true;
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric   AM.Disp = Val;
18250b57cec5SDimitry Andric   return false;
18260b57cec5SDimitry Andric }
18270b57cec5SDimitry Andric 
matchLoadInAddress(LoadSDNode * N,X86ISelAddressMode & AM,bool AllowSegmentRegForX32)1828e8d8bef9SDimitry Andric bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,
1829e8d8bef9SDimitry Andric                                          bool AllowSegmentRegForX32) {
18300b57cec5SDimitry Andric   SDValue Address = N->getOperand(1);
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric   // load gs:0 -> GS segment register.
18330b57cec5SDimitry Andric   // load fs:0 -> FS segment register.
18340b57cec5SDimitry Andric   //
1835e8d8bef9SDimitry Andric   // This optimization is generally valid because the GNU TLS model defines that
1836e8d8bef9SDimitry Andric   // gs:0 (or fs:0 on X86-64) contains its own address. However, for X86-64 mode
1837e8d8bef9SDimitry Andric   // with 32-bit registers, as we get in ILP32 mode, those registers are first
1838e8d8bef9SDimitry Andric   // zero-extended to 64 bits and then added it to the base address, which gives
1839e8d8bef9SDimitry Andric   // unwanted results when the register holds a negative value.
18400b57cec5SDimitry Andric   // For more information see http://people.redhat.com/drepper/tls.pdf
184106c3fb27SDimitry Andric   if (isNullConstant(Address) && AM.Segment.getNode() == nullptr &&
18420b57cec5SDimitry Andric       !IndirectTlsSegRefs &&
18430b57cec5SDimitry Andric       (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1844e8d8bef9SDimitry Andric        Subtarget->isTargetFuchsia())) {
1845e8d8bef9SDimitry Andric     if (Subtarget->isTarget64BitILP32() && !AllowSegmentRegForX32)
1846e8d8bef9SDimitry Andric       return true;
18470b57cec5SDimitry Andric     switch (N->getPointerInfo().getAddrSpace()) {
18485ffd83dbSDimitry Andric     case X86AS::GS:
18490b57cec5SDimitry Andric       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
18500b57cec5SDimitry Andric       return false;
18515ffd83dbSDimitry Andric     case X86AS::FS:
18520b57cec5SDimitry Andric       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
18530b57cec5SDimitry Andric       return false;
18545ffd83dbSDimitry Andric       // Address space X86AS::SS is not handled here, because it is not used to
18550b57cec5SDimitry Andric       // address TLS areas.
18560b57cec5SDimitry Andric     }
1857e8d8bef9SDimitry Andric   }
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric   return true;
18600b57cec5SDimitry Andric }
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
18630b57cec5SDimitry Andric /// mode. These wrap things that will resolve down into a symbol reference.
18640b57cec5SDimitry Andric /// If no match is possible, this returns true, otherwise it returns false.
matchWrapper(SDValue N,X86ISelAddressMode & AM)18650b57cec5SDimitry Andric bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
18660b57cec5SDimitry Andric   // If the addressing mode already has a symbol as the displacement, we can
18670b57cec5SDimitry Andric   // never match another symbol.
18680b57cec5SDimitry Andric   if (AM.hasSymbolicDisplacement())
18690b57cec5SDimitry Andric     return true;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   bool IsRIPRelTLS = false;
18720b57cec5SDimitry Andric   bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
18730b57cec5SDimitry Andric   if (IsRIPRel) {
18740b57cec5SDimitry Andric     SDValue Val = N.getOperand(0);
18750b57cec5SDimitry Andric     if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
18760b57cec5SDimitry Andric       IsRIPRelTLS = true;
18770b57cec5SDimitry Andric   }
18780b57cec5SDimitry Andric 
18790b57cec5SDimitry Andric   // We can't use an addressing mode in the 64-bit large code model.
18800b57cec5SDimitry Andric   // Global TLS addressing is an exception. In the medium code model,
18810b57cec5SDimitry Andric   // we use can use a mode when RIP wrappers are present.
18820b57cec5SDimitry Andric   // That signifies access to globals that are known to be "near",
18830b57cec5SDimitry Andric   // such as the GOT itself.
18840b57cec5SDimitry Andric   CodeModel::Model M = TM.getCodeModel();
1885cb14a3feSDimitry Andric   if (Subtarget->is64Bit() && M == CodeModel::Large && !IsRIPRelTLS)
18860b57cec5SDimitry Andric     return true;
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric   // Base and index reg must be 0 in order to use %rip as base.
18890b57cec5SDimitry Andric   if (IsRIPRel && AM.hasBaseOrIndexReg())
18900b57cec5SDimitry Andric     return true;
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric   // Make a local copy in case we can't do this fold.
18930b57cec5SDimitry Andric   X86ISelAddressMode Backup = AM;
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric   int64_t Offset = 0;
18960b57cec5SDimitry Andric   SDValue N0 = N.getOperand(0);
1897bdd1243dSDimitry Andric   if (auto *G = dyn_cast<GlobalAddressSDNode>(N0)) {
18980b57cec5SDimitry Andric     AM.GV = G->getGlobal();
18990b57cec5SDimitry Andric     AM.SymbolFlags = G->getTargetFlags();
19000b57cec5SDimitry Andric     Offset = G->getOffset();
1901bdd1243dSDimitry Andric   } else if (auto *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
19020b57cec5SDimitry Andric     AM.CP = CP->getConstVal();
19035ffd83dbSDimitry Andric     AM.Alignment = CP->getAlign();
19040b57cec5SDimitry Andric     AM.SymbolFlags = CP->getTargetFlags();
19050b57cec5SDimitry Andric     Offset = CP->getOffset();
1906bdd1243dSDimitry Andric   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
19070b57cec5SDimitry Andric     AM.ES = S->getSymbol();
19080b57cec5SDimitry Andric     AM.SymbolFlags = S->getTargetFlags();
19090b57cec5SDimitry Andric   } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
19100b57cec5SDimitry Andric     AM.MCSym = S->getMCSymbol();
1911bdd1243dSDimitry Andric   } else if (auto *J = dyn_cast<JumpTableSDNode>(N0)) {
19120b57cec5SDimitry Andric     AM.JT = J->getIndex();
19130b57cec5SDimitry Andric     AM.SymbolFlags = J->getTargetFlags();
1914bdd1243dSDimitry Andric   } else if (auto *BA = dyn_cast<BlockAddressSDNode>(N0)) {
19150b57cec5SDimitry Andric     AM.BlockAddr = BA->getBlockAddress();
19160b57cec5SDimitry Andric     AM.SymbolFlags = BA->getTargetFlags();
19170b57cec5SDimitry Andric     Offset = BA->getOffset();
19180b57cec5SDimitry Andric   } else
19190b57cec5SDimitry Andric     llvm_unreachable("Unhandled symbol reference node.");
19200b57cec5SDimitry Andric 
1921cb14a3feSDimitry Andric   // Can't use an addressing mode with large globals.
1922cb14a3feSDimitry Andric   if (Subtarget->is64Bit() && !IsRIPRel && AM.GV &&
1923cb14a3feSDimitry Andric       TM.isLargeGlobalValue(AM.GV)) {
1924cb14a3feSDimitry Andric     AM = Backup;
1925cb14a3feSDimitry Andric     return true;
1926cb14a3feSDimitry Andric   }
1927cb14a3feSDimitry Andric 
19280b57cec5SDimitry Andric   if (foldOffsetIntoAddress(Offset, AM)) {
19290b57cec5SDimitry Andric     AM = Backup;
19300b57cec5SDimitry Andric     return true;
19310b57cec5SDimitry Andric   }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   if (IsRIPRel)
19340b57cec5SDimitry Andric     AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric   // Commit the changes now that we know this fold is safe.
19370b57cec5SDimitry Andric   return false;
19380b57cec5SDimitry Andric }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric /// Add the specified node to the specified addressing mode, returning true if
19410b57cec5SDimitry Andric /// it cannot be done. This just pattern matches for the addressing mode.
matchAddress(SDValue N,X86ISelAddressMode & AM)19420b57cec5SDimitry Andric bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
19430b57cec5SDimitry Andric   if (matchAddressRecursively(N, AM, 0))
19440b57cec5SDimitry Andric     return true;
19450b57cec5SDimitry Andric 
1946e8d8bef9SDimitry Andric   // Post-processing: Make a second attempt to fold a load, if we now know
1947e8d8bef9SDimitry Andric   // that there will not be any other register. This is only performed for
1948e8d8bef9SDimitry Andric   // 64-bit ILP32 mode since 32-bit mode and 64-bit LP64 mode will have folded
1949e8d8bef9SDimitry Andric   // any foldable load the first time.
1950e8d8bef9SDimitry Andric   if (Subtarget->isTarget64BitILP32() &&
1951e8d8bef9SDimitry Andric       AM.BaseType == X86ISelAddressMode::RegBase &&
1952e8d8bef9SDimitry Andric       AM.Base_Reg.getNode() != nullptr && AM.IndexReg.getNode() == nullptr) {
1953e8d8bef9SDimitry Andric     SDValue Save_Base_Reg = AM.Base_Reg;
1954e8d8bef9SDimitry Andric     if (auto *LoadN = dyn_cast<LoadSDNode>(Save_Base_Reg)) {
1955e8d8bef9SDimitry Andric       AM.Base_Reg = SDValue();
1956e8d8bef9SDimitry Andric       if (matchLoadInAddress(LoadN, AM, /*AllowSegmentRegForX32=*/true))
1957e8d8bef9SDimitry Andric         AM.Base_Reg = Save_Base_Reg;
1958e8d8bef9SDimitry Andric     }
1959e8d8bef9SDimitry Andric   }
1960e8d8bef9SDimitry Andric 
19610b57cec5SDimitry Andric   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
19620b57cec5SDimitry Andric   // a smaller encoding and avoids a scaled-index.
19630b57cec5SDimitry Andric   if (AM.Scale == 2 &&
19640b57cec5SDimitry Andric       AM.BaseType == X86ISelAddressMode::RegBase &&
19650b57cec5SDimitry Andric       AM.Base_Reg.getNode() == nullptr) {
19660b57cec5SDimitry Andric     AM.Base_Reg = AM.IndexReg;
19670b57cec5SDimitry Andric     AM.Scale = 1;
19680b57cec5SDimitry Andric   }
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
19710b57cec5SDimitry Andric   // because it has a smaller encoding.
1972cb14a3feSDimitry Andric   if (TM.getCodeModel() != CodeModel::Large &&
1973cb14a3feSDimitry Andric       (!AM.GV || !TM.isLargeGlobalValue(AM.GV)) && Subtarget->is64Bit() &&
1974cb14a3feSDimitry Andric       AM.Scale == 1 && AM.BaseType == X86ISelAddressMode::RegBase &&
1975cb14a3feSDimitry Andric       AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr &&
1976cb14a3feSDimitry Andric       AM.SymbolFlags == X86II::MO_NO_FLAG && AM.hasSymbolicDisplacement()) {
19770b57cec5SDimitry Andric     AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
19780b57cec5SDimitry Andric   }
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   return false;
19810b57cec5SDimitry Andric }
19820b57cec5SDimitry Andric 
matchAdd(SDValue & N,X86ISelAddressMode & AM,unsigned Depth)19830b57cec5SDimitry Andric bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,
19840b57cec5SDimitry Andric                                unsigned Depth) {
19850b57cec5SDimitry Andric   // Add an artificial use to this node so that we can keep track of
19860b57cec5SDimitry Andric   // it if it gets CSE'd with a different node.
19870b57cec5SDimitry Andric   HandleSDNode Handle(N);
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric   X86ISelAddressMode Backup = AM;
19900b57cec5SDimitry Andric   if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
19910b57cec5SDimitry Andric       !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
19920b57cec5SDimitry Andric     return false;
19930b57cec5SDimitry Andric   AM = Backup;
19940b57cec5SDimitry Andric 
19955ffd83dbSDimitry Andric   // Try again after commutating the operands.
19965ffd83dbSDimitry Andric   if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM,
19975ffd83dbSDimitry Andric                                Depth + 1) &&
19980b57cec5SDimitry Andric       !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1))
19990b57cec5SDimitry Andric     return false;
20000b57cec5SDimitry Andric   AM = Backup;
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   // If we couldn't fold both operands into the address at the same time,
20030b57cec5SDimitry Andric   // see if we can just put each operand into a register and fold at least
20040b57cec5SDimitry Andric   // the add.
20050b57cec5SDimitry Andric   if (AM.BaseType == X86ISelAddressMode::RegBase &&
20060b57cec5SDimitry Andric       !AM.Base_Reg.getNode() &&
20070b57cec5SDimitry Andric       !AM.IndexReg.getNode()) {
20080b57cec5SDimitry Andric     N = Handle.getValue();
20090b57cec5SDimitry Andric     AM.Base_Reg = N.getOperand(0);
20100b57cec5SDimitry Andric     AM.IndexReg = N.getOperand(1);
20110b57cec5SDimitry Andric     AM.Scale = 1;
20120b57cec5SDimitry Andric     return false;
20130b57cec5SDimitry Andric   }
20140b57cec5SDimitry Andric   N = Handle.getValue();
20150b57cec5SDimitry Andric   return true;
20160b57cec5SDimitry Andric }
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric // Insert a node into the DAG at least before the Pos node's position. This
20190b57cec5SDimitry Andric // will reposition the node as needed, and will assign it a node ID that is <=
20200b57cec5SDimitry Andric // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
20210b57cec5SDimitry Andric // IDs! The selection DAG must no longer depend on their uniqueness when this
20220b57cec5SDimitry Andric // is used.
insertDAGNode(SelectionDAG & DAG,SDValue Pos,SDValue N)20230b57cec5SDimitry Andric static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
20240b57cec5SDimitry Andric   if (N->getNodeId() == -1 ||
20250b57cec5SDimitry Andric       (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
20260b57cec5SDimitry Andric        SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
20270b57cec5SDimitry Andric     DAG.RepositionNode(Pos->getIterator(), N.getNode());
20280b57cec5SDimitry Andric     // Mark Node as invalid for pruning as after this it may be a successor to a
20290b57cec5SDimitry Andric     // selected node but otherwise be in the same position of Pos.
20300b57cec5SDimitry Andric     // Conservatively mark it with the same -abs(Id) to assure node id
20310b57cec5SDimitry Andric     // invariant is preserved.
20320b57cec5SDimitry Andric     N->setNodeId(Pos->getNodeId());
20330b57cec5SDimitry Andric     SelectionDAGISel::InvalidateNodeId(N.getNode());
20340b57cec5SDimitry Andric   }
20350b57cec5SDimitry Andric }
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
20380b57cec5SDimitry Andric // safe. This allows us to convert the shift and and into an h-register
20390b57cec5SDimitry Andric // extract and a scaled index. Returns false if the simplification is
20400b57cec5SDimitry Andric // performed.
foldMaskAndShiftToExtract(SelectionDAG & DAG,SDValue N,uint64_t Mask,SDValue Shift,SDValue X,X86ISelAddressMode & AM)20410b57cec5SDimitry Andric static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
20420b57cec5SDimitry Andric                                       uint64_t Mask,
20430b57cec5SDimitry Andric                                       SDValue Shift, SDValue X,
20440b57cec5SDimitry Andric                                       X86ISelAddressMode &AM) {
20450b57cec5SDimitry Andric   if (Shift.getOpcode() != ISD::SRL ||
20460b57cec5SDimitry Andric       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
20470b57cec5SDimitry Andric       !Shift.hasOneUse())
20480b57cec5SDimitry Andric     return true;
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
20510b57cec5SDimitry Andric   if (ScaleLog <= 0 || ScaleLog >= 4 ||
20520b57cec5SDimitry Andric       Mask != (0xffu << ScaleLog))
20530b57cec5SDimitry Andric     return true;
20540b57cec5SDimitry Andric 
205506c3fb27SDimitry Andric   MVT XVT = X.getSimpleValueType();
20560b57cec5SDimitry Andric   MVT VT = N.getSimpleValueType();
20570b57cec5SDimitry Andric   SDLoc DL(N);
20580b57cec5SDimitry Andric   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
205906c3fb27SDimitry Andric   SDValue NewMask = DAG.getConstant(0xff, DL, XVT);
206006c3fb27SDimitry Andric   SDValue Srl = DAG.getNode(ISD::SRL, DL, XVT, X, Eight);
206106c3fb27SDimitry Andric   SDValue And = DAG.getNode(ISD::AND, DL, XVT, Srl, NewMask);
206206c3fb27SDimitry Andric   SDValue Ext = DAG.getZExtOrTrunc(And, DL, VT);
20635f757f3fSDimitry Andric   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
206406c3fb27SDimitry Andric   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Ext, ShlCount);
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   // Insert the new nodes into the topological ordering. We must do this in
20670b57cec5SDimitry Andric   // a valid topological ordering as nothing is going to go back and re-sort
20680b57cec5SDimitry Andric   // these nodes. We continually insert before 'N' in sequence as this is
20690b57cec5SDimitry Andric   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
20700b57cec5SDimitry Andric   // hierarchy left to express.
20710b57cec5SDimitry Andric   insertDAGNode(DAG, N, Eight);
20720b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewMask);
20735f757f3fSDimitry Andric   insertDAGNode(DAG, N, Srl);
20740b57cec5SDimitry Andric   insertDAGNode(DAG, N, And);
207506c3fb27SDimitry Andric   insertDAGNode(DAG, N, Ext);
20765f757f3fSDimitry Andric   insertDAGNode(DAG, N, ShlCount);
20770b57cec5SDimitry Andric   insertDAGNode(DAG, N, Shl);
20780b57cec5SDimitry Andric   DAG.ReplaceAllUsesWith(N, Shl);
20790b57cec5SDimitry Andric   DAG.RemoveDeadNode(N.getNode());
208006c3fb27SDimitry Andric   AM.IndexReg = Ext;
20810b57cec5SDimitry Andric   AM.Scale = (1 << ScaleLog);
20820b57cec5SDimitry Andric   return false;
20830b57cec5SDimitry Andric }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
20860b57cec5SDimitry Andric // allows us to fold the shift into this addressing mode. Returns false if the
20870b57cec5SDimitry Andric // transform succeeded.
foldMaskedShiftToScaledMask(SelectionDAG & DAG,SDValue N,X86ISelAddressMode & AM)20880b57cec5SDimitry Andric static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
20890b57cec5SDimitry Andric                                         X86ISelAddressMode &AM) {
20900b57cec5SDimitry Andric   SDValue Shift = N.getOperand(0);
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric   // Use a signed mask so that shifting right will insert sign bits. These
20930b57cec5SDimitry Andric   // bits will be removed when we shift the result left so it doesn't matter
20940b57cec5SDimitry Andric   // what we use. This might allow a smaller immediate encoding.
20950b57cec5SDimitry Andric   int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric   // If we have an any_extend feeding the AND, look through it to see if there
20980b57cec5SDimitry Andric   // is a shift behind it. But only if the AND doesn't use the extended bits.
20990b57cec5SDimitry Andric   // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
21000b57cec5SDimitry Andric   bool FoundAnyExtend = false;
21010b57cec5SDimitry Andric   if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
21020b57cec5SDimitry Andric       Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
21030b57cec5SDimitry Andric       isUInt<32>(Mask)) {
21040b57cec5SDimitry Andric     FoundAnyExtend = true;
21050b57cec5SDimitry Andric     Shift = Shift.getOperand(0);
21060b57cec5SDimitry Andric   }
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric   if (Shift.getOpcode() != ISD::SHL ||
21090b57cec5SDimitry Andric       !isa<ConstantSDNode>(Shift.getOperand(1)))
21100b57cec5SDimitry Andric     return true;
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   SDValue X = Shift.getOperand(0);
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   // Not likely to be profitable if either the AND or SHIFT node has more
21150b57cec5SDimitry Andric   // than one use (unless all uses are for address computation). Besides,
21160b57cec5SDimitry Andric   // isel mechanism requires their node ids to be reused.
21170b57cec5SDimitry Andric   if (!N.hasOneUse() || !Shift.hasOneUse())
21180b57cec5SDimitry Andric     return true;
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric   // Verify that the shift amount is something we can fold.
21210b57cec5SDimitry Andric   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
21220b57cec5SDimitry Andric   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
21230b57cec5SDimitry Andric     return true;
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric   MVT VT = N.getSimpleValueType();
21260b57cec5SDimitry Andric   SDLoc DL(N);
21270b57cec5SDimitry Andric   if (FoundAnyExtend) {
21280b57cec5SDimitry Andric     SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
21290b57cec5SDimitry Andric     insertDAGNode(DAG, N, NewX);
21300b57cec5SDimitry Andric     X = NewX;
21310b57cec5SDimitry Andric   }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
21340b57cec5SDimitry Andric   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
21350b57cec5SDimitry Andric   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   // Insert the new nodes into the topological ordering. We must do this in
21380b57cec5SDimitry Andric   // a valid topological ordering as nothing is going to go back and re-sort
21390b57cec5SDimitry Andric   // these nodes. We continually insert before 'N' in sequence as this is
21400b57cec5SDimitry Andric   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
21410b57cec5SDimitry Andric   // hierarchy left to express.
21420b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewMask);
21430b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewAnd);
21440b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewShift);
21450b57cec5SDimitry Andric   DAG.ReplaceAllUsesWith(N, NewShift);
21460b57cec5SDimitry Andric   DAG.RemoveDeadNode(N.getNode());
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric   AM.Scale = 1 << ShiftAmt;
21490b57cec5SDimitry Andric   AM.IndexReg = NewAnd;
21500b57cec5SDimitry Andric   return false;
21510b57cec5SDimitry Andric }
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric // Implement some heroics to detect shifts of masked values where the mask can
21540b57cec5SDimitry Andric // be replaced by extending the shift and undoing that in the addressing mode
21550b57cec5SDimitry Andric // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
21560b57cec5SDimitry Andric // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
21570b57cec5SDimitry Andric // the addressing mode. This results in code such as:
21580b57cec5SDimitry Andric //
21590b57cec5SDimitry Andric //   int f(short *y, int *lookup_table) {
21600b57cec5SDimitry Andric //     ...
21610b57cec5SDimitry Andric //     return *y + lookup_table[*y >> 11];
21620b57cec5SDimitry Andric //   }
21630b57cec5SDimitry Andric //
21640b57cec5SDimitry Andric // Turning into:
21650b57cec5SDimitry Andric //   movzwl (%rdi), %eax
21660b57cec5SDimitry Andric //   movl %eax, %ecx
21670b57cec5SDimitry Andric //   shrl $11, %ecx
21680b57cec5SDimitry Andric //   addl (%rsi,%rcx,4), %eax
21690b57cec5SDimitry Andric //
21700b57cec5SDimitry Andric // Instead of:
21710b57cec5SDimitry Andric //   movzwl (%rdi), %eax
21720b57cec5SDimitry Andric //   movl %eax, %ecx
21730b57cec5SDimitry Andric //   shrl $9, %ecx
21740b57cec5SDimitry Andric //   andl $124, %rcx
21750b57cec5SDimitry Andric //   addl (%rsi,%rcx), %eax
21760b57cec5SDimitry Andric //
21770b57cec5SDimitry Andric // Note that this function assumes the mask is provided as a mask *after* the
21780b57cec5SDimitry Andric // value is shifted. The input chain may or may not match that, but computing
21790b57cec5SDimitry Andric // such a mask is trivial.
foldMaskAndShiftToScale(SelectionDAG & DAG,SDValue N,uint64_t Mask,SDValue Shift,SDValue X,X86ISelAddressMode & AM)21800b57cec5SDimitry Andric static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
21810b57cec5SDimitry Andric                                     uint64_t Mask,
21820b57cec5SDimitry Andric                                     SDValue Shift, SDValue X,
21830b57cec5SDimitry Andric                                     X86ISelAddressMode &AM) {
21840b57cec5SDimitry Andric   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
21850b57cec5SDimitry Andric       !isa<ConstantSDNode>(Shift.getOperand(1)))
21860b57cec5SDimitry Andric     return true;
21870b57cec5SDimitry Andric 
21885f757f3fSDimitry Andric   // We need to ensure that mask is a continuous run of bits.
21895f757f3fSDimitry Andric   unsigned MaskIdx, MaskLen;
21905f757f3fSDimitry Andric   if (!isShiftedMask_64(Mask, MaskIdx, MaskLen))
21915f757f3fSDimitry Andric     return true;
21925f757f3fSDimitry Andric   unsigned MaskLZ = 64 - (MaskIdx + MaskLen);
21935f757f3fSDimitry Andric 
21940b57cec5SDimitry Andric   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric   // The amount of shift we're trying to fit into the addressing mode is taken
21975f757f3fSDimitry Andric   // from the shifted mask index (number of trailing zeros of the mask).
21985f757f3fSDimitry Andric   unsigned AMShiftAmt = MaskIdx;
21990b57cec5SDimitry Andric 
22000b57cec5SDimitry Andric   // There is nothing we can do here unless the mask is removing some bits.
22010b57cec5SDimitry Andric   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
22025ffd83dbSDimitry Andric   if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   // Scale the leading zero count down based on the actual size of the value.
22050b57cec5SDimitry Andric   // Also scale it down based on the size of the shift.
22060b57cec5SDimitry Andric   unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
22070b57cec5SDimitry Andric   if (MaskLZ < ScaleDown)
22080b57cec5SDimitry Andric     return true;
22090b57cec5SDimitry Andric   MaskLZ -= ScaleDown;
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric   // The final check is to ensure that any masked out high bits of X are
22120b57cec5SDimitry Andric   // already known to be zero. Otherwise, the mask has a semantic impact
22130b57cec5SDimitry Andric   // other than masking out a couple of low bits. Unfortunately, because of
22140b57cec5SDimitry Andric   // the mask, zero extensions will be removed from operands in some cases.
22150b57cec5SDimitry Andric   // This code works extra hard to look through extensions because we can
22160b57cec5SDimitry Andric   // replace them with zero extensions cheaply if necessary.
22170b57cec5SDimitry Andric   bool ReplacingAnyExtend = false;
22180b57cec5SDimitry Andric   if (X.getOpcode() == ISD::ANY_EXTEND) {
22190b57cec5SDimitry Andric     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
22200b57cec5SDimitry Andric                           X.getOperand(0).getSimpleValueType().getSizeInBits();
22210b57cec5SDimitry Andric     // Assume that we'll replace the any-extend with a zero-extend, and
22220b57cec5SDimitry Andric     // narrow the search to the extended value.
22230b57cec5SDimitry Andric     X = X.getOperand(0);
22240b57cec5SDimitry Andric     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
22250b57cec5SDimitry Andric     ReplacingAnyExtend = true;
22260b57cec5SDimitry Andric   }
22270b57cec5SDimitry Andric   APInt MaskedHighBits =
22280b57cec5SDimitry Andric     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
22295f757f3fSDimitry Andric   if (!DAG.MaskedValueIsZero(X, MaskedHighBits))
22305f757f3fSDimitry Andric     return true;
22310b57cec5SDimitry Andric 
22320b57cec5SDimitry Andric   // We've identified a pattern that can be transformed into a single shift
22330b57cec5SDimitry Andric   // and an addressing mode. Make it so.
22340b57cec5SDimitry Andric   MVT VT = N.getSimpleValueType();
22350b57cec5SDimitry Andric   if (ReplacingAnyExtend) {
22360b57cec5SDimitry Andric     assert(X.getValueType() != VT);
22370b57cec5SDimitry Andric     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
22380b57cec5SDimitry Andric     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
22390b57cec5SDimitry Andric     insertDAGNode(DAG, N, NewX);
22400b57cec5SDimitry Andric     X = NewX;
22410b57cec5SDimitry Andric   }
22425f757f3fSDimitry Andric 
22435f757f3fSDimitry Andric   MVT XVT = X.getSimpleValueType();
22440b57cec5SDimitry Andric   SDLoc DL(N);
22450b57cec5SDimitry Andric   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
22465f757f3fSDimitry Andric   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt);
22475f757f3fSDimitry Andric   SDValue NewExt = DAG.getZExtOrTrunc(NewSRL, DL, VT);
22480b57cec5SDimitry Andric   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
22495f757f3fSDimitry Andric   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt);
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric   // Insert the new nodes into the topological ordering. We must do this in
22520b57cec5SDimitry Andric   // a valid topological ordering as nothing is going to go back and re-sort
22530b57cec5SDimitry Andric   // these nodes. We continually insert before 'N' in sequence as this is
22540b57cec5SDimitry Andric   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
22550b57cec5SDimitry Andric   // hierarchy left to express.
22560b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSRLAmt);
22570b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSRL);
22585f757f3fSDimitry Andric   insertDAGNode(DAG, N, NewExt);
22590b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSHLAmt);
22600b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSHL);
22610b57cec5SDimitry Andric   DAG.ReplaceAllUsesWith(N, NewSHL);
22620b57cec5SDimitry Andric   DAG.RemoveDeadNode(N.getNode());
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   AM.Scale = 1 << AMShiftAmt;
22655f757f3fSDimitry Andric   AM.IndexReg = NewExt;
22660b57cec5SDimitry Andric   return false;
22670b57cec5SDimitry Andric }
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric // Transform "(X >> SHIFT) & (MASK << C1)" to
22700b57cec5SDimitry Andric // "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
22710b57cec5SDimitry Andric // 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)22720b57cec5SDimitry Andric static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,
22730b57cec5SDimitry Andric                                    uint64_t Mask,
22740b57cec5SDimitry Andric                                    SDValue Shift, SDValue X,
22750b57cec5SDimitry Andric                                    X86ISelAddressMode &AM,
22760b57cec5SDimitry Andric                                    const X86Subtarget &Subtarget) {
22770b57cec5SDimitry Andric   if (Shift.getOpcode() != ISD::SRL ||
22780b57cec5SDimitry Andric       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
22790b57cec5SDimitry Andric       !Shift.hasOneUse() || !N.hasOneUse())
22800b57cec5SDimitry Andric     return true;
22810b57cec5SDimitry Andric 
22820b57cec5SDimitry Andric   // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
22830b57cec5SDimitry Andric   if (!Subtarget.hasTBM() &&
22840b57cec5SDimitry Andric       !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
22850b57cec5SDimitry Andric     return true;
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric   // We need to ensure that mask is a continuous run of bits.
22885f757f3fSDimitry Andric   unsigned MaskIdx, MaskLen;
22895f757f3fSDimitry Andric   if (!isShiftedMask_64(Mask, MaskIdx, MaskLen))
22905f757f3fSDimitry Andric     return true;
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   // The amount of shift we're trying to fit into the addressing mode is taken
22955f757f3fSDimitry Andric   // from the shifted mask index (number of trailing zeros of the mask).
22965f757f3fSDimitry Andric   unsigned AMShiftAmt = MaskIdx;
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   // There is nothing we can do here unless the mask is removing some bits.
22990b57cec5SDimitry Andric   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
23005ffd83dbSDimitry Andric   if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
23010b57cec5SDimitry Andric 
23025f757f3fSDimitry Andric   MVT XVT = X.getSimpleValueType();
23030b57cec5SDimitry Andric   MVT VT = N.getSimpleValueType();
23040b57cec5SDimitry Andric   SDLoc DL(N);
23050b57cec5SDimitry Andric   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
23065f757f3fSDimitry Andric   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt);
23075f757f3fSDimitry Andric   SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, XVT);
23085f757f3fSDimitry Andric   SDValue NewAnd = DAG.getNode(ISD::AND, DL, XVT, NewSRL, NewMask);
23095f757f3fSDimitry Andric   SDValue NewExt = DAG.getZExtOrTrunc(NewAnd, DL, VT);
23100b57cec5SDimitry Andric   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
23115f757f3fSDimitry Andric   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt);
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric   // Insert the new nodes into the topological ordering. We must do this in
23140b57cec5SDimitry Andric   // a valid topological ordering as nothing is going to go back and re-sort
23150b57cec5SDimitry Andric   // these nodes. We continually insert before 'N' in sequence as this is
23160b57cec5SDimitry Andric   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
23170b57cec5SDimitry Andric   // hierarchy left to express.
23180b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSRLAmt);
23190b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSRL);
23200b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewMask);
23210b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewAnd);
23225f757f3fSDimitry Andric   insertDAGNode(DAG, N, NewExt);
23230b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSHLAmt);
23240b57cec5SDimitry Andric   insertDAGNode(DAG, N, NewSHL);
23250b57cec5SDimitry Andric   DAG.ReplaceAllUsesWith(N, NewSHL);
23260b57cec5SDimitry Andric   DAG.RemoveDeadNode(N.getNode());
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric   AM.Scale = 1 << AMShiftAmt;
23295f757f3fSDimitry Andric   AM.IndexReg = NewExt;
23300b57cec5SDimitry Andric   return false;
23310b57cec5SDimitry Andric }
23320b57cec5SDimitry Andric 
23335f757f3fSDimitry Andric // Attempt to peek further into a scaled index register, collecting additional
23345f757f3fSDimitry Andric // extensions / offsets / etc. Returns /p N if we can't peek any further.
matchIndexRecursively(SDValue N,X86ISelAddressMode & AM,unsigned Depth)23355f757f3fSDimitry Andric SDValue X86DAGToDAGISel::matchIndexRecursively(SDValue N,
23365f757f3fSDimitry Andric                                                X86ISelAddressMode &AM,
23375f757f3fSDimitry Andric                                                unsigned Depth) {
23385f757f3fSDimitry Andric   assert(AM.IndexReg.getNode() == nullptr && "IndexReg already matched");
23395f757f3fSDimitry Andric   assert((AM.Scale == 1 || AM.Scale == 2 || AM.Scale == 4 || AM.Scale == 8) &&
23405f757f3fSDimitry Andric          "Illegal index scale");
23415f757f3fSDimitry Andric 
23425f757f3fSDimitry Andric   // Limit recursion.
23435f757f3fSDimitry Andric   if (Depth >= SelectionDAG::MaxRecursionDepth)
23445f757f3fSDimitry Andric     return N;
23455f757f3fSDimitry Andric 
23465f757f3fSDimitry Andric   EVT VT = N.getValueType();
23475f757f3fSDimitry Andric   unsigned Opc = N.getOpcode();
23485f757f3fSDimitry Andric 
23495f757f3fSDimitry Andric   // index: add(x,c) -> index: x, disp + c
23505f757f3fSDimitry Andric   if (CurDAG->isBaseWithConstantOffset(N)) {
23515f757f3fSDimitry Andric     auto *AddVal = cast<ConstantSDNode>(N.getOperand(1));
23525f757f3fSDimitry Andric     uint64_t Offset = (uint64_t)AddVal->getSExtValue() * AM.Scale;
23535f757f3fSDimitry Andric     if (!foldOffsetIntoAddress(Offset, AM))
23545f757f3fSDimitry Andric       return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);
23555f757f3fSDimitry Andric   }
23565f757f3fSDimitry Andric 
23575f757f3fSDimitry Andric   // index: add(x,x) -> index: x, scale * 2
23585f757f3fSDimitry Andric   if (Opc == ISD::ADD && N.getOperand(0) == N.getOperand(1)) {
23595f757f3fSDimitry Andric     if (AM.Scale <= 4) {
23605f757f3fSDimitry Andric       AM.Scale *= 2;
23615f757f3fSDimitry Andric       return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);
23625f757f3fSDimitry Andric     }
23635f757f3fSDimitry Andric   }
23645f757f3fSDimitry Andric 
23655f757f3fSDimitry Andric   // index: shl(x,i) -> index: x, scale * (1 << i)
23665f757f3fSDimitry Andric   if (Opc == X86ISD::VSHLI) {
23675f757f3fSDimitry Andric     uint64_t ShiftAmt = N.getConstantOperandVal(1);
23685f757f3fSDimitry Andric     uint64_t ScaleAmt = 1ULL << ShiftAmt;
23695f757f3fSDimitry Andric     if ((AM.Scale * ScaleAmt) <= 8) {
23705f757f3fSDimitry Andric       AM.Scale *= ScaleAmt;
23715f757f3fSDimitry Andric       return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);
23725f757f3fSDimitry Andric     }
23735f757f3fSDimitry Andric   }
23745f757f3fSDimitry Andric 
23755f757f3fSDimitry Andric   // index: sext(add_nsw(x,c)) -> index: sext(x), disp + sext(c)
23765f757f3fSDimitry Andric   // TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext?
23775f757f3fSDimitry Andric   if (Opc == ISD::SIGN_EXTEND && !VT.isVector() && N.hasOneUse()) {
23785f757f3fSDimitry Andric     SDValue Src = N.getOperand(0);
23795f757f3fSDimitry Andric     if (Src.getOpcode() == ISD::ADD && Src->getFlags().hasNoSignedWrap() &&
23805f757f3fSDimitry Andric         Src.hasOneUse()) {
23815f757f3fSDimitry Andric       if (CurDAG->isBaseWithConstantOffset(Src)) {
23825f757f3fSDimitry Andric         SDValue AddSrc = Src.getOperand(0);
23835f757f3fSDimitry Andric         auto *AddVal = cast<ConstantSDNode>(Src.getOperand(1));
23845f757f3fSDimitry Andric         uint64_t Offset = (uint64_t)AddVal->getSExtValue();
23855f757f3fSDimitry Andric         if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) {
23865f757f3fSDimitry Andric           SDLoc DL(N);
23875f757f3fSDimitry Andric           SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc);
23885f757f3fSDimitry Andric           SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT);
23895f757f3fSDimitry Andric           SDValue ExtAdd = CurDAG->getNode(ISD::ADD, DL, VT, ExtSrc, ExtVal);
23905f757f3fSDimitry Andric           insertDAGNode(*CurDAG, N, ExtSrc);
23915f757f3fSDimitry Andric           insertDAGNode(*CurDAG, N, ExtVal);
23925f757f3fSDimitry Andric           insertDAGNode(*CurDAG, N, ExtAdd);
23935f757f3fSDimitry Andric           CurDAG->ReplaceAllUsesWith(N, ExtAdd);
23945f757f3fSDimitry Andric           CurDAG->RemoveDeadNode(N.getNode());
23955f757f3fSDimitry Andric           return ExtSrc;
23965f757f3fSDimitry Andric         }
23975f757f3fSDimitry Andric       }
23985f757f3fSDimitry Andric     }
23995f757f3fSDimitry Andric   }
24005f757f3fSDimitry Andric 
24015f757f3fSDimitry Andric   // index: zext(add_nuw(x,c)) -> index: zext(x), disp + zext(c)
24025f757f3fSDimitry Andric   // index: zext(addlike(x,c)) -> index: zext(x), disp + zext(c)
24035f757f3fSDimitry Andric   // TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext?
24045f757f3fSDimitry Andric   if (Opc == ISD::ZERO_EXTEND && !VT.isVector() && N.hasOneUse()) {
24055f757f3fSDimitry Andric     SDValue Src = N.getOperand(0);
24065f757f3fSDimitry Andric     unsigned SrcOpc = Src.getOpcode();
24075f757f3fSDimitry Andric     if (((SrcOpc == ISD::ADD && Src->getFlags().hasNoUnsignedWrap()) ||
2408*0fca6ea1SDimitry Andric          CurDAG->isADDLike(Src, /*NoWrap=*/true)) &&
24095f757f3fSDimitry Andric         Src.hasOneUse()) {
24105f757f3fSDimitry Andric       if (CurDAG->isBaseWithConstantOffset(Src)) {
24115f757f3fSDimitry Andric         SDValue AddSrc = Src.getOperand(0);
24127a6dacacSDimitry Andric         uint64_t Offset = Src.getConstantOperandVal(1);
24135f757f3fSDimitry Andric         if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) {
24145f757f3fSDimitry Andric           SDLoc DL(N);
24155f757f3fSDimitry Andric           SDValue Res;
24165f757f3fSDimitry Andric           // If we're also scaling, see if we can use that as well.
24175f757f3fSDimitry Andric           if (AddSrc.getOpcode() == ISD::SHL &&
24185f757f3fSDimitry Andric               isa<ConstantSDNode>(AddSrc.getOperand(1))) {
24195f757f3fSDimitry Andric             SDValue ShVal = AddSrc.getOperand(0);
24205f757f3fSDimitry Andric             uint64_t ShAmt = AddSrc.getConstantOperandVal(1);
24215f757f3fSDimitry Andric             APInt HiBits =
24225f757f3fSDimitry Andric                 APInt::getHighBitsSet(AddSrc.getScalarValueSizeInBits(), ShAmt);
24235f757f3fSDimitry Andric             uint64_t ScaleAmt = 1ULL << ShAmt;
24245f757f3fSDimitry Andric             if ((AM.Scale * ScaleAmt) <= 8 &&
24255f757f3fSDimitry Andric                 (AddSrc->getFlags().hasNoUnsignedWrap() ||
24265f757f3fSDimitry Andric                  CurDAG->MaskedValueIsZero(ShVal, HiBits))) {
24275f757f3fSDimitry Andric               AM.Scale *= ScaleAmt;
24285f757f3fSDimitry Andric               SDValue ExtShVal = CurDAG->getNode(Opc, DL, VT, ShVal);
24295f757f3fSDimitry Andric               SDValue ExtShift = CurDAG->getNode(ISD::SHL, DL, VT, ExtShVal,
24305f757f3fSDimitry Andric                                                  AddSrc.getOperand(1));
24315f757f3fSDimitry Andric               insertDAGNode(*CurDAG, N, ExtShVal);
24325f757f3fSDimitry Andric               insertDAGNode(*CurDAG, N, ExtShift);
24335f757f3fSDimitry Andric               AddSrc = ExtShift;
24345f757f3fSDimitry Andric               Res = ExtShVal;
24355f757f3fSDimitry Andric             }
24365f757f3fSDimitry Andric           }
24375f757f3fSDimitry Andric           SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc);
24385f757f3fSDimitry Andric           SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT);
24395f757f3fSDimitry Andric           SDValue ExtAdd = CurDAG->getNode(SrcOpc, DL, VT, ExtSrc, ExtVal);
24405f757f3fSDimitry Andric           insertDAGNode(*CurDAG, N, ExtSrc);
24415f757f3fSDimitry Andric           insertDAGNode(*CurDAG, N, ExtVal);
24425f757f3fSDimitry Andric           insertDAGNode(*CurDAG, N, ExtAdd);
24435f757f3fSDimitry Andric           CurDAG->ReplaceAllUsesWith(N, ExtAdd);
24445f757f3fSDimitry Andric           CurDAG->RemoveDeadNode(N.getNode());
24455f757f3fSDimitry Andric           return Res ? Res : ExtSrc;
24465f757f3fSDimitry Andric         }
24475f757f3fSDimitry Andric       }
24485f757f3fSDimitry Andric     }
24495f757f3fSDimitry Andric   }
24505f757f3fSDimitry Andric 
24515f757f3fSDimitry Andric   // TODO: Handle extensions, shifted masks etc.
24525f757f3fSDimitry Andric   return N;
24535f757f3fSDimitry Andric }
24545f757f3fSDimitry Andric 
matchAddressRecursively(SDValue N,X86ISelAddressMode & AM,unsigned Depth)24550b57cec5SDimitry Andric bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
24560b57cec5SDimitry Andric                                               unsigned Depth) {
24570b57cec5SDimitry Andric   SDLoc dl(N);
24580b57cec5SDimitry Andric   LLVM_DEBUG({
24590b57cec5SDimitry Andric     dbgs() << "MatchAddress: ";
24600b57cec5SDimitry Andric     AM.dump(CurDAG);
24610b57cec5SDimitry Andric   });
24620b57cec5SDimitry Andric   // Limit recursion.
24635f757f3fSDimitry Andric   if (Depth >= SelectionDAG::MaxRecursionDepth)
24640b57cec5SDimitry Andric     return matchAddressBase(N, AM);
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   // If this is already a %rip relative address, we can only merge immediates
24670b57cec5SDimitry Andric   // into it.  Instead of handling this in every case, we handle it here.
24680b57cec5SDimitry Andric   // RIP relative addressing: %rip + 32-bit displacement!
24690b57cec5SDimitry Andric   if (AM.isRIPRelative()) {
24700b57cec5SDimitry Andric     // FIXME: JumpTable and ExternalSymbol address currently don't like
24710b57cec5SDimitry Andric     // displacements.  It isn't very important, but this should be fixed for
24720b57cec5SDimitry Andric     // consistency.
24730b57cec5SDimitry Andric     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
24740b57cec5SDimitry Andric       return true;
24750b57cec5SDimitry Andric 
2476bdd1243dSDimitry Andric     if (auto *Cst = dyn_cast<ConstantSDNode>(N))
24770b57cec5SDimitry Andric       if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
24780b57cec5SDimitry Andric         return false;
24790b57cec5SDimitry Andric     return true;
24800b57cec5SDimitry Andric   }
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric   switch (N.getOpcode()) {
24830b57cec5SDimitry Andric   default: break;
24840b57cec5SDimitry Andric   case ISD::LOCAL_RECOVER: {
24850b57cec5SDimitry Andric     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
24860b57cec5SDimitry Andric       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
24870b57cec5SDimitry Andric         // Use the symbol and don't prefix it.
24880b57cec5SDimitry Andric         AM.MCSym = ESNode->getMCSymbol();
24890b57cec5SDimitry Andric         return false;
24900b57cec5SDimitry Andric       }
24910b57cec5SDimitry Andric     break;
24920b57cec5SDimitry Andric   }
24930b57cec5SDimitry Andric   case ISD::Constant: {
24940b57cec5SDimitry Andric     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
24950b57cec5SDimitry Andric     if (!foldOffsetIntoAddress(Val, AM))
24960b57cec5SDimitry Andric       return false;
24970b57cec5SDimitry Andric     break;
24980b57cec5SDimitry Andric   }
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric   case X86ISD::Wrapper:
25010b57cec5SDimitry Andric   case X86ISD::WrapperRIP:
25020b57cec5SDimitry Andric     if (!matchWrapper(N, AM))
25030b57cec5SDimitry Andric       return false;
25040b57cec5SDimitry Andric     break;
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric   case ISD::LOAD:
25070b57cec5SDimitry Andric     if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
25080b57cec5SDimitry Andric       return false;
25090b57cec5SDimitry Andric     break;
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric   case ISD::FrameIndex:
25120b57cec5SDimitry Andric     if (AM.BaseType == X86ISelAddressMode::RegBase &&
25130b57cec5SDimitry Andric         AM.Base_Reg.getNode() == nullptr &&
25140b57cec5SDimitry Andric         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
25150b57cec5SDimitry Andric       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
25160b57cec5SDimitry Andric       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
25170b57cec5SDimitry Andric       return false;
25180b57cec5SDimitry Andric     }
25190b57cec5SDimitry Andric     break;
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric   case ISD::SHL:
25220b57cec5SDimitry Andric     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
25230b57cec5SDimitry Andric       break;
25240b57cec5SDimitry Andric 
2525bdd1243dSDimitry Andric     if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
25260b57cec5SDimitry Andric       unsigned Val = CN->getZExtValue();
25270b57cec5SDimitry Andric       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
25280b57cec5SDimitry Andric       // that the base operand remains free for further matching. If
25290b57cec5SDimitry Andric       // the base doesn't end up getting used, a post-processing step
25300b57cec5SDimitry Andric       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
25310b57cec5SDimitry Andric       if (Val == 1 || Val == 2 || Val == 3) {
25320b57cec5SDimitry Andric         SDValue ShVal = N.getOperand(0);
25335f757f3fSDimitry Andric         AM.Scale = 1 << Val;
25345f757f3fSDimitry Andric         AM.IndexReg = matchIndexRecursively(ShVal, AM, Depth + 1);
25350b57cec5SDimitry Andric         return false;
25360b57cec5SDimitry Andric       }
25370b57cec5SDimitry Andric     }
25380b57cec5SDimitry Andric     break;
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric   case ISD::SRL: {
25410b57cec5SDimitry Andric     // Scale must not be used already.
25420b57cec5SDimitry Andric     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric     // We only handle up to 64-bit values here as those are what matter for
25450b57cec5SDimitry Andric     // addressing mode optimizations.
25460b57cec5SDimitry Andric     assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
25470b57cec5SDimitry Andric            "Unexpected value size!");
25480b57cec5SDimitry Andric 
25490b57cec5SDimitry Andric     SDValue And = N.getOperand(0);
25500b57cec5SDimitry Andric     if (And.getOpcode() != ISD::AND) break;
25510b57cec5SDimitry Andric     SDValue X = And.getOperand(0);
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric     // The mask used for the transform is expected to be post-shift, but we
25540b57cec5SDimitry Andric     // found the shift first so just apply the shift to the mask before passing
25550b57cec5SDimitry Andric     // it down.
25560b57cec5SDimitry Andric     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
25570b57cec5SDimitry Andric         !isa<ConstantSDNode>(And.getOperand(1)))
25580b57cec5SDimitry Andric       break;
25590b57cec5SDimitry Andric     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric     // Try to fold the mask and shift into the scale, and return false if we
25620b57cec5SDimitry Andric     // succeed.
25630b57cec5SDimitry Andric     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
25640b57cec5SDimitry Andric       return false;
25650b57cec5SDimitry Andric     break;
25660b57cec5SDimitry Andric   }
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric   case ISD::SMUL_LOHI:
25690b57cec5SDimitry Andric   case ISD::UMUL_LOHI:
25700b57cec5SDimitry Andric     // A mul_lohi where we need the low part can be folded as a plain multiply.
25710b57cec5SDimitry Andric     if (N.getResNo() != 0) break;
2572bdd1243dSDimitry Andric     [[fallthrough]];
25730b57cec5SDimitry Andric   case ISD::MUL:
25740b57cec5SDimitry Andric   case X86ISD::MUL_IMM:
25750b57cec5SDimitry Andric     // X*[3,5,9] -> X+X*[2,4,8]
25760b57cec5SDimitry Andric     if (AM.BaseType == X86ISelAddressMode::RegBase &&
25770b57cec5SDimitry Andric         AM.Base_Reg.getNode() == nullptr &&
25780b57cec5SDimitry Andric         AM.IndexReg.getNode() == nullptr) {
2579bdd1243dSDimitry Andric       if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
25800b57cec5SDimitry Andric         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
25810b57cec5SDimitry Andric             CN->getZExtValue() == 9) {
25820b57cec5SDimitry Andric           AM.Scale = unsigned(CN->getZExtValue())-1;
25830b57cec5SDimitry Andric 
25840b57cec5SDimitry Andric           SDValue MulVal = N.getOperand(0);
25850b57cec5SDimitry Andric           SDValue Reg;
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric           // Okay, we know that we have a scale by now.  However, if the scaled
25880b57cec5SDimitry Andric           // value is an add of something and a constant, we can fold the
25890b57cec5SDimitry Andric           // constant into the disp field here.
25900b57cec5SDimitry Andric           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
25910b57cec5SDimitry Andric               isa<ConstantSDNode>(MulVal.getOperand(1))) {
25920b57cec5SDimitry Andric             Reg = MulVal.getOperand(0);
2593bdd1243dSDimitry Andric             auto *AddVal = cast<ConstantSDNode>(MulVal.getOperand(1));
25940b57cec5SDimitry Andric             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
25950b57cec5SDimitry Andric             if (foldOffsetIntoAddress(Disp, AM))
25960b57cec5SDimitry Andric               Reg = N.getOperand(0);
25970b57cec5SDimitry Andric           } else {
25980b57cec5SDimitry Andric             Reg = N.getOperand(0);
25990b57cec5SDimitry Andric           }
26000b57cec5SDimitry Andric 
26010b57cec5SDimitry Andric           AM.IndexReg = AM.Base_Reg = Reg;
26020b57cec5SDimitry Andric           return false;
26030b57cec5SDimitry Andric         }
26040b57cec5SDimitry Andric     }
26050b57cec5SDimitry Andric     break;
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric   case ISD::SUB: {
26080b57cec5SDimitry Andric     // Given A-B, if A can be completely folded into the address and
26090b57cec5SDimitry Andric     // the index field with the index field unused, use -B as the index.
26100b57cec5SDimitry Andric     // This is a win if a has multiple parts that can be folded into
26110b57cec5SDimitry Andric     // the address. Also, this saves a mov if the base register has
26120b57cec5SDimitry Andric     // other uses, since it avoids a two-address sub instruction, however
26130b57cec5SDimitry Andric     // it costs an additional mov if the index register has other uses.
26140b57cec5SDimitry Andric 
26150b57cec5SDimitry Andric     // Add an artificial use to this node so that we can keep track of
26160b57cec5SDimitry Andric     // it if it gets CSE'd with a different node.
26170b57cec5SDimitry Andric     HandleSDNode Handle(N);
26180b57cec5SDimitry Andric 
26190b57cec5SDimitry Andric     // Test if the LHS of the sub can be folded.
26200b57cec5SDimitry Andric     X86ISelAddressMode Backup = AM;
26210b57cec5SDimitry Andric     if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
26220b57cec5SDimitry Andric       N = Handle.getValue();
26230b57cec5SDimitry Andric       AM = Backup;
26240b57cec5SDimitry Andric       break;
26250b57cec5SDimitry Andric     }
26260b57cec5SDimitry Andric     N = Handle.getValue();
26270b57cec5SDimitry Andric     // Test if the index field is free for use.
26280b57cec5SDimitry Andric     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
26290b57cec5SDimitry Andric       AM = Backup;
26300b57cec5SDimitry Andric       break;
26310b57cec5SDimitry Andric     }
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric     int Cost = 0;
26340b57cec5SDimitry Andric     SDValue RHS = N.getOperand(1);
26350b57cec5SDimitry Andric     // If the RHS involves a register with multiple uses, this
26360b57cec5SDimitry Andric     // transformation incurs an extra mov, due to the neg instruction
26370b57cec5SDimitry Andric     // clobbering its operand.
26380b57cec5SDimitry Andric     if (!RHS.getNode()->hasOneUse() ||
26390b57cec5SDimitry Andric         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
26400b57cec5SDimitry Andric         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
26410b57cec5SDimitry Andric         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
26420b57cec5SDimitry Andric         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
26430b57cec5SDimitry Andric          RHS.getOperand(0).getValueType() == MVT::i32))
26440b57cec5SDimitry Andric       ++Cost;
26450b57cec5SDimitry Andric     // If the base is a register with multiple uses, this
26460b57cec5SDimitry Andric     // transformation may save a mov.
26470b57cec5SDimitry Andric     if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
26480b57cec5SDimitry Andric          !AM.Base_Reg.getNode()->hasOneUse()) ||
26490b57cec5SDimitry Andric         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
26500b57cec5SDimitry Andric       --Cost;
26510b57cec5SDimitry Andric     // If the folded LHS was interesting, this transformation saves
26520b57cec5SDimitry Andric     // address arithmetic.
26530b57cec5SDimitry Andric     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
26540b57cec5SDimitry Andric         ((AM.Disp != 0) && (Backup.Disp == 0)) +
26550b57cec5SDimitry Andric         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
26560b57cec5SDimitry Andric       --Cost;
26570b57cec5SDimitry Andric     // If it doesn't look like it may be an overall win, don't do it.
26580b57cec5SDimitry Andric     if (Cost >= 0) {
26590b57cec5SDimitry Andric       AM = Backup;
26600b57cec5SDimitry Andric       break;
26610b57cec5SDimitry Andric     }
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric     // Ok, the transformation is legal and appears profitable. Go for it.
26640b57cec5SDimitry Andric     // Negation will be emitted later to avoid creating dangling nodes if this
26650b57cec5SDimitry Andric     // was an unprofitable LEA.
26660b57cec5SDimitry Andric     AM.IndexReg = RHS;
26670b57cec5SDimitry Andric     AM.NegateIndex = true;
26680b57cec5SDimitry Andric     AM.Scale = 1;
26690b57cec5SDimitry Andric     return false;
26700b57cec5SDimitry Andric   }
26710b57cec5SDimitry Andric 
26725f757f3fSDimitry Andric   case ISD::OR:
26735f757f3fSDimitry Andric   case ISD::XOR:
26745f757f3fSDimitry Andric     // See if we can treat the OR/XOR node as an ADD node.
26755f757f3fSDimitry Andric     if (!CurDAG->isADDLike(N))
26765f757f3fSDimitry Andric       break;
26775f757f3fSDimitry Andric     [[fallthrough]];
26780b57cec5SDimitry Andric   case ISD::ADD:
26790b57cec5SDimitry Andric     if (!matchAdd(N, AM, Depth))
26800b57cec5SDimitry Andric       return false;
26810b57cec5SDimitry Andric     break;
26820b57cec5SDimitry Andric 
26830b57cec5SDimitry Andric   case ISD::AND: {
26840b57cec5SDimitry Andric     // Perform some heroic transforms on an and of a constant-count shift
26850b57cec5SDimitry Andric     // with a constant to enable use of the scaled offset field.
26860b57cec5SDimitry Andric 
26870b57cec5SDimitry Andric     // Scale must not be used already.
26880b57cec5SDimitry Andric     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric     // We only handle up to 64-bit values here as those are what matter for
26910b57cec5SDimitry Andric     // addressing mode optimizations.
26920b57cec5SDimitry Andric     assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
26930b57cec5SDimitry Andric            "Unexpected value size!");
26940b57cec5SDimitry Andric 
26950b57cec5SDimitry Andric     if (!isa<ConstantSDNode>(N.getOperand(1)))
26960b57cec5SDimitry Andric       break;
26970b57cec5SDimitry Andric 
26980b57cec5SDimitry Andric     if (N.getOperand(0).getOpcode() == ISD::SRL) {
26990b57cec5SDimitry Andric       SDValue Shift = N.getOperand(0);
27000b57cec5SDimitry Andric       SDValue X = Shift.getOperand(0);
27010b57cec5SDimitry Andric 
27020b57cec5SDimitry Andric       uint64_t Mask = N.getConstantOperandVal(1);
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric       // Try to fold the mask and shift into an extract and scale.
27050b57cec5SDimitry Andric       if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
27060b57cec5SDimitry Andric         return false;
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric       // Try to fold the mask and shift directly into the scale.
27090b57cec5SDimitry Andric       if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
27100b57cec5SDimitry Andric         return false;
27110b57cec5SDimitry Andric 
27120b57cec5SDimitry Andric       // Try to fold the mask and shift into BEXTR and scale.
27130b57cec5SDimitry Andric       if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
27140b57cec5SDimitry Andric         return false;
27150b57cec5SDimitry Andric     }
27160b57cec5SDimitry Andric 
27170b57cec5SDimitry Andric     // Try to swap the mask and shift to place shifts which can be done as
27180b57cec5SDimitry Andric     // a scale on the outside of the mask.
27190b57cec5SDimitry Andric     if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))
27200b57cec5SDimitry Andric       return false;
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric     break;
27230b57cec5SDimitry Andric   }
27240b57cec5SDimitry Andric   case ISD::ZERO_EXTEND: {
27250b57cec5SDimitry Andric     // Try to widen a zexted shift left to the same size as its use, so we can
27260b57cec5SDimitry Andric     // match the shift as a scale factor.
27270b57cec5SDimitry Andric     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
27280b57cec5SDimitry Andric       break;
27290b57cec5SDimitry Andric 
273006c3fb27SDimitry Andric     SDValue Src = N.getOperand(0);
27315f757f3fSDimitry Andric 
27325f757f3fSDimitry Andric     // See if we can match a zext(addlike(x,c)).
27335f757f3fSDimitry Andric     // TODO: Move more ZERO_EXTEND patterns into matchIndexRecursively.
27345f757f3fSDimitry Andric     if (Src.getOpcode() == ISD::ADD || Src.getOpcode() == ISD::OR)
27355f757f3fSDimitry Andric       if (SDValue Index = matchIndexRecursively(N, AM, Depth + 1))
27365f757f3fSDimitry Andric         if (Index != N) {
27375f757f3fSDimitry Andric           AM.IndexReg = Index;
27385f757f3fSDimitry Andric           return false;
27395f757f3fSDimitry Andric         }
27405f757f3fSDimitry Andric 
27415f757f3fSDimitry Andric     // Peek through mask: zext(and(shl(x,c1),c2))
274206c3fb27SDimitry Andric     APInt Mask = APInt::getAllOnes(Src.getScalarValueSizeInBits());
274306c3fb27SDimitry Andric     if (Src.getOpcode() == ISD::AND && Src.hasOneUse())
274406c3fb27SDimitry Andric       if (auto *MaskC = dyn_cast<ConstantSDNode>(Src.getOperand(1))) {
274506c3fb27SDimitry Andric         Mask = MaskC->getAPIntValue();
274606c3fb27SDimitry Andric         Src = Src.getOperand(0);
274706c3fb27SDimitry Andric       }
274806c3fb27SDimitry Andric 
2749*0fca6ea1SDimitry Andric     if (Src.getOpcode() == ISD::SHL && Src.hasOneUse() && N->hasOneUse()) {
27500b57cec5SDimitry Andric       // Give up if the shift is not a valid scale factor [1,2,3].
275106c3fb27SDimitry Andric       SDValue ShlSrc = Src.getOperand(0);
275206c3fb27SDimitry Andric       SDValue ShlAmt = Src.getOperand(1);
275306c3fb27SDimitry Andric       auto *ShAmtC = dyn_cast<ConstantSDNode>(ShlAmt);
275406c3fb27SDimitry Andric       if (!ShAmtC)
275506c3fb27SDimitry Andric         break;
275606c3fb27SDimitry Andric       unsigned ShAmtV = ShAmtC->getZExtValue();
275706c3fb27SDimitry Andric       if (ShAmtV > 3)
27580b57cec5SDimitry Andric         break;
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric       // The narrow shift must only shift out zero bits (it must be 'nuw').
27610b57cec5SDimitry Andric       // That makes it safe to widen to the destination type.
276206c3fb27SDimitry Andric       APInt HighZeros =
276306c3fb27SDimitry Andric           APInt::getHighBitsSet(ShlSrc.getValueSizeInBits(), ShAmtV);
27645f757f3fSDimitry Andric       if (!Src->getFlags().hasNoUnsignedWrap() &&
27655f757f3fSDimitry Andric           !CurDAG->MaskedValueIsZero(ShlSrc, HighZeros & Mask))
27660b57cec5SDimitry Andric         break;
27670b57cec5SDimitry Andric 
276806c3fb27SDimitry Andric       // zext (shl nuw i8 %x, C1) to i32
276906c3fb27SDimitry Andric       // --> shl (zext i8 %x to i32), (zext C1)
277006c3fb27SDimitry Andric       // zext (and (shl nuw i8 %x, C1), C2) to i32
277106c3fb27SDimitry Andric       // --> shl (zext i8 (and %x, C2 >> C1) to i32), (zext C1)
277206c3fb27SDimitry Andric       MVT SrcVT = ShlSrc.getSimpleValueType();
27730b57cec5SDimitry Andric       MVT VT = N.getSimpleValueType();
27740b57cec5SDimitry Andric       SDLoc DL(N);
277506c3fb27SDimitry Andric 
277606c3fb27SDimitry Andric       SDValue Res = ShlSrc;
277706c3fb27SDimitry Andric       if (!Mask.isAllOnes()) {
277806c3fb27SDimitry Andric         Res = CurDAG->getConstant(Mask.lshr(ShAmtV), DL, SrcVT);
277906c3fb27SDimitry Andric         insertDAGNode(*CurDAG, N, Res);
278006c3fb27SDimitry Andric         Res = CurDAG->getNode(ISD::AND, DL, SrcVT, ShlSrc, Res);
278106c3fb27SDimitry Andric         insertDAGNode(*CurDAG, N, Res);
278206c3fb27SDimitry Andric       }
278306c3fb27SDimitry Andric       SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Res);
278406c3fb27SDimitry Andric       insertDAGNode(*CurDAG, N, Zext);
278506c3fb27SDimitry Andric       SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, ShlAmt);
278606c3fb27SDimitry Andric       insertDAGNode(*CurDAG, N, NewShl);
2787*0fca6ea1SDimitry Andric       CurDAG->ReplaceAllUsesWith(N, NewShl);
2788*0fca6ea1SDimitry Andric       CurDAG->RemoveDeadNode(N.getNode());
27890b57cec5SDimitry Andric 
27900b57cec5SDimitry Andric       // Convert the shift to scale factor.
279106c3fb27SDimitry Andric       AM.Scale = 1 << ShAmtV;
2792*0fca6ea1SDimitry Andric       // If matchIndexRecursively is not called here,
2793*0fca6ea1SDimitry Andric       // Zext may be replaced by other nodes but later used to call a builder
2794*0fca6ea1SDimitry Andric       // method
2795*0fca6ea1SDimitry Andric       AM.IndexReg = matchIndexRecursively(Zext, AM, Depth + 1);
27960b57cec5SDimitry Andric       return false;
27970b57cec5SDimitry Andric     }
279806c3fb27SDimitry Andric 
27995f757f3fSDimitry Andric     if (Src.getOpcode() == ISD::SRL && !Mask.isAllOnes()) {
280006c3fb27SDimitry Andric       // Try to fold the mask and shift into an extract and scale.
28015f757f3fSDimitry Andric       if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask.getZExtValue(), Src,
280206c3fb27SDimitry Andric                                      Src.getOperand(0), AM))
280306c3fb27SDimitry Andric         return false;
280406c3fb27SDimitry Andric 
28055f757f3fSDimitry Andric       // Try to fold the mask and shift directly into the scale.
28065f757f3fSDimitry Andric       if (!foldMaskAndShiftToScale(*CurDAG, N, Mask.getZExtValue(), Src,
28075f757f3fSDimitry Andric                                    Src.getOperand(0), AM))
28085f757f3fSDimitry Andric         return false;
28095f757f3fSDimitry Andric 
28105f757f3fSDimitry Andric       // Try to fold the mask and shift into BEXTR and scale.
28115f757f3fSDimitry Andric       if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask.getZExtValue(), Src,
28125f757f3fSDimitry Andric                                   Src.getOperand(0), AM, *Subtarget))
28135f757f3fSDimitry Andric         return false;
28145f757f3fSDimitry Andric     }
28155f757f3fSDimitry Andric 
281606c3fb27SDimitry Andric     break;
281706c3fb27SDimitry Andric   }
28180b57cec5SDimitry Andric   }
28190b57cec5SDimitry Andric 
28200b57cec5SDimitry Andric   return matchAddressBase(N, AM);
28210b57cec5SDimitry Andric }
28220b57cec5SDimitry Andric 
28230b57cec5SDimitry Andric /// Helper for MatchAddress. Add the specified node to the
28240b57cec5SDimitry Andric /// specified addressing mode without any further recursion.
matchAddressBase(SDValue N,X86ISelAddressMode & AM)28250b57cec5SDimitry Andric bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
28260b57cec5SDimitry Andric   // Is the base register already occupied?
28270b57cec5SDimitry Andric   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
28280b57cec5SDimitry Andric     // If so, check to see if the scale index register is set.
28290b57cec5SDimitry Andric     if (!AM.IndexReg.getNode()) {
28300b57cec5SDimitry Andric       AM.IndexReg = N;
28310b57cec5SDimitry Andric       AM.Scale = 1;
28320b57cec5SDimitry Andric       return false;
28330b57cec5SDimitry Andric     }
28340b57cec5SDimitry Andric 
28350b57cec5SDimitry Andric     // Otherwise, we cannot select it.
28360b57cec5SDimitry Andric     return true;
28370b57cec5SDimitry Andric   }
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric   // Default, generate it as a register.
28400b57cec5SDimitry Andric   AM.BaseType = X86ISelAddressMode::RegBase;
28410b57cec5SDimitry Andric   AM.Base_Reg = N;
28420b57cec5SDimitry Andric   return false;
28430b57cec5SDimitry Andric }
28440b57cec5SDimitry Andric 
matchVectorAddressRecursively(SDValue N,X86ISelAddressMode & AM,unsigned Depth)2845349cc55cSDimitry Andric bool X86DAGToDAGISel::matchVectorAddressRecursively(SDValue N,
2846349cc55cSDimitry Andric                                                     X86ISelAddressMode &AM,
2847349cc55cSDimitry Andric                                                     unsigned Depth) {
2848349cc55cSDimitry Andric   SDLoc dl(N);
2849349cc55cSDimitry Andric   LLVM_DEBUG({
2850349cc55cSDimitry Andric     dbgs() << "MatchVectorAddress: ";
2851349cc55cSDimitry Andric     AM.dump(CurDAG);
2852349cc55cSDimitry Andric   });
2853349cc55cSDimitry Andric   // Limit recursion.
28545f757f3fSDimitry Andric   if (Depth >= SelectionDAG::MaxRecursionDepth)
2855349cc55cSDimitry Andric     return matchAddressBase(N, AM);
2856349cc55cSDimitry Andric 
28570b57cec5SDimitry Andric   // TODO: Support other operations.
28580b57cec5SDimitry Andric   switch (N.getOpcode()) {
28590b57cec5SDimitry Andric   case ISD::Constant: {
28600b57cec5SDimitry Andric     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
28610b57cec5SDimitry Andric     if (!foldOffsetIntoAddress(Val, AM))
28620b57cec5SDimitry Andric       return false;
28630b57cec5SDimitry Andric     break;
28640b57cec5SDimitry Andric   }
28650b57cec5SDimitry Andric   case X86ISD::Wrapper:
28660b57cec5SDimitry Andric     if (!matchWrapper(N, AM))
28670b57cec5SDimitry Andric       return false;
28680b57cec5SDimitry Andric     break;
2869349cc55cSDimitry Andric   case ISD::ADD: {
2870349cc55cSDimitry Andric     // Add an artificial use to this node so that we can keep track of
2871349cc55cSDimitry Andric     // it if it gets CSE'd with a different node.
2872349cc55cSDimitry Andric     HandleSDNode Handle(N);
2873349cc55cSDimitry Andric 
2874349cc55cSDimitry Andric     X86ISelAddressMode Backup = AM;
2875349cc55cSDimitry Andric     if (!matchVectorAddressRecursively(N.getOperand(0), AM, Depth + 1) &&
2876349cc55cSDimitry Andric         !matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,
2877349cc55cSDimitry Andric                                        Depth + 1))
2878349cc55cSDimitry Andric       return false;
2879349cc55cSDimitry Andric     AM = Backup;
2880349cc55cSDimitry Andric 
2881349cc55cSDimitry Andric     // Try again after commuting the operands.
2882349cc55cSDimitry Andric     if (!matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,
2883349cc55cSDimitry Andric                                        Depth + 1) &&
2884349cc55cSDimitry Andric         !matchVectorAddressRecursively(Handle.getValue().getOperand(0), AM,
2885349cc55cSDimitry Andric                                        Depth + 1))
2886349cc55cSDimitry Andric       return false;
2887349cc55cSDimitry Andric     AM = Backup;
2888349cc55cSDimitry Andric 
2889349cc55cSDimitry Andric     N = Handle.getValue();
2890349cc55cSDimitry Andric     break;
2891349cc55cSDimitry Andric   }
28920b57cec5SDimitry Andric   }
28930b57cec5SDimitry Andric 
28940b57cec5SDimitry Andric   return matchAddressBase(N, AM);
28950b57cec5SDimitry Andric }
28960b57cec5SDimitry Andric 
2897349cc55cSDimitry Andric /// Helper for selectVectorAddr. Handles things that can be folded into a
2898349cc55cSDimitry Andric /// gather/scatter address. The index register and scale should have already
2899349cc55cSDimitry Andric /// been handled.
matchVectorAddress(SDValue N,X86ISelAddressMode & AM)2900349cc55cSDimitry Andric bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
2901349cc55cSDimitry Andric   return matchVectorAddressRecursively(N, AM, 0);
2902349cc55cSDimitry Andric }
2903349cc55cSDimitry Andric 
selectVectorAddr(MemSDNode * Parent,SDValue BasePtr,SDValue IndexOp,SDValue ScaleOp,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)29045ffd83dbSDimitry Andric bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr,
29055ffd83dbSDimitry Andric                                        SDValue IndexOp, SDValue ScaleOp,
29065ffd83dbSDimitry Andric                                        SDValue &Base, SDValue &Scale,
29075ffd83dbSDimitry Andric                                        SDValue &Index, SDValue &Disp,
29085ffd83dbSDimitry Andric                                        SDValue &Segment) {
29090b57cec5SDimitry Andric   X86ISelAddressMode AM;
29101db9f3b2SDimitry Andric   AM.Scale = ScaleOp->getAsZExtVal();
29110b57cec5SDimitry Andric 
29125f757f3fSDimitry Andric   // Attempt to match index patterns, as long as we're not relying on implicit
29135f757f3fSDimitry Andric   // sign-extension, which is performed BEFORE scale.
29145f757f3fSDimitry Andric   if (IndexOp.getScalarValueSizeInBits() == BasePtr.getScalarValueSizeInBits())
29155f757f3fSDimitry Andric     AM.IndexReg = matchIndexRecursively(IndexOp, AM, 0);
29165f757f3fSDimitry Andric   else
29175f757f3fSDimitry Andric     AM.IndexReg = IndexOp;
29185f757f3fSDimitry Andric 
29195ffd83dbSDimitry Andric   unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace();
2920480093f4SDimitry Andric   if (AddrSpace == X86AS::GS)
29210b57cec5SDimitry Andric     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2922480093f4SDimitry Andric   if (AddrSpace == X86AS::FS)
29230b57cec5SDimitry Andric     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2924480093f4SDimitry Andric   if (AddrSpace == X86AS::SS)
29250b57cec5SDimitry Andric     AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
29260b57cec5SDimitry Andric 
29275ffd83dbSDimitry Andric   SDLoc DL(BasePtr);
29285ffd83dbSDimitry Andric   MVT VT = BasePtr.getSimpleValueType();
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   // Try to match into the base and displacement fields.
29315ffd83dbSDimitry Andric   if (matchVectorAddress(BasePtr, AM))
29320b57cec5SDimitry Andric     return false;
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
29350b57cec5SDimitry Andric   return true;
29360b57cec5SDimitry Andric }
29370b57cec5SDimitry Andric 
29380b57cec5SDimitry Andric /// Returns true if it is able to pattern match an addressing mode.
29390b57cec5SDimitry Andric /// It returns the operands which make up the maximal addressing mode it can
29400b57cec5SDimitry Andric /// match by reference.
29410b57cec5SDimitry Andric ///
29420b57cec5SDimitry Andric /// Parent is the parent node of the addr operand that is being matched.  It
29430b57cec5SDimitry Andric /// is always a load, store, atomic node, or null.  It is only null when
29440b57cec5SDimitry Andric /// checking memory operands for inline asm nodes.
selectAddr(SDNode * Parent,SDValue N,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)29450b57cec5SDimitry Andric bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
29460b57cec5SDimitry Andric                                  SDValue &Scale, SDValue &Index,
29470b57cec5SDimitry Andric                                  SDValue &Disp, SDValue &Segment) {
29480b57cec5SDimitry Andric   X86ISelAddressMode AM;
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   if (Parent &&
29510b57cec5SDimitry Andric       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
29520b57cec5SDimitry Andric       // that are not a MemSDNode, and thus don't have proper addrspace info.
29530b57cec5SDimitry Andric       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
29540b57cec5SDimitry Andric       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
29550b57cec5SDimitry Andric       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
29560b57cec5SDimitry Andric       Parent->getOpcode() != X86ISD::ENQCMD && // Fixme
29570b57cec5SDimitry Andric       Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme
29580b57cec5SDimitry Andric       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
29590b57cec5SDimitry Andric       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
29600b57cec5SDimitry Andric     unsigned AddrSpace =
29610b57cec5SDimitry Andric       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
29625ffd83dbSDimitry Andric     if (AddrSpace == X86AS::GS)
29630b57cec5SDimitry Andric       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
29645ffd83dbSDimitry Andric     if (AddrSpace == X86AS::FS)
29650b57cec5SDimitry Andric       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
29665ffd83dbSDimitry Andric     if (AddrSpace == X86AS::SS)
29670b57cec5SDimitry Andric       AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
29680b57cec5SDimitry Andric   }
29690b57cec5SDimitry Andric 
29700b57cec5SDimitry Andric   // Save the DL and VT before calling matchAddress, it can invalidate N.
29710b57cec5SDimitry Andric   SDLoc DL(N);
29720b57cec5SDimitry Andric   MVT VT = N.getSimpleValueType();
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   if (matchAddress(N, AM))
29750b57cec5SDimitry Andric     return false;
29760b57cec5SDimitry Andric 
29770b57cec5SDimitry Andric   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
29780b57cec5SDimitry Andric   return true;
29790b57cec5SDimitry Andric }
29800b57cec5SDimitry Andric 
selectMOV64Imm32(SDValue N,SDValue & Imm)29810b57cec5SDimitry Andric bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
29825678d1d9SDimitry Andric   // Cannot use 32 bit constants to reference objects in kernel/large code
29835678d1d9SDimitry Andric   // model.
29845f757f3fSDimitry Andric   if (TM.getCodeModel() == CodeModel::Kernel ||
29855678d1d9SDimitry Andric       TM.getCodeModel() == CodeModel::Large)
29865f757f3fSDimitry Andric     return false;
29875f757f3fSDimitry Andric 
29880b57cec5SDimitry Andric   // In static codegen with small code model, we can get the address of a label
29890b57cec5SDimitry Andric   // into a register with 'movl'
29900b57cec5SDimitry Andric   if (N->getOpcode() != X86ISD::Wrapper)
29910b57cec5SDimitry Andric     return false;
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric   N = N.getOperand(0);
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric   // At least GNU as does not accept 'movl' for TPOFF relocations.
29960b57cec5SDimitry Andric   // FIXME: We could use 'movl' when we know we are targeting MC.
29970b57cec5SDimitry Andric   if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
29980b57cec5SDimitry Andric     return false;
29990b57cec5SDimitry Andric 
30000b57cec5SDimitry Andric   Imm = N;
30015f757f3fSDimitry Andric   // Small/medium code model can reference non-TargetGlobalAddress objects with
30025f757f3fSDimitry Andric   // 32 bit constants.
30035f757f3fSDimitry Andric   if (N->getOpcode() != ISD::TargetGlobalAddress) {
30045f757f3fSDimitry Andric     return TM.getCodeModel() == CodeModel::Small ||
30055f757f3fSDimitry Andric            TM.getCodeModel() == CodeModel::Medium;
30065f757f3fSDimitry Andric   }
30070b57cec5SDimitry Andric 
30085f757f3fSDimitry Andric   const GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
30095f757f3fSDimitry Andric   if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
30100b57cec5SDimitry Andric     return CR->getUnsignedMax().ult(1ull << 32);
30115f757f3fSDimitry Andric 
30125f757f3fSDimitry Andric   return !TM.isLargeGlobalValue(GV);
30130b57cec5SDimitry Andric }
30140b57cec5SDimitry Andric 
selectLEA64_32Addr(SDValue N,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)30150b57cec5SDimitry Andric bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
30160b57cec5SDimitry Andric                                          SDValue &Scale, SDValue &Index,
30170b57cec5SDimitry Andric                                          SDValue &Disp, SDValue &Segment) {
30180b57cec5SDimitry Andric   // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
30190b57cec5SDimitry Andric   SDLoc DL(N);
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric   if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
30220b57cec5SDimitry Andric     return false;
30230b57cec5SDimitry Andric 
3024bdd1243dSDimitry Andric   auto *RN = dyn_cast<RegisterSDNode>(Base);
30250b57cec5SDimitry Andric   if (RN && RN->getReg() == 0)
30260b57cec5SDimitry Andric     Base = CurDAG->getRegister(0, MVT::i64);
30270b57cec5SDimitry Andric   else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) {
30280b57cec5SDimitry Andric     // Base could already be %rip, particularly in the x32 ABI.
30290b57cec5SDimitry Andric     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
30300b57cec5SDimitry Andric                                                      MVT::i64), 0);
30310b57cec5SDimitry Andric     Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
30320b57cec5SDimitry Andric                                          Base);
30330b57cec5SDimitry Andric   }
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   RN = dyn_cast<RegisterSDNode>(Index);
30360b57cec5SDimitry Andric   if (RN && RN->getReg() == 0)
30370b57cec5SDimitry Andric     Index = CurDAG->getRegister(0, MVT::i64);
30380b57cec5SDimitry Andric   else {
30390b57cec5SDimitry Andric     assert(Index.getValueType() == MVT::i32 &&
30400b57cec5SDimitry Andric            "Expect to be extending 32-bit registers for use in LEA");
30410b57cec5SDimitry Andric     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
30420b57cec5SDimitry Andric                                                      MVT::i64), 0);
30430b57cec5SDimitry Andric     Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
30440b57cec5SDimitry Andric                                           Index);
30450b57cec5SDimitry Andric   }
30460b57cec5SDimitry Andric 
30470b57cec5SDimitry Andric   return true;
30480b57cec5SDimitry Andric }
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric /// Calls SelectAddr and determines if the maximal addressing
30510b57cec5SDimitry Andric /// 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)30520b57cec5SDimitry Andric bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
30530b57cec5SDimitry Andric                                     SDValue &Base, SDValue &Scale,
30540b57cec5SDimitry Andric                                     SDValue &Index, SDValue &Disp,
30550b57cec5SDimitry Andric                                     SDValue &Segment) {
30560b57cec5SDimitry Andric   X86ISelAddressMode AM;
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric   // Save the DL and VT before calling matchAddress, it can invalidate N.
30590b57cec5SDimitry Andric   SDLoc DL(N);
30600b57cec5SDimitry Andric   MVT VT = N.getSimpleValueType();
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
30630b57cec5SDimitry Andric   // segments.
30640b57cec5SDimitry Andric   SDValue Copy = AM.Segment;
30650b57cec5SDimitry Andric   SDValue T = CurDAG->getRegister(0, MVT::i32);
30660b57cec5SDimitry Andric   AM.Segment = T;
30670b57cec5SDimitry Andric   if (matchAddress(N, AM))
30680b57cec5SDimitry Andric     return false;
30690b57cec5SDimitry Andric   assert (T == AM.Segment);
30700b57cec5SDimitry Andric   AM.Segment = Copy;
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric   unsigned Complexity = 0;
30730b57cec5SDimitry Andric   if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())
30740b57cec5SDimitry Andric     Complexity = 1;
30750b57cec5SDimitry Andric   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
30760b57cec5SDimitry Andric     Complexity = 4;
30770b57cec5SDimitry Andric 
30780b57cec5SDimitry Andric   if (AM.IndexReg.getNode())
30790b57cec5SDimitry Andric     Complexity++;
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
30820b57cec5SDimitry Andric   // a simple shift.
30830b57cec5SDimitry Andric   if (AM.Scale > 1)
30840b57cec5SDimitry Andric     Complexity++;
30850b57cec5SDimitry Andric 
30860b57cec5SDimitry Andric   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
30870b57cec5SDimitry Andric   // to a LEA. This is determined with some experimentation but is by no means
30880b57cec5SDimitry Andric   // optimal (especially for code size consideration). LEA is nice because of
30890b57cec5SDimitry Andric   // its three-address nature. Tweak the cost function again when we can run
30900b57cec5SDimitry Andric   // convertToThreeAddress() at register allocation time.
30910b57cec5SDimitry Andric   if (AM.hasSymbolicDisplacement()) {
30920b57cec5SDimitry Andric     // For X86-64, always use LEA to materialize RIP-relative addresses.
30930b57cec5SDimitry Andric     if (Subtarget->is64Bit())
30940b57cec5SDimitry Andric       Complexity = 4;
30950b57cec5SDimitry Andric     else
30960b57cec5SDimitry Andric       Complexity += 2;
30970b57cec5SDimitry Andric   }
30980b57cec5SDimitry Andric 
30990b57cec5SDimitry Andric   // Heuristic: try harder to form an LEA from ADD if the operands set flags.
31000b57cec5SDimitry Andric   // Unlike ADD, LEA does not affect flags, so we will be less likely to require
31010b57cec5SDimitry Andric   // duplicating flag-producing instructions later in the pipeline.
31020b57cec5SDimitry Andric   if (N.getOpcode() == ISD::ADD) {
31030b57cec5SDimitry Andric     auto isMathWithFlags = [](SDValue V) {
31040b57cec5SDimitry Andric       switch (V.getOpcode()) {
31050b57cec5SDimitry Andric       case X86ISD::ADD:
31060b57cec5SDimitry Andric       case X86ISD::SUB:
31070b57cec5SDimitry Andric       case X86ISD::ADC:
31080b57cec5SDimitry Andric       case X86ISD::SBB:
31090b57cec5SDimitry Andric       case X86ISD::SMUL:
31100b57cec5SDimitry Andric       case X86ISD::UMUL:
311181ad6265SDimitry Andric       /* TODO: These opcodes can be added safely, but we may want to justify
311281ad6265SDimitry Andric                their inclusion for different reasons (better for reg-alloc).
31130b57cec5SDimitry Andric       case X86ISD::OR:
31140b57cec5SDimitry Andric       case X86ISD::XOR:
31150b57cec5SDimitry Andric       case X86ISD::AND:
31160b57cec5SDimitry Andric       */
31170b57cec5SDimitry Andric         // Value 1 is the flag output of the node - verify it's not dead.
31180b57cec5SDimitry Andric         return !SDValue(V.getNode(), 1).use_empty();
31190b57cec5SDimitry Andric       default:
31200b57cec5SDimitry Andric         return false;
31210b57cec5SDimitry Andric       }
31220b57cec5SDimitry Andric     };
312381ad6265SDimitry Andric     // TODO: We might want to factor in whether there's a load folding
312481ad6265SDimitry Andric     // opportunity for the math op that disappears with LEA.
312581ad6265SDimitry Andric     if (isMathWithFlags(N.getOperand(0)) || isMathWithFlags(N.getOperand(1)))
31260b57cec5SDimitry Andric       Complexity++;
31270b57cec5SDimitry Andric   }
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric   if (AM.Disp)
31300b57cec5SDimitry Andric     Complexity++;
31310b57cec5SDimitry Andric 
31320b57cec5SDimitry Andric   // If it isn't worth using an LEA, reject it.
31330b57cec5SDimitry Andric   if (Complexity <= 2)
31340b57cec5SDimitry Andric     return false;
31350b57cec5SDimitry Andric 
31360b57cec5SDimitry Andric   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
31370b57cec5SDimitry Andric   return true;
31380b57cec5SDimitry Andric }
31390b57cec5SDimitry Andric 
31400b57cec5SDimitry Andric /// This is only run on TargetGlobalTLSAddress nodes.
selectTLSADDRAddr(SDValue N,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)31410b57cec5SDimitry Andric bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
31420b57cec5SDimitry Andric                                         SDValue &Scale, SDValue &Index,
31430b57cec5SDimitry Andric                                         SDValue &Disp, SDValue &Segment) {
3144*0fca6ea1SDimitry Andric   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress ||
3145*0fca6ea1SDimitry Andric          N.getOpcode() == ISD::TargetExternalSymbol);
31460b57cec5SDimitry Andric 
31470b57cec5SDimitry Andric   X86ISelAddressMode AM;
3148*0fca6ea1SDimitry Andric   if (auto *GA = dyn_cast<GlobalAddressSDNode>(N)) {
31490b57cec5SDimitry Andric     AM.GV = GA->getGlobal();
31500b57cec5SDimitry Andric     AM.Disp += GA->getOffset();
31510b57cec5SDimitry Andric     AM.SymbolFlags = GA->getTargetFlags();
3152*0fca6ea1SDimitry Andric   } else {
3153*0fca6ea1SDimitry Andric     auto *SA = cast<ExternalSymbolSDNode>(N);
3154*0fca6ea1SDimitry Andric     AM.ES = SA->getSymbol();
3155*0fca6ea1SDimitry Andric     AM.SymbolFlags = SA->getTargetFlags();
3156*0fca6ea1SDimitry Andric   }
31570b57cec5SDimitry Andric 
3158e8d8bef9SDimitry Andric   if (Subtarget->is32Bit()) {
31590b57cec5SDimitry Andric     AM.Scale = 1;
31600b57cec5SDimitry Andric     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
31610b57cec5SDimitry Andric   }
31620b57cec5SDimitry Andric 
3163e8d8bef9SDimitry Andric   MVT VT = N.getSimpleValueType();
31640b57cec5SDimitry Andric   getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);
31650b57cec5SDimitry Andric   return true;
31660b57cec5SDimitry Andric }
31670b57cec5SDimitry Andric 
selectRelocImm(SDValue N,SDValue & Op)31680b57cec5SDimitry Andric bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
31690b57cec5SDimitry Andric   // Keep track of the original value type and whether this value was
31700b57cec5SDimitry Andric   // truncated. If we see a truncation from pointer type to VT that truncates
31710b57cec5SDimitry Andric   // bits that are known to be zero, we can use a narrow reference.
31720b57cec5SDimitry Andric   EVT VT = N.getValueType();
31730b57cec5SDimitry Andric   bool WasTruncated = false;
31740b57cec5SDimitry Andric   if (N.getOpcode() == ISD::TRUNCATE) {
31750b57cec5SDimitry Andric     WasTruncated = true;
31760b57cec5SDimitry Andric     N = N.getOperand(0);
31770b57cec5SDimitry Andric   }
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric   if (N.getOpcode() != X86ISD::Wrapper)
31800b57cec5SDimitry Andric     return false;
31810b57cec5SDimitry Andric 
31820b57cec5SDimitry Andric   // We can only use non-GlobalValues as immediates if they were not truncated,
31830b57cec5SDimitry Andric   // as we do not have any range information. If we have a GlobalValue and the
31840b57cec5SDimitry Andric   // address was not truncated, we can select it as an operand directly.
31850b57cec5SDimitry Andric   unsigned Opc = N.getOperand(0)->getOpcode();
31860b57cec5SDimitry Andric   if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
31870b57cec5SDimitry Andric     Op = N.getOperand(0);
31880b57cec5SDimitry Andric     // We can only select the operand directly if we didn't have to look past a
31890b57cec5SDimitry Andric     // truncate.
31900b57cec5SDimitry Andric     return !WasTruncated;
31910b57cec5SDimitry Andric   }
31920b57cec5SDimitry Andric 
31930b57cec5SDimitry Andric   // Check that the global's range fits into VT.
31940b57cec5SDimitry Andric   auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
3195bdd1243dSDimitry Andric   std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
31960b57cec5SDimitry Andric   if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
31970b57cec5SDimitry Andric     return false;
31980b57cec5SDimitry Andric 
31990b57cec5SDimitry Andric   // Okay, we can use a narrow reference.
32000b57cec5SDimitry Andric   Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
32010b57cec5SDimitry Andric                                       GA->getOffset(), GA->getTargetFlags());
32020b57cec5SDimitry Andric   return true;
32030b57cec5SDimitry Andric }
32040b57cec5SDimitry Andric 
tryFoldLoad(SDNode * Root,SDNode * P,SDValue N,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)32050b57cec5SDimitry Andric bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
32060b57cec5SDimitry Andric                                   SDValue &Base, SDValue &Scale,
32070b57cec5SDimitry Andric                                   SDValue &Index, SDValue &Disp,
32080b57cec5SDimitry Andric                                   SDValue &Segment) {
32098bcb0991SDimitry Andric   assert(Root && P && "Unknown root/parent nodes");
32100b57cec5SDimitry Andric   if (!ISD::isNON_EXTLoad(N.getNode()) ||
32110b57cec5SDimitry Andric       !IsProfitableToFold(N, P, Root) ||
32120b57cec5SDimitry Andric       !IsLegalToFold(N, P, Root, OptLevel))
32130b57cec5SDimitry Andric     return false;
32140b57cec5SDimitry Andric 
32150b57cec5SDimitry Andric   return selectAddr(N.getNode(),
32160b57cec5SDimitry Andric                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
32170b57cec5SDimitry Andric }
32180b57cec5SDimitry Andric 
tryFoldBroadcast(SDNode * Root,SDNode * P,SDValue N,SDValue & Base,SDValue & Scale,SDValue & Index,SDValue & Disp,SDValue & Segment)32198bcb0991SDimitry Andric bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
32208bcb0991SDimitry Andric                                        SDValue &Base, SDValue &Scale,
32218bcb0991SDimitry Andric                                        SDValue &Index, SDValue &Disp,
32228bcb0991SDimitry Andric                                        SDValue &Segment) {
32238bcb0991SDimitry Andric   assert(Root && P && "Unknown root/parent nodes");
32248bcb0991SDimitry Andric   if (N->getOpcode() != X86ISD::VBROADCAST_LOAD ||
32258bcb0991SDimitry Andric       !IsProfitableToFold(N, P, Root) ||
32268bcb0991SDimitry Andric       !IsLegalToFold(N, P, Root, OptLevel))
32278bcb0991SDimitry Andric     return false;
32288bcb0991SDimitry Andric 
32298bcb0991SDimitry Andric   return selectAddr(N.getNode(),
32308bcb0991SDimitry Andric                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
32318bcb0991SDimitry Andric }
32328bcb0991SDimitry Andric 
32330b57cec5SDimitry Andric /// Return an SDNode that returns the value of the global base register.
32340b57cec5SDimitry Andric /// Output instructions required to initialize the global base register,
32350b57cec5SDimitry Andric /// if necessary.
getGlobalBaseReg()32360b57cec5SDimitry Andric SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
32370b57cec5SDimitry Andric   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
32380b57cec5SDimitry Andric   auto &DL = MF->getDataLayout();
32390b57cec5SDimitry Andric   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
32400b57cec5SDimitry Andric }
32410b57cec5SDimitry Andric 
isSExtAbsoluteSymbolRef(unsigned Width,SDNode * N) const32420b57cec5SDimitry Andric bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
32430b57cec5SDimitry Andric   if (N->getOpcode() == ISD::TRUNCATE)
32440b57cec5SDimitry Andric     N = N->getOperand(0).getNode();
32450b57cec5SDimitry Andric   if (N->getOpcode() != X86ISD::Wrapper)
32460b57cec5SDimitry Andric     return false;
32470b57cec5SDimitry Andric 
32480b57cec5SDimitry Andric   auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
32490b57cec5SDimitry Andric   if (!GA)
32500b57cec5SDimitry Andric     return false;
32510b57cec5SDimitry Andric 
32527a6dacacSDimitry Andric   auto *GV = GA->getGlobal();
32537a6dacacSDimitry Andric   std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange();
32547a6dacacSDimitry Andric   if (CR)
3255e8d8bef9SDimitry Andric     return CR->getSignedMin().sge(-1ull << Width) &&
32560b57cec5SDimitry Andric            CR->getSignedMax().slt(1ull << Width);
32577a6dacacSDimitry Andric   // In the kernel code model, globals are in the negative 2GB of the address
32587a6dacacSDimitry Andric   // space, so globals can be a sign extended 32-bit immediate.
32597a6dacacSDimitry Andric   // In other code models, small globals are in the low 2GB of the address
32607a6dacacSDimitry Andric   // space, so sign extending them is equivalent to zero extending them.
32617a6dacacSDimitry Andric   return Width == 32 && !TM.isLargeGlobalValue(GV);
32620b57cec5SDimitry Andric }
32630b57cec5SDimitry Andric 
getCondFromNode(SDNode * N) const326481ad6265SDimitry Andric X86::CondCode X86DAGToDAGISel::getCondFromNode(SDNode *N) const {
32650b57cec5SDimitry Andric   assert(N->isMachineOpcode() && "Unexpected node");
32660b57cec5SDimitry Andric   unsigned Opc = N->getMachineOpcode();
326781ad6265SDimitry Andric   const MCInstrDesc &MCID = getInstrInfo()->get(Opc);
326881ad6265SDimitry Andric   int CondNo = X86::getCondSrcNoFromDesc(MCID);
326981ad6265SDimitry Andric   if (CondNo < 0)
327081ad6265SDimitry Andric     return X86::COND_INVALID;
32710b57cec5SDimitry Andric 
327281ad6265SDimitry Andric   return static_cast<X86::CondCode>(N->getConstantOperandVal(CondNo));
32730b57cec5SDimitry Andric }
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric /// Test whether the given X86ISD::CMP node has any users that use a flag
32760b57cec5SDimitry Andric /// other than ZF.
onlyUsesZeroFlag(SDValue Flags) const32770b57cec5SDimitry Andric bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
32780b57cec5SDimitry Andric   // Examine each user of the node.
32790b57cec5SDimitry Andric   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
32800b57cec5SDimitry Andric          UI != UE; ++UI) {
32810b57cec5SDimitry Andric     // Only check things that use the flags.
32820b57cec5SDimitry Andric     if (UI.getUse().getResNo() != Flags.getResNo())
32830b57cec5SDimitry Andric       continue;
32840b57cec5SDimitry Andric     // Only examine CopyToReg uses that copy to EFLAGS.
32850b57cec5SDimitry Andric     if (UI->getOpcode() != ISD::CopyToReg ||
32860b57cec5SDimitry Andric         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
32870b57cec5SDimitry Andric       return false;
32880b57cec5SDimitry Andric     // Examine each user of the CopyToReg use.
32890b57cec5SDimitry Andric     for (SDNode::use_iterator FlagUI = UI->use_begin(),
32900b57cec5SDimitry Andric            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
32910b57cec5SDimitry Andric       // Only examine the Flag result.
32920b57cec5SDimitry Andric       if (FlagUI.getUse().getResNo() != 1) continue;
32930b57cec5SDimitry Andric       // Anything unusual: assume conservatively.
32940b57cec5SDimitry Andric       if (!FlagUI->isMachineOpcode()) return false;
32950b57cec5SDimitry Andric       // Examine the condition code of the user.
32960b57cec5SDimitry Andric       X86::CondCode CC = getCondFromNode(*FlagUI);
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric       switch (CC) {
32990b57cec5SDimitry Andric       // Comparisons which only use the zero flag.
33000b57cec5SDimitry Andric       case X86::COND_E: case X86::COND_NE:
33010b57cec5SDimitry Andric         continue;
33020b57cec5SDimitry Andric       // Anything else: assume conservatively.
33030b57cec5SDimitry Andric       default:
33040b57cec5SDimitry Andric         return false;
33050b57cec5SDimitry Andric       }
33060b57cec5SDimitry Andric     }
33070b57cec5SDimitry Andric   }
33080b57cec5SDimitry Andric   return true;
33090b57cec5SDimitry Andric }
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric /// Test whether the given X86ISD::CMP node has any uses which require the SF
33120b57cec5SDimitry Andric /// flag to be accurate.
hasNoSignFlagUses(SDValue Flags) const33130b57cec5SDimitry Andric bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
33140b57cec5SDimitry Andric   // Examine each user of the node.
33150b57cec5SDimitry Andric   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
33160b57cec5SDimitry Andric          UI != UE; ++UI) {
33170b57cec5SDimitry Andric     // Only check things that use the flags.
33180b57cec5SDimitry Andric     if (UI.getUse().getResNo() != Flags.getResNo())
33190b57cec5SDimitry Andric       continue;
33200b57cec5SDimitry Andric     // Only examine CopyToReg uses that copy to EFLAGS.
33210b57cec5SDimitry Andric     if (UI->getOpcode() != ISD::CopyToReg ||
33220b57cec5SDimitry Andric         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
33230b57cec5SDimitry Andric       return false;
33240b57cec5SDimitry Andric     // Examine each user of the CopyToReg use.
33250b57cec5SDimitry Andric     for (SDNode::use_iterator FlagUI = UI->use_begin(),
33260b57cec5SDimitry Andric            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
33270b57cec5SDimitry Andric       // Only examine the Flag result.
33280b57cec5SDimitry Andric       if (FlagUI.getUse().getResNo() != 1) continue;
33290b57cec5SDimitry Andric       // Anything unusual: assume conservatively.
33300b57cec5SDimitry Andric       if (!FlagUI->isMachineOpcode()) return false;
33310b57cec5SDimitry Andric       // Examine the condition code of the user.
33320b57cec5SDimitry Andric       X86::CondCode CC = getCondFromNode(*FlagUI);
33330b57cec5SDimitry Andric 
33340b57cec5SDimitry Andric       switch (CC) {
33350b57cec5SDimitry Andric       // Comparisons which don't examine the SF flag.
33360b57cec5SDimitry Andric       case X86::COND_A: case X86::COND_AE:
33370b57cec5SDimitry Andric       case X86::COND_B: case X86::COND_BE:
33380b57cec5SDimitry Andric       case X86::COND_E: case X86::COND_NE:
33390b57cec5SDimitry Andric       case X86::COND_O: case X86::COND_NO:
33400b57cec5SDimitry Andric       case X86::COND_P: case X86::COND_NP:
33410b57cec5SDimitry Andric         continue;
33420b57cec5SDimitry Andric       // Anything else: assume conservatively.
33430b57cec5SDimitry Andric       default:
33440b57cec5SDimitry Andric         return false;
33450b57cec5SDimitry Andric       }
33460b57cec5SDimitry Andric     }
33470b57cec5SDimitry Andric   }
33480b57cec5SDimitry Andric   return true;
33490b57cec5SDimitry Andric }
33500b57cec5SDimitry Andric 
mayUseCarryFlag(X86::CondCode CC)33510b57cec5SDimitry Andric static bool mayUseCarryFlag(X86::CondCode CC) {
33520b57cec5SDimitry Andric   switch (CC) {
33530b57cec5SDimitry Andric   // Comparisons which don't examine the CF flag.
33540b57cec5SDimitry Andric   case X86::COND_O: case X86::COND_NO:
33550b57cec5SDimitry Andric   case X86::COND_E: case X86::COND_NE:
33560b57cec5SDimitry Andric   case X86::COND_S: case X86::COND_NS:
33570b57cec5SDimitry Andric   case X86::COND_P: case X86::COND_NP:
33580b57cec5SDimitry Andric   case X86::COND_L: case X86::COND_GE:
33590b57cec5SDimitry Andric   case X86::COND_G: case X86::COND_LE:
33600b57cec5SDimitry Andric     return false;
33610b57cec5SDimitry Andric   // Anything else: assume conservatively.
33620b57cec5SDimitry Andric   default:
33630b57cec5SDimitry Andric     return true;
33640b57cec5SDimitry Andric   }
33650b57cec5SDimitry Andric }
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric /// Test whether the given node which sets flags has any uses which require the
33680b57cec5SDimitry Andric /// CF flag to be accurate.
hasNoCarryFlagUses(SDValue Flags) const33690b57cec5SDimitry Andric  bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
33700b57cec5SDimitry Andric   // Examine each user of the node.
33710b57cec5SDimitry Andric   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
33720b57cec5SDimitry Andric          UI != UE; ++UI) {
33730b57cec5SDimitry Andric     // Only check things that use the flags.
33740b57cec5SDimitry Andric     if (UI.getUse().getResNo() != Flags.getResNo())
33750b57cec5SDimitry Andric       continue;
33760b57cec5SDimitry Andric 
33770b57cec5SDimitry Andric     unsigned UIOpc = UI->getOpcode();
33780b57cec5SDimitry Andric 
33790b57cec5SDimitry Andric     if (UIOpc == ISD::CopyToReg) {
33800b57cec5SDimitry Andric       // Only examine CopyToReg uses that copy to EFLAGS.
33810b57cec5SDimitry Andric       if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
33820b57cec5SDimitry Andric         return false;
33830b57cec5SDimitry Andric       // Examine each user of the CopyToReg use.
33840b57cec5SDimitry Andric       for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
33850b57cec5SDimitry Andric            FlagUI != FlagUE; ++FlagUI) {
33860b57cec5SDimitry Andric         // Only examine the Flag result.
33870b57cec5SDimitry Andric         if (FlagUI.getUse().getResNo() != 1)
33880b57cec5SDimitry Andric           continue;
33890b57cec5SDimitry Andric         // Anything unusual: assume conservatively.
33900b57cec5SDimitry Andric         if (!FlagUI->isMachineOpcode())
33910b57cec5SDimitry Andric           return false;
33920b57cec5SDimitry Andric         // Examine the condition code of the user.
33930b57cec5SDimitry Andric         X86::CondCode CC = getCondFromNode(*FlagUI);
33940b57cec5SDimitry Andric 
33950b57cec5SDimitry Andric         if (mayUseCarryFlag(CC))
33960b57cec5SDimitry Andric           return false;
33970b57cec5SDimitry Andric       }
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric       // This CopyToReg is ok. Move on to the next user.
34000b57cec5SDimitry Andric       continue;
34010b57cec5SDimitry Andric     }
34020b57cec5SDimitry Andric 
34030b57cec5SDimitry Andric     // This might be an unselected node. So look for the pre-isel opcodes that
34040b57cec5SDimitry Andric     // use flags.
34050b57cec5SDimitry Andric     unsigned CCOpNo;
34060b57cec5SDimitry Andric     switch (UIOpc) {
34070b57cec5SDimitry Andric     default:
34080b57cec5SDimitry Andric       // Something unusual. Be conservative.
34090b57cec5SDimitry Andric       return false;
34100b57cec5SDimitry Andric     case X86ISD::SETCC:       CCOpNo = 0; break;
34110b57cec5SDimitry Andric     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
34120b57cec5SDimitry Andric     case X86ISD::CMOV:        CCOpNo = 2; break;
34130b57cec5SDimitry Andric     case X86ISD::BRCOND:      CCOpNo = 2; break;
34140b57cec5SDimitry Andric     }
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric     X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);
34170b57cec5SDimitry Andric     if (mayUseCarryFlag(CC))
34180b57cec5SDimitry Andric       return false;
34190b57cec5SDimitry Andric   }
34200b57cec5SDimitry Andric   return true;
34210b57cec5SDimitry Andric }
34220b57cec5SDimitry Andric 
34230b57cec5SDimitry Andric /// Check whether or not the chain ending in StoreNode is suitable for doing
34240b57cec5SDimitry Andric /// the {load; op; store} to modify transformation.
isFusableLoadOpStorePattern(StoreSDNode * StoreNode,SDValue StoredVal,SelectionDAG * CurDAG,unsigned LoadOpNo,LoadSDNode * & LoadNode,SDValue & InputChain)34250b57cec5SDimitry Andric static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
34260b57cec5SDimitry Andric                                         SDValue StoredVal, SelectionDAG *CurDAG,
34270b57cec5SDimitry Andric                                         unsigned LoadOpNo,
34280b57cec5SDimitry Andric                                         LoadSDNode *&LoadNode,
34290b57cec5SDimitry Andric                                         SDValue &InputChain) {
34300b57cec5SDimitry Andric   // Is the stored value result 0 of the operation?
34310b57cec5SDimitry Andric   if (StoredVal.getResNo() != 0) return false;
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric   // Are there other uses of the operation other than the store?
34340b57cec5SDimitry Andric   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric   // Is the store non-extending and non-indexed?
34370b57cec5SDimitry Andric   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
34380b57cec5SDimitry Andric     return false;
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric   SDValue Load = StoredVal->getOperand(LoadOpNo);
34410b57cec5SDimitry Andric   // Is the stored value a non-extending and non-indexed load?
34420b57cec5SDimitry Andric   if (!ISD::isNormalLoad(Load.getNode())) return false;
34430b57cec5SDimitry Andric 
34440b57cec5SDimitry Andric   // Return LoadNode by reference.
34450b57cec5SDimitry Andric   LoadNode = cast<LoadSDNode>(Load);
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric   // Is store the only read of the loaded value?
34480b57cec5SDimitry Andric   if (!Load.hasOneUse())
34490b57cec5SDimitry Andric     return false;
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   // Is the address of the store the same as the load?
34520b57cec5SDimitry Andric   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
34530b57cec5SDimitry Andric       LoadNode->getOffset() != StoreNode->getOffset())
34540b57cec5SDimitry Andric     return false;
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric   bool FoundLoad = false;
34570b57cec5SDimitry Andric   SmallVector<SDValue, 4> ChainOps;
34580b57cec5SDimitry Andric   SmallVector<const SDNode *, 4> LoopWorklist;
34590b57cec5SDimitry Andric   SmallPtrSet<const SDNode *, 16> Visited;
34600b57cec5SDimitry Andric   const unsigned int Max = 1024;
34610b57cec5SDimitry Andric 
34620b57cec5SDimitry Andric   //  Visualization of Load-Op-Store fusion:
34630b57cec5SDimitry Andric   // -------------------------
34640b57cec5SDimitry Andric   // Legend:
34650b57cec5SDimitry Andric   //    *-lines = Chain operand dependencies.
34660b57cec5SDimitry Andric   //    |-lines = Normal operand dependencies.
34670b57cec5SDimitry Andric   //    Dependencies flow down and right. n-suffix references multiple nodes.
34680b57cec5SDimitry Andric   //
34690b57cec5SDimitry Andric   //        C                        Xn  C
34700b57cec5SDimitry Andric   //        *                         *  *
34710b57cec5SDimitry Andric   //        *                          * *
34720b57cec5SDimitry Andric   //  Xn  A-LD    Yn                    TF         Yn
34730b57cec5SDimitry Andric   //   *    * \   |                       *        |
34740b57cec5SDimitry Andric   //    *   *  \  |                        *       |
34750b57cec5SDimitry Andric   //     *  *   \ |             =>       A--LD_OP_ST
34760b57cec5SDimitry Andric   //      * *    \|                                 \
34770b57cec5SDimitry Andric   //       TF    OP                                  \
34780b57cec5SDimitry Andric   //         *   | \                                  Zn
34790b57cec5SDimitry Andric   //          *  |  \
34800b57cec5SDimitry Andric   //         A-ST    Zn
34810b57cec5SDimitry Andric   //
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric   // This merge induced dependences from: #1: Xn -> LD, OP, Zn
34840b57cec5SDimitry Andric   //                                      #2: Yn -> LD
34850b57cec5SDimitry Andric   //                                      #3: ST -> Zn
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric   // Ensure the transform is safe by checking for the dual
34880b57cec5SDimitry Andric   // dependencies to make sure we do not induce a loop.
34890b57cec5SDimitry Andric 
34900b57cec5SDimitry Andric   // As LD is a predecessor to both OP and ST we can do this by checking:
34910b57cec5SDimitry Andric   //  a). if LD is a predecessor to a member of Xn or Yn.
34920b57cec5SDimitry Andric   //  b). if a Zn is a predecessor to ST.
34930b57cec5SDimitry Andric 
34940b57cec5SDimitry Andric   // However, (b) can only occur through being a chain predecessor to
34950b57cec5SDimitry Andric   // ST, which is the same as Zn being a member or predecessor of Xn,
34960b57cec5SDimitry Andric   // which is a subset of LD being a predecessor of Xn. So it's
34970b57cec5SDimitry Andric   // subsumed by check (a).
34980b57cec5SDimitry Andric 
34990b57cec5SDimitry Andric   SDValue Chain = StoreNode->getChain();
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   // Gather X elements in ChainOps.
35020b57cec5SDimitry Andric   if (Chain == Load.getValue(1)) {
35030b57cec5SDimitry Andric     FoundLoad = true;
35040b57cec5SDimitry Andric     ChainOps.push_back(Load.getOperand(0));
35050b57cec5SDimitry Andric   } else if (Chain.getOpcode() == ISD::TokenFactor) {
35060b57cec5SDimitry Andric     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
35070b57cec5SDimitry Andric       SDValue Op = Chain.getOperand(i);
35080b57cec5SDimitry Andric       if (Op == Load.getValue(1)) {
35090b57cec5SDimitry Andric         FoundLoad = true;
35100b57cec5SDimitry Andric         // Drop Load, but keep its chain. No cycle check necessary.
35110b57cec5SDimitry Andric         ChainOps.push_back(Load.getOperand(0));
35120b57cec5SDimitry Andric         continue;
35130b57cec5SDimitry Andric       }
35140b57cec5SDimitry Andric       LoopWorklist.push_back(Op.getNode());
35150b57cec5SDimitry Andric       ChainOps.push_back(Op);
35160b57cec5SDimitry Andric     }
35170b57cec5SDimitry Andric   }
35180b57cec5SDimitry Andric 
35190b57cec5SDimitry Andric   if (!FoundLoad)
35200b57cec5SDimitry Andric     return false;
35210b57cec5SDimitry Andric 
35220b57cec5SDimitry Andric   // Worklist is currently Xn. Add Yn to worklist.
35230b57cec5SDimitry Andric   for (SDValue Op : StoredVal->ops())
35240b57cec5SDimitry Andric     if (Op.getNode() != LoadNode)
35250b57cec5SDimitry Andric       LoopWorklist.push_back(Op.getNode());
35260b57cec5SDimitry Andric 
35270b57cec5SDimitry Andric   // Check (a) if Load is a predecessor to Xn + Yn
35280b57cec5SDimitry Andric   if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
35290b57cec5SDimitry Andric                                    true))
35300b57cec5SDimitry Andric     return false;
35310b57cec5SDimitry Andric 
35320b57cec5SDimitry Andric   InputChain =
35330b57cec5SDimitry Andric       CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
35340b57cec5SDimitry Andric   return true;
35350b57cec5SDimitry Andric }
35360b57cec5SDimitry Andric 
35370b57cec5SDimitry Andric // Change a chain of {load; op; store} of the same value into a simple op
35380b57cec5SDimitry Andric // through memory of that value, if the uses of the modified value and its
35390b57cec5SDimitry Andric // address are suitable.
35400b57cec5SDimitry Andric //
35410b57cec5SDimitry Andric // The tablegen pattern memory operand pattern is currently not able to match
35420b57cec5SDimitry Andric // the case where the EFLAGS on the original operation are used.
35430b57cec5SDimitry Andric //
35440b57cec5SDimitry Andric // To move this to tablegen, we'll need to improve tablegen to allow flags to
35450b57cec5SDimitry Andric // be transferred from a node in the pattern to the result node, probably with
35460b57cec5SDimitry Andric // a new keyword. For example, we have this
35470b57cec5SDimitry Andric // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
35480b57cec5SDimitry Andric //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
35490b57cec5SDimitry Andric //   (implicit EFLAGS)]>;
35500b57cec5SDimitry Andric // but maybe need something like this
35510b57cec5SDimitry Andric // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
35520b57cec5SDimitry Andric //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
35530b57cec5SDimitry Andric //   (transferrable EFLAGS)]>;
35540b57cec5SDimitry Andric //
35550b57cec5SDimitry Andric // Until then, we manually fold these and instruction select the operation
35560b57cec5SDimitry Andric // here.
foldLoadStoreIntoMemOperand(SDNode * Node)35570b57cec5SDimitry Andric bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
3558bdd1243dSDimitry Andric   auto *StoreNode = cast<StoreSDNode>(Node);
35590b57cec5SDimitry Andric   SDValue StoredVal = StoreNode->getOperand(1);
35600b57cec5SDimitry Andric   unsigned Opc = StoredVal->getOpcode();
35610b57cec5SDimitry Andric 
35620b57cec5SDimitry Andric   // Before we try to select anything, make sure this is memory operand size
35630b57cec5SDimitry Andric   // and opcode we can handle. Note that this must match the code below that
35640b57cec5SDimitry Andric   // actually lowers the opcodes.
35650b57cec5SDimitry Andric   EVT MemVT = StoreNode->getMemoryVT();
35660b57cec5SDimitry Andric   if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
35670b57cec5SDimitry Andric       MemVT != MVT::i8)
35680b57cec5SDimitry Andric     return false;
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   bool IsCommutable = false;
35710b57cec5SDimitry Andric   bool IsNegate = false;
35720b57cec5SDimitry Andric   switch (Opc) {
35730b57cec5SDimitry Andric   default:
35740b57cec5SDimitry Andric     return false;
35750b57cec5SDimitry Andric   case X86ISD::SUB:
35760b57cec5SDimitry Andric     IsNegate = isNullConstant(StoredVal.getOperand(0));
35770b57cec5SDimitry Andric     break;
35780b57cec5SDimitry Andric   case X86ISD::SBB:
35790b57cec5SDimitry Andric     break;
35800b57cec5SDimitry Andric   case X86ISD::ADD:
35810b57cec5SDimitry Andric   case X86ISD::ADC:
35820b57cec5SDimitry Andric   case X86ISD::AND:
35830b57cec5SDimitry Andric   case X86ISD::OR:
35840b57cec5SDimitry Andric   case X86ISD::XOR:
35850b57cec5SDimitry Andric     IsCommutable = true;
35860b57cec5SDimitry Andric     break;
35870b57cec5SDimitry Andric   }
35880b57cec5SDimitry Andric 
35890b57cec5SDimitry Andric   unsigned LoadOpNo = IsNegate ? 1 : 0;
35900b57cec5SDimitry Andric   LoadSDNode *LoadNode = nullptr;
35910b57cec5SDimitry Andric   SDValue InputChain;
35920b57cec5SDimitry Andric   if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
35930b57cec5SDimitry Andric                                    LoadNode, InputChain)) {
35940b57cec5SDimitry Andric     if (!IsCommutable)
35950b57cec5SDimitry Andric       return false;
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric     // This operation is commutable, try the other operand.
35980b57cec5SDimitry Andric     LoadOpNo = 1;
35990b57cec5SDimitry Andric     if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
36000b57cec5SDimitry Andric                                      LoadNode, InputChain))
36010b57cec5SDimitry Andric       return false;
36020b57cec5SDimitry Andric   }
36030b57cec5SDimitry Andric 
36040b57cec5SDimitry Andric   SDValue Base, Scale, Index, Disp, Segment;
36050b57cec5SDimitry Andric   if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
36060b57cec5SDimitry Andric                   Segment))
36070b57cec5SDimitry Andric     return false;
36080b57cec5SDimitry Andric 
36090b57cec5SDimitry Andric   auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
36100b57cec5SDimitry Andric                           unsigned Opc8) {
36110b57cec5SDimitry Andric     switch (MemVT.getSimpleVT().SimpleTy) {
36120b57cec5SDimitry Andric     case MVT::i64:
36130b57cec5SDimitry Andric       return Opc64;
36140b57cec5SDimitry Andric     case MVT::i32:
36150b57cec5SDimitry Andric       return Opc32;
36160b57cec5SDimitry Andric     case MVT::i16:
36170b57cec5SDimitry Andric       return Opc16;
36180b57cec5SDimitry Andric     case MVT::i8:
36190b57cec5SDimitry Andric       return Opc8;
36200b57cec5SDimitry Andric     default:
36210b57cec5SDimitry Andric       llvm_unreachable("Invalid size!");
36220b57cec5SDimitry Andric     }
36230b57cec5SDimitry Andric   };
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric   MachineSDNode *Result;
36260b57cec5SDimitry Andric   switch (Opc) {
36270b57cec5SDimitry Andric   case X86ISD::SUB:
36280b57cec5SDimitry Andric     // Handle negate.
36290b57cec5SDimitry Andric     if (IsNegate) {
36300b57cec5SDimitry Andric       unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,
36310b57cec5SDimitry Andric                                      X86::NEG8m);
36320b57cec5SDimitry Andric       const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
36330b57cec5SDimitry Andric       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
36340b57cec5SDimitry Andric                                       MVT::Other, Ops);
36350b57cec5SDimitry Andric       break;
36360b57cec5SDimitry Andric     }
3637bdd1243dSDimitry Andric    [[fallthrough]];
36380b57cec5SDimitry Andric   case X86ISD::ADD:
36390b57cec5SDimitry Andric     // Try to match inc/dec.
3640480093f4SDimitry Andric     if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) {
36410b57cec5SDimitry Andric       bool IsOne = isOneConstant(StoredVal.getOperand(1));
36420b57cec5SDimitry Andric       bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
36430b57cec5SDimitry Andric       // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
36440b57cec5SDimitry Andric       if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
36450b57cec5SDimitry Andric         unsigned NewOpc =
36460b57cec5SDimitry Andric           ((Opc == X86ISD::ADD) == IsOne)
36470b57cec5SDimitry Andric               ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
36480b57cec5SDimitry Andric               : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
36490b57cec5SDimitry Andric         const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
36500b57cec5SDimitry Andric         Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
36510b57cec5SDimitry Andric                                         MVT::Other, Ops);
36520b57cec5SDimitry Andric         break;
36530b57cec5SDimitry Andric       }
36540b57cec5SDimitry Andric     }
3655bdd1243dSDimitry Andric     [[fallthrough]];
36560b57cec5SDimitry Andric   case X86ISD::ADC:
36570b57cec5SDimitry Andric   case X86ISD::SBB:
36580b57cec5SDimitry Andric   case X86ISD::AND:
36590b57cec5SDimitry Andric   case X86ISD::OR:
36600b57cec5SDimitry Andric   case X86ISD::XOR: {
36610b57cec5SDimitry Andric     auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
36620b57cec5SDimitry Andric       switch (Opc) {
36630b57cec5SDimitry Andric       case X86ISD::ADD:
36640b57cec5SDimitry Andric         return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
36650b57cec5SDimitry Andric                             X86::ADD8mr);
36660b57cec5SDimitry Andric       case X86ISD::ADC:
36670b57cec5SDimitry Andric         return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
36680b57cec5SDimitry Andric                             X86::ADC8mr);
36690b57cec5SDimitry Andric       case X86ISD::SUB:
36700b57cec5SDimitry Andric         return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
36710b57cec5SDimitry Andric                             X86::SUB8mr);
36720b57cec5SDimitry Andric       case X86ISD::SBB:
36730b57cec5SDimitry Andric         return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
36740b57cec5SDimitry Andric                             X86::SBB8mr);
36750b57cec5SDimitry Andric       case X86ISD::AND:
36760b57cec5SDimitry Andric         return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
36770b57cec5SDimitry Andric                             X86::AND8mr);
36780b57cec5SDimitry Andric       case X86ISD::OR:
36790b57cec5SDimitry Andric         return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
36800b57cec5SDimitry Andric       case X86ISD::XOR:
36810b57cec5SDimitry Andric         return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
36820b57cec5SDimitry Andric                             X86::XOR8mr);
36830b57cec5SDimitry Andric       default:
36840b57cec5SDimitry Andric         llvm_unreachable("Invalid opcode!");
36850b57cec5SDimitry Andric       }
36860b57cec5SDimitry Andric     };
36870b57cec5SDimitry Andric     auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
36880b57cec5SDimitry Andric       switch (Opc) {
36890b57cec5SDimitry Andric       case X86ISD::ADD:
36900b57cec5SDimitry Andric         return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
36910b57cec5SDimitry Andric                             X86::ADD8mi);
36920b57cec5SDimitry Andric       case X86ISD::ADC:
36930b57cec5SDimitry Andric         return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
36940b57cec5SDimitry Andric                             X86::ADC8mi);
36950b57cec5SDimitry Andric       case X86ISD::SUB:
36960b57cec5SDimitry Andric         return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
36970b57cec5SDimitry Andric                             X86::SUB8mi);
36980b57cec5SDimitry Andric       case X86ISD::SBB:
36990b57cec5SDimitry Andric         return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
37000b57cec5SDimitry Andric                             X86::SBB8mi);
37010b57cec5SDimitry Andric       case X86ISD::AND:
37020b57cec5SDimitry Andric         return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
37030b57cec5SDimitry Andric                             X86::AND8mi);
37040b57cec5SDimitry Andric       case X86ISD::OR:
37050b57cec5SDimitry Andric         return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
37060b57cec5SDimitry Andric                             X86::OR8mi);
37070b57cec5SDimitry Andric       case X86ISD::XOR:
37080b57cec5SDimitry Andric         return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
37090b57cec5SDimitry Andric                             X86::XOR8mi);
37100b57cec5SDimitry Andric       default:
37110b57cec5SDimitry Andric         llvm_unreachable("Invalid opcode!");
37120b57cec5SDimitry Andric       }
37130b57cec5SDimitry Andric     };
37140b57cec5SDimitry Andric 
37150b57cec5SDimitry Andric     unsigned NewOpc = SelectRegOpcode(Opc);
37160b57cec5SDimitry Andric     SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
37170b57cec5SDimitry Andric 
37180b57cec5SDimitry Andric     // See if the operand is a constant that we can fold into an immediate
37190b57cec5SDimitry Andric     // operand.
37200b57cec5SDimitry Andric     if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
37210b57cec5SDimitry Andric       int64_t OperandV = OperandC->getSExtValue();
37220b57cec5SDimitry Andric 
37230b57cec5SDimitry Andric       // Check if we can shrink the operand enough to fit in an immediate (or
37240b57cec5SDimitry Andric       // fit into a smaller immediate) by negating it and switching the
37250b57cec5SDimitry Andric       // operation.
37260b57cec5SDimitry Andric       if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
37270b57cec5SDimitry Andric           ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||
37280b57cec5SDimitry Andric            (MemVT == MVT::i64 && !isInt<32>(OperandV) &&
37290b57cec5SDimitry Andric             isInt<32>(-OperandV))) &&
37300b57cec5SDimitry Andric           hasNoCarryFlagUses(StoredVal.getValue(1))) {
37310b57cec5SDimitry Andric         OperandV = -OperandV;
37320b57cec5SDimitry Andric         Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
37330b57cec5SDimitry Andric       }
37340b57cec5SDimitry Andric 
373506c3fb27SDimitry Andric       if (MemVT != MVT::i64 || isInt<32>(OperandV)) {
37360b57cec5SDimitry Andric         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
37370b57cec5SDimitry Andric         NewOpc = SelectImmOpcode(Opc);
37380b57cec5SDimitry Andric       }
37390b57cec5SDimitry Andric     }
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric     if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
37420b57cec5SDimitry Andric       SDValue CopyTo =
37430b57cec5SDimitry Andric           CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
37440b57cec5SDimitry Andric                                StoredVal.getOperand(2), SDValue());
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric       const SDValue Ops[] = {Base,    Scale,   Index,  Disp,
37470b57cec5SDimitry Andric                              Segment, Operand, CopyTo, CopyTo.getValue(1)};
37480b57cec5SDimitry Andric       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
37490b57cec5SDimitry Andric                                       Ops);
37500b57cec5SDimitry Andric     } else {
37510b57cec5SDimitry Andric       const SDValue Ops[] = {Base,    Scale,   Index,     Disp,
37520b57cec5SDimitry Andric                              Segment, Operand, InputChain};
37530b57cec5SDimitry Andric       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
37540b57cec5SDimitry Andric                                       Ops);
37550b57cec5SDimitry Andric     }
37560b57cec5SDimitry Andric     break;
37570b57cec5SDimitry Andric   }
37580b57cec5SDimitry Andric   default:
37590b57cec5SDimitry Andric     llvm_unreachable("Invalid opcode!");
37600b57cec5SDimitry Andric   }
37610b57cec5SDimitry Andric 
37620b57cec5SDimitry Andric   MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
37630b57cec5SDimitry Andric                                  LoadNode->getMemOperand()};
37640b57cec5SDimitry Andric   CurDAG->setNodeMemRefs(Result, MemOps);
37650b57cec5SDimitry Andric 
37660b57cec5SDimitry Andric   // Update Load Chain uses as well.
37670b57cec5SDimitry Andric   ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
37680b57cec5SDimitry Andric   ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
37690b57cec5SDimitry Andric   ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
37700b57cec5SDimitry Andric   CurDAG->RemoveDeadNode(Node);
37710b57cec5SDimitry Andric   return true;
37720b57cec5SDimitry Andric }
37730b57cec5SDimitry Andric 
37740b57cec5SDimitry Andric // See if this is an  X & Mask  that we can match to BEXTR/BZHI.
37750b57cec5SDimitry Andric // Where Mask is one of the following patterns:
37760b57cec5SDimitry Andric //   a) x &  (1 << nbits) - 1
37770b57cec5SDimitry Andric //   b) x & ~(-1 << nbits)
37780b57cec5SDimitry Andric //   c) x &  (-1 >> (32 - y))
37790b57cec5SDimitry Andric //   d) x << (32 - y) >> (32 - y)
378006c3fb27SDimitry Andric //   e) (1 << nbits) - 1
matchBitExtract(SDNode * Node)37810b57cec5SDimitry Andric bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
37820b57cec5SDimitry Andric   assert(
378306c3fb27SDimitry Andric       (Node->getOpcode() == ISD::ADD || Node->getOpcode() == ISD::AND ||
378406c3fb27SDimitry Andric        Node->getOpcode() == ISD::SRL) &&
37850b57cec5SDimitry Andric       "Should be either an and-mask, or right-shift after clearing high bits.");
37860b57cec5SDimitry Andric 
37870b57cec5SDimitry Andric   // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
37880b57cec5SDimitry Andric   if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
37890b57cec5SDimitry Andric     return false;
37900b57cec5SDimitry Andric 
37910b57cec5SDimitry Andric   MVT NVT = Node->getSimpleValueType(0);
37920b57cec5SDimitry Andric 
37930b57cec5SDimitry Andric   // Only supported for 32 and 64 bits.
37940b57cec5SDimitry Andric   if (NVT != MVT::i32 && NVT != MVT::i64)
37950b57cec5SDimitry Andric     return false;
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric   SDValue NBits;
3798349cc55cSDimitry Andric   bool NegateNBits;
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric   // If we have BMI2's BZHI, we are ok with muti-use patterns.
38010b57cec5SDimitry Andric   // Else, if we only have BMI1's BEXTR, we require one-use.
3802349cc55cSDimitry Andric   const bool AllowExtraUsesByDefault = Subtarget->hasBMI2();
3803bdd1243dSDimitry Andric   auto checkUses = [AllowExtraUsesByDefault](
3804bdd1243dSDimitry Andric                        SDValue Op, unsigned NUses,
3805bdd1243dSDimitry Andric                        std::optional<bool> AllowExtraUses) {
380681ad6265SDimitry Andric     return AllowExtraUses.value_or(AllowExtraUsesByDefault) ||
38070b57cec5SDimitry Andric            Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
38080b57cec5SDimitry Andric   };
3809349cc55cSDimitry Andric   auto checkOneUse = [checkUses](SDValue Op,
3810bdd1243dSDimitry Andric                                  std::optional<bool> AllowExtraUses =
3811bdd1243dSDimitry Andric                                      std::nullopt) {
3812349cc55cSDimitry Andric     return checkUses(Op, 1, AllowExtraUses);
3813349cc55cSDimitry Andric   };
3814349cc55cSDimitry Andric   auto checkTwoUse = [checkUses](SDValue Op,
3815bdd1243dSDimitry Andric                                  std::optional<bool> AllowExtraUses =
3816bdd1243dSDimitry Andric                                      std::nullopt) {
3817349cc55cSDimitry Andric     return checkUses(Op, 2, AllowExtraUses);
3818349cc55cSDimitry Andric   };
38190b57cec5SDimitry Andric 
38200b57cec5SDimitry Andric   auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) {
38210b57cec5SDimitry Andric     if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) {
38220b57cec5SDimitry Andric       assert(V.getSimpleValueType() == MVT::i32 &&
38230b57cec5SDimitry Andric              V.getOperand(0).getSimpleValueType() == MVT::i64 &&
38240b57cec5SDimitry Andric              "Expected i64 -> i32 truncation");
38250b57cec5SDimitry Andric       V = V.getOperand(0);
38260b57cec5SDimitry Andric     }
38270b57cec5SDimitry Andric     return V;
38280b57cec5SDimitry Andric   };
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric   // a) x & ((1 << nbits) + (-1))
3831349cc55cSDimitry Andric   auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation, &NBits,
3832349cc55cSDimitry Andric                         &NegateNBits](SDValue Mask) -> bool {
38330b57cec5SDimitry Andric     // Match `add`. Must only have one use!
38340b57cec5SDimitry Andric     if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
38350b57cec5SDimitry Andric       return false;
38360b57cec5SDimitry Andric     // We should be adding all-ones constant (i.e. subtracting one.)
38370b57cec5SDimitry Andric     if (!isAllOnesConstant(Mask->getOperand(1)))
38380b57cec5SDimitry Andric       return false;
38390b57cec5SDimitry Andric     // Match `1 << nbits`. Might be truncated. Must only have one use!
38400b57cec5SDimitry Andric     SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
38410b57cec5SDimitry Andric     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
38420b57cec5SDimitry Andric       return false;
38430b57cec5SDimitry Andric     if (!isOneConstant(M0->getOperand(0)))
38440b57cec5SDimitry Andric       return false;
38450b57cec5SDimitry Andric     NBits = M0->getOperand(1);
3846349cc55cSDimitry Andric     NegateNBits = false;
38470b57cec5SDimitry Andric     return true;
38480b57cec5SDimitry Andric   };
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric   auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) {
38510b57cec5SDimitry Andric     V = peekThroughOneUseTruncation(V);
38520b57cec5SDimitry Andric     return CurDAG->MaskedValueIsAllOnes(
38530b57cec5SDimitry Andric         V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(),
38540b57cec5SDimitry Andric                                 NVT.getSizeInBits()));
38550b57cec5SDimitry Andric   };
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric   // b) x & ~(-1 << nbits)
38580b57cec5SDimitry Andric   auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation,
3859349cc55cSDimitry Andric                         &NBits, &NegateNBits](SDValue Mask) -> bool {
38600b57cec5SDimitry Andric     // Match `~()`. Must only have one use!
38610b57cec5SDimitry Andric     if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask))
38620b57cec5SDimitry Andric       return false;
38630b57cec5SDimitry Andric     // The -1 only has to be all-ones for the final Node's NVT.
38640b57cec5SDimitry Andric     if (!isAllOnes(Mask->getOperand(1)))
38650b57cec5SDimitry Andric       return false;
38660b57cec5SDimitry Andric     // Match `-1 << nbits`. Might be truncated. Must only have one use!
38670b57cec5SDimitry Andric     SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
38680b57cec5SDimitry Andric     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
38690b57cec5SDimitry Andric       return false;
38700b57cec5SDimitry Andric     // The -1 only has to be all-ones for the final Node's NVT.
38710b57cec5SDimitry Andric     if (!isAllOnes(M0->getOperand(0)))
38720b57cec5SDimitry Andric       return false;
38730b57cec5SDimitry Andric     NBits = M0->getOperand(1);
3874349cc55cSDimitry Andric     NegateNBits = false;
38750b57cec5SDimitry Andric     return true;
38760b57cec5SDimitry Andric   };
38770b57cec5SDimitry Andric 
3878349cc55cSDimitry Andric   // Try to match potentially-truncated shift amount as `(bitwidth - y)`,
3879349cc55cSDimitry Andric   // or leave the shift amount as-is, but then we'll have to negate it.
3880349cc55cSDimitry Andric   auto canonicalizeShiftAmt = [&NBits, &NegateNBits](SDValue ShiftAmt,
38810b57cec5SDimitry Andric                                                      unsigned Bitwidth) {
3882349cc55cSDimitry Andric     NBits = ShiftAmt;
3883349cc55cSDimitry Andric     NegateNBits = true;
3884349cc55cSDimitry Andric     // Skip over a truncate of the shift amount, if any.
3885349cc55cSDimitry Andric     if (NBits.getOpcode() == ISD::TRUNCATE)
3886349cc55cSDimitry Andric       NBits = NBits.getOperand(0);
3887349cc55cSDimitry Andric     // Try to match the shift amount as (bitwidth - y). It should go away, too.
3888349cc55cSDimitry Andric     // If it doesn't match, that's fine, we'll just negate it ourselves.
3889349cc55cSDimitry Andric     if (NBits.getOpcode() != ISD::SUB)
3890349cc55cSDimitry Andric       return;
3891349cc55cSDimitry Andric     auto *V0 = dyn_cast<ConstantSDNode>(NBits.getOperand(0));
38920b57cec5SDimitry Andric     if (!V0 || V0->getZExtValue() != Bitwidth)
3893349cc55cSDimitry Andric       return;
3894349cc55cSDimitry Andric     NBits = NBits.getOperand(1);
3895349cc55cSDimitry Andric     NegateNBits = false;
38960b57cec5SDimitry Andric   };
38970b57cec5SDimitry Andric 
3898349cc55cSDimitry Andric   // c) x &  (-1 >> z)  but then we'll have to subtract z from bitwidth
3899349cc55cSDimitry Andric   //   or
39000b57cec5SDimitry Andric   // c) x &  (-1 >> (32 - y))
3901349cc55cSDimitry Andric   auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation, &NegateNBits,
3902349cc55cSDimitry Andric                         canonicalizeShiftAmt](SDValue Mask) -> bool {
39030b57cec5SDimitry Andric     // The mask itself may be truncated.
39040b57cec5SDimitry Andric     Mask = peekThroughOneUseTruncation(Mask);
39050b57cec5SDimitry Andric     unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits();
39060b57cec5SDimitry Andric     // Match `l>>`. Must only have one use!
39070b57cec5SDimitry Andric     if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
39080b57cec5SDimitry Andric       return false;
39090b57cec5SDimitry Andric     // We should be shifting truly all-ones constant.
39100b57cec5SDimitry Andric     if (!isAllOnesConstant(Mask.getOperand(0)))
39110b57cec5SDimitry Andric       return false;
39120b57cec5SDimitry Andric     SDValue M1 = Mask.getOperand(1);
39130b57cec5SDimitry Andric     // The shift amount should not be used externally.
39140b57cec5SDimitry Andric     if (!checkOneUse(M1))
39150b57cec5SDimitry Andric       return false;
3916349cc55cSDimitry Andric     canonicalizeShiftAmt(M1, Bitwidth);
3917349cc55cSDimitry Andric     // Pattern c. is non-canonical, and is expanded into pattern d. iff there
3918349cc55cSDimitry Andric     // is no extra use of the mask. Clearly, there was one since we are here.
3919349cc55cSDimitry Andric     // But at the same time, if we need to negate the shift amount,
3920349cc55cSDimitry Andric     // then we don't want the mask to stick around, else it's unprofitable.
3921349cc55cSDimitry Andric     return !NegateNBits;
39220b57cec5SDimitry Andric   };
39230b57cec5SDimitry Andric 
39240b57cec5SDimitry Andric   SDValue X;
39250b57cec5SDimitry Andric 
3926349cc55cSDimitry Andric   // d) x << z >> z  but then we'll have to subtract z from bitwidth
3927349cc55cSDimitry Andric   //   or
39280b57cec5SDimitry Andric   // d) x << (32 - y) >> (32 - y)
3929349cc55cSDimitry Andric   auto matchPatternD = [checkOneUse, checkTwoUse, canonicalizeShiftAmt,
3930349cc55cSDimitry Andric                         AllowExtraUsesByDefault, &NegateNBits,
39310b57cec5SDimitry Andric                         &X](SDNode *Node) -> bool {
39320b57cec5SDimitry Andric     if (Node->getOpcode() != ISD::SRL)
39330b57cec5SDimitry Andric       return false;
39340b57cec5SDimitry Andric     SDValue N0 = Node->getOperand(0);
3935349cc55cSDimitry Andric     if (N0->getOpcode() != ISD::SHL)
39360b57cec5SDimitry Andric       return false;
39370b57cec5SDimitry Andric     unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits();
39380b57cec5SDimitry Andric     SDValue N1 = Node->getOperand(1);
39390b57cec5SDimitry Andric     SDValue N01 = N0->getOperand(1);
39400b57cec5SDimitry Andric     // Both of the shifts must be by the exact same value.
3941349cc55cSDimitry Andric     if (N1 != N01)
39420b57cec5SDimitry Andric       return false;
3943349cc55cSDimitry Andric     canonicalizeShiftAmt(N1, Bitwidth);
3944349cc55cSDimitry Andric     // There should not be any external uses of the inner shift / shift amount.
3945349cc55cSDimitry Andric     // Note that while we are generally okay with external uses given BMI2,
3946349cc55cSDimitry Andric     // iff we need to negate the shift amount, we are not okay with extra uses.
3947349cc55cSDimitry Andric     const bool AllowExtraUses = AllowExtraUsesByDefault && !NegateNBits;
3948349cc55cSDimitry Andric     if (!checkOneUse(N0, AllowExtraUses) || !checkTwoUse(N1, AllowExtraUses))
39490b57cec5SDimitry Andric       return false;
39500b57cec5SDimitry Andric     X = N0->getOperand(0);
39510b57cec5SDimitry Andric     return true;
39520b57cec5SDimitry Andric   };
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric   auto matchLowBitMask = [matchPatternA, matchPatternB,
39550b57cec5SDimitry Andric                           matchPatternC](SDValue Mask) -> bool {
39560b57cec5SDimitry Andric     return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
39570b57cec5SDimitry Andric   };
39580b57cec5SDimitry Andric 
39590b57cec5SDimitry Andric   if (Node->getOpcode() == ISD::AND) {
39600b57cec5SDimitry Andric     X = Node->getOperand(0);
39610b57cec5SDimitry Andric     SDValue Mask = Node->getOperand(1);
39620b57cec5SDimitry Andric 
39630b57cec5SDimitry Andric     if (matchLowBitMask(Mask)) {
39640b57cec5SDimitry Andric       // Great.
39650b57cec5SDimitry Andric     } else {
39660b57cec5SDimitry Andric       std::swap(X, Mask);
39670b57cec5SDimitry Andric       if (!matchLowBitMask(Mask))
39680b57cec5SDimitry Andric         return false;
39690b57cec5SDimitry Andric     }
397006c3fb27SDimitry Andric   } else if (matchLowBitMask(SDValue(Node, 0))) {
397106c3fb27SDimitry Andric     X = CurDAG->getAllOnesConstant(SDLoc(Node), NVT);
39720b57cec5SDimitry Andric   } else if (!matchPatternD(Node))
39730b57cec5SDimitry Andric     return false;
39740b57cec5SDimitry Andric 
3975349cc55cSDimitry Andric   // If we need to negate the shift amount, require BMI2 BZHI support.
3976349cc55cSDimitry Andric   // It's just too unprofitable for BMI1 BEXTR.
3977349cc55cSDimitry Andric   if (NegateNBits && !Subtarget->hasBMI2())
3978349cc55cSDimitry Andric     return false;
3979349cc55cSDimitry Andric 
39800b57cec5SDimitry Andric   SDLoc DL(Node);
39810b57cec5SDimitry Andric 
39820b57cec5SDimitry Andric   // Truncate the shift amount.
39830b57cec5SDimitry Andric   NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
39840b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
39850b57cec5SDimitry Andric 
39860b57cec5SDimitry Andric   // Insert 8-bit NBits into lowest 8 bits of 32-bit register.
39870b57cec5SDimitry Andric   // All the other bits are undefined, we do not care about them.
39880b57cec5SDimitry Andric   SDValue ImplDef = SDValue(
39890b57cec5SDimitry Andric       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);
39900b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric   SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32);
39930b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal);
3994349cc55cSDimitry Andric   NBits = SDValue(CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
3995349cc55cSDimitry Andric                                          MVT::i32, ImplDef, NBits, SRIdxVal),
3996349cc55cSDimitry Andric                   0);
39970b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
39980b57cec5SDimitry Andric 
3999349cc55cSDimitry Andric   // We might have matched the amount of high bits to be cleared,
4000349cc55cSDimitry Andric   // but we want the amount of low bits to be kept, so negate it then.
4001349cc55cSDimitry Andric   if (NegateNBits) {
4002349cc55cSDimitry Andric     SDValue BitWidthC = CurDAG->getConstant(NVT.getSizeInBits(), DL, MVT::i32);
4003349cc55cSDimitry Andric     insertDAGNode(*CurDAG, SDValue(Node, 0), BitWidthC);
4004349cc55cSDimitry Andric 
4005349cc55cSDimitry Andric     NBits = CurDAG->getNode(ISD::SUB, DL, MVT::i32, BitWidthC, NBits);
4006349cc55cSDimitry Andric     insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
4007349cc55cSDimitry Andric   }
4008349cc55cSDimitry Andric 
40090b57cec5SDimitry Andric   if (Subtarget->hasBMI2()) {
40105f757f3fSDimitry Andric     // Great, just emit the BZHI..
40110b57cec5SDimitry Andric     if (NVT != MVT::i32) {
40120b57cec5SDimitry Andric       // But have to place the bit count into the wide-enough register first.
40130b57cec5SDimitry Andric       NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits);
40140b57cec5SDimitry Andric       insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
40150b57cec5SDimitry Andric     }
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric     SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
40180b57cec5SDimitry Andric     ReplaceNode(Node, Extract.getNode());
40190b57cec5SDimitry Andric     SelectCode(Extract.getNode());
40200b57cec5SDimitry Andric     return true;
40210b57cec5SDimitry Andric   }
40220b57cec5SDimitry Andric 
40230b57cec5SDimitry Andric   // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is
40240b57cec5SDimitry Andric   // *logically* shifted (potentially with one-use trunc inbetween),
40250b57cec5SDimitry Andric   // and the truncation was the only use of the shift,
40260b57cec5SDimitry Andric   // and if so look past one-use truncation.
40270b57cec5SDimitry Andric   {
40280b57cec5SDimitry Andric     SDValue RealX = peekThroughOneUseTruncation(X);
40290b57cec5SDimitry Andric     // FIXME: only if the shift is one-use?
40300b57cec5SDimitry Andric     if (RealX != X && RealX.getOpcode() == ISD::SRL)
40310b57cec5SDimitry Andric       X = RealX;
40320b57cec5SDimitry Andric   }
40330b57cec5SDimitry Andric 
40340b57cec5SDimitry Andric   MVT XVT = X.getSimpleValueType();
40350b57cec5SDimitry Andric 
40360b57cec5SDimitry Andric   // Else, emitting BEXTR requires one more step.
40370b57cec5SDimitry Andric   // The 'control' of BEXTR has the pattern of:
40380b57cec5SDimitry Andric   // [15...8 bit][ 7...0 bit] location
40390b57cec5SDimitry Andric   // [ bit count][     shift] name
40400b57cec5SDimitry Andric   // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric   // Shift NBits left by 8 bits, thus producing 'control'.
40430b57cec5SDimitry Andric   // This makes the low 8 bits to be zero.
40440b57cec5SDimitry Andric   SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
404582bf979dSDimitry Andric   insertDAGNode(*CurDAG, SDValue(Node, 0), C8);
40460b57cec5SDimitry Andric   SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);
40470b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric   // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
40500b57cec5SDimitry Andric   // FIXME: only if the shift is one-use?
40510b57cec5SDimitry Andric   if (X.getOpcode() == ISD::SRL) {
40520b57cec5SDimitry Andric     SDValue ShiftAmt = X.getOperand(1);
40530b57cec5SDimitry Andric     X = X.getOperand(0);
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric     assert(ShiftAmt.getValueType() == MVT::i8 &&
40560b57cec5SDimitry Andric            "Expected shift amount to be i8");
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric     // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
40590b57cec5SDimitry Andric     // We could zext to i16 in some form, but we intentionally don't do that.
40600b57cec5SDimitry Andric     SDValue OrigShiftAmt = ShiftAmt;
40610b57cec5SDimitry Andric     ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);
40620b57cec5SDimitry Andric     insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
40630b57cec5SDimitry Andric 
40640b57cec5SDimitry Andric     // And now 'or' these low 8 bits of shift amount into the 'control'.
40650b57cec5SDimitry Andric     Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);
40660b57cec5SDimitry Andric     insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
40670b57cec5SDimitry Andric   }
40680b57cec5SDimitry Andric 
40690b57cec5SDimitry Andric   // But have to place the 'control' into the wide-enough register first.
40700b57cec5SDimitry Andric   if (XVT != MVT::i32) {
40710b57cec5SDimitry Andric     Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);
40720b57cec5SDimitry Andric     insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
40730b57cec5SDimitry Andric   }
40740b57cec5SDimitry Andric 
40750b57cec5SDimitry Andric   // And finally, form the BEXTR itself.
40760b57cec5SDimitry Andric   SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric   // The 'X' was originally truncated. Do that now.
40790b57cec5SDimitry Andric   if (XVT != NVT) {
40800b57cec5SDimitry Andric     insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);
40810b57cec5SDimitry Andric     Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);
40820b57cec5SDimitry Andric   }
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric   ReplaceNode(Node, Extract.getNode());
40850b57cec5SDimitry Andric   SelectCode(Extract.getNode());
40860b57cec5SDimitry Andric 
40870b57cec5SDimitry Andric   return true;
40880b57cec5SDimitry Andric }
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
matchBEXTRFromAndImm(SDNode * Node)40910b57cec5SDimitry Andric MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
40920b57cec5SDimitry Andric   MVT NVT = Node->getSimpleValueType(0);
40930b57cec5SDimitry Andric   SDLoc dl(Node);
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric   SDValue N0 = Node->getOperand(0);
40960b57cec5SDimitry Andric   SDValue N1 = Node->getOperand(1);
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   // If we have TBM we can use an immediate for the control. If we have BMI
40990b57cec5SDimitry Andric   // we should only do this if the BEXTR instruction is implemented well.
41000b57cec5SDimitry Andric   // Otherwise moving the control into a register makes this more costly.
41010b57cec5SDimitry Andric   // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
41020b57cec5SDimitry Andric   // hoisting the move immediate would make it worthwhile with a less optimal
41030b57cec5SDimitry Andric   // BEXTR?
41048bcb0991SDimitry Andric   bool PreferBEXTR =
41058bcb0991SDimitry Andric       Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR());
41068bcb0991SDimitry Andric   if (!PreferBEXTR && !Subtarget->hasBMI2())
41070b57cec5SDimitry Andric     return nullptr;
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric   // Must have a shift right.
41100b57cec5SDimitry Andric   if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
41110b57cec5SDimitry Andric     return nullptr;
41120b57cec5SDimitry Andric 
41130b57cec5SDimitry Andric   // Shift can't have additional users.
41140b57cec5SDimitry Andric   if (!N0->hasOneUse())
41150b57cec5SDimitry Andric     return nullptr;
41160b57cec5SDimitry Andric 
41170b57cec5SDimitry Andric   // Only supported for 32 and 64 bits.
41180b57cec5SDimitry Andric   if (NVT != MVT::i32 && NVT != MVT::i64)
41190b57cec5SDimitry Andric     return nullptr;
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric   // Shift amount and RHS of and must be constant.
4122bdd1243dSDimitry Andric   auto *MaskCst = dyn_cast<ConstantSDNode>(N1);
4123bdd1243dSDimitry Andric   auto *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
41240b57cec5SDimitry Andric   if (!MaskCst || !ShiftCst)
41250b57cec5SDimitry Andric     return nullptr;
41260b57cec5SDimitry Andric 
41270b57cec5SDimitry Andric   // And RHS must be a mask.
41280b57cec5SDimitry Andric   uint64_t Mask = MaskCst->getZExtValue();
41290b57cec5SDimitry Andric   if (!isMask_64(Mask))
41300b57cec5SDimitry Andric     return nullptr;
41310b57cec5SDimitry Andric 
41320b57cec5SDimitry Andric   uint64_t Shift = ShiftCst->getZExtValue();
4133bdd1243dSDimitry Andric   uint64_t MaskSize = llvm::popcount(Mask);
41340b57cec5SDimitry Andric 
41350b57cec5SDimitry Andric   // Don't interfere with something that can be handled by extracting AH.
41360b57cec5SDimitry Andric   // TODO: If we are able to fold a load, BEXTR might still be better than AH.
41370b57cec5SDimitry Andric   if (Shift == 8 && MaskSize == 8)
41380b57cec5SDimitry Andric     return nullptr;
41390b57cec5SDimitry Andric 
41400b57cec5SDimitry Andric   // Make sure we are only using bits that were in the original value, not
41410b57cec5SDimitry Andric   // shifted in.
41420b57cec5SDimitry Andric   if (Shift + MaskSize > NVT.getSizeInBits())
41430b57cec5SDimitry Andric     return nullptr;
41440b57cec5SDimitry Andric 
41458bcb0991SDimitry Andric   // BZHI, if available, is always fast, unlike BEXTR. But even if we decide
41468bcb0991SDimitry Andric   // that we can't use BEXTR, it is only worthwhile using BZHI if the mask
41478bcb0991SDimitry Andric   // does not fit into 32 bits. Load folding is not a sufficient reason.
41488bcb0991SDimitry Andric   if (!PreferBEXTR && MaskSize <= 32)
41498bcb0991SDimitry Andric     return nullptr;
41500b57cec5SDimitry Andric 
41518bcb0991SDimitry Andric   SDValue Control;
41528bcb0991SDimitry Andric   unsigned ROpc, MOpc;
41538bcb0991SDimitry Andric 
41547a6dacacSDimitry Andric #define GET_EGPR_IF_ENABLED(OPC) (Subtarget->hasEGPR() ? OPC##_EVEX : OPC)
41558bcb0991SDimitry Andric   if (!PreferBEXTR) {
41568bcb0991SDimitry Andric     assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then.");
41578bcb0991SDimitry Andric     // If we can't make use of BEXTR then we can't fuse shift+mask stages.
41588bcb0991SDimitry Andric     // Let's perform the mask first, and apply shift later. Note that we need to
41598bcb0991SDimitry Andric     // widen the mask to account for the fact that we'll apply shift afterwards!
41608bcb0991SDimitry Andric     Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT);
41617a6dacacSDimitry Andric     ROpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BZHI64rr)
41627a6dacacSDimitry Andric                            : GET_EGPR_IF_ENABLED(X86::BZHI32rr);
41637a6dacacSDimitry Andric     MOpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BZHI64rm)
41647a6dacacSDimitry Andric                            : GET_EGPR_IF_ENABLED(X86::BZHI32rm);
41658bcb0991SDimitry Andric     unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
41668bcb0991SDimitry Andric     Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
41678bcb0991SDimitry Andric   } else {
41688bcb0991SDimitry Andric     // The 'control' of BEXTR has the pattern of:
41698bcb0991SDimitry Andric     // [15...8 bit][ 7...0 bit] location
41708bcb0991SDimitry Andric     // [ bit count][     shift] name
41718bcb0991SDimitry Andric     // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
41728bcb0991SDimitry Andric     Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
41738bcb0991SDimitry Andric     if (Subtarget->hasTBM()) {
41748bcb0991SDimitry Andric       ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
41758bcb0991SDimitry Andric       MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
41768bcb0991SDimitry Andric     } else {
41778bcb0991SDimitry Andric       assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then.");
41780b57cec5SDimitry Andric       // BMI requires the immediate to placed in a register.
41797a6dacacSDimitry Andric       ROpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BEXTR64rr)
41807a6dacacSDimitry Andric                              : GET_EGPR_IF_ENABLED(X86::BEXTR32rr);
41817a6dacacSDimitry Andric       MOpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BEXTR64rm)
41827a6dacacSDimitry Andric                              : GET_EGPR_IF_ENABLED(X86::BEXTR32rm);
41830b57cec5SDimitry Andric       unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
41848bcb0991SDimitry Andric       Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
41858bcb0991SDimitry Andric     }
41860b57cec5SDimitry Andric   }
41870b57cec5SDimitry Andric 
41880b57cec5SDimitry Andric   MachineSDNode *NewNode;
41890b57cec5SDimitry Andric   SDValue Input = N0->getOperand(0);
41900b57cec5SDimitry Andric   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
41910b57cec5SDimitry Andric   if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
41928bcb0991SDimitry Andric     SDValue Ops[] = {
41938bcb0991SDimitry Andric         Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)};
41940b57cec5SDimitry Andric     SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
41950b57cec5SDimitry Andric     NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
41960b57cec5SDimitry Andric     // Update the chain.
41970b57cec5SDimitry Andric     ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));
41980b57cec5SDimitry Andric     // Record the mem-refs
41990b57cec5SDimitry Andric     CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
42000b57cec5SDimitry Andric   } else {
42018bcb0991SDimitry Andric     NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control);
42028bcb0991SDimitry Andric   }
42038bcb0991SDimitry Andric 
42048bcb0991SDimitry Andric   if (!PreferBEXTR) {
42058bcb0991SDimitry Andric     // We still need to apply the shift.
42068bcb0991SDimitry Andric     SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT);
4207*0fca6ea1SDimitry Andric     unsigned NewOpc = NVT == MVT::i64 ? GET_ND_IF_ENABLED(X86::SHR64ri)
4208*0fca6ea1SDimitry Andric                                       : GET_ND_IF_ENABLED(X86::SHR32ri);
42098bcb0991SDimitry Andric     NewNode =
42108bcb0991SDimitry Andric         CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt);
42110b57cec5SDimitry Andric   }
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric   return NewNode;
42140b57cec5SDimitry Andric }
42150b57cec5SDimitry Andric 
42160b57cec5SDimitry Andric // Emit a PCMISTR(I/M) instruction.
emitPCMPISTR(unsigned ROpc,unsigned MOpc,bool MayFoldLoad,const SDLoc & dl,MVT VT,SDNode * Node)42170b57cec5SDimitry Andric MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
42180b57cec5SDimitry Andric                                              bool MayFoldLoad, const SDLoc &dl,
42190b57cec5SDimitry Andric                                              MVT VT, SDNode *Node) {
42200b57cec5SDimitry Andric   SDValue N0 = Node->getOperand(0);
42210b57cec5SDimitry Andric   SDValue N1 = Node->getOperand(1);
42220b57cec5SDimitry Andric   SDValue Imm = Node->getOperand(2);
4223bdd1243dSDimitry Andric   auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
42240b57cec5SDimitry Andric   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
42250b57cec5SDimitry Andric 
42260b57cec5SDimitry Andric   // Try to fold a load. No need to check alignment.
42270b57cec5SDimitry Andric   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
42280b57cec5SDimitry Andric   if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
42290b57cec5SDimitry Andric     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
42300b57cec5SDimitry Andric                       N1.getOperand(0) };
42310b57cec5SDimitry Andric     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
42320b57cec5SDimitry Andric     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
42330b57cec5SDimitry Andric     // Update the chain.
42340b57cec5SDimitry Andric     ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
42350b57cec5SDimitry Andric     // Record the mem-refs
42360b57cec5SDimitry Andric     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
42370b57cec5SDimitry Andric     return CNode;
42380b57cec5SDimitry Andric   }
42390b57cec5SDimitry Andric 
42400b57cec5SDimitry Andric   SDValue Ops[] = { N0, N1, Imm };
42410b57cec5SDimitry Andric   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
42420b57cec5SDimitry Andric   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
42430b57cec5SDimitry Andric   return CNode;
42440b57cec5SDimitry Andric }
42450b57cec5SDimitry Andric 
42460b57cec5SDimitry Andric // Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
42470b57cec5SDimitry Andric // to emit a second instruction after this one. This is needed since we have two
42480b57cec5SDimitry Andric // 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 & InGlue)42490b57cec5SDimitry Andric MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
42500b57cec5SDimitry Andric                                              bool MayFoldLoad, const SDLoc &dl,
42510b57cec5SDimitry Andric                                              MVT VT, SDNode *Node,
425206c3fb27SDimitry Andric                                              SDValue &InGlue) {
42530b57cec5SDimitry Andric   SDValue N0 = Node->getOperand(0);
42540b57cec5SDimitry Andric   SDValue N2 = Node->getOperand(2);
42550b57cec5SDimitry Andric   SDValue Imm = Node->getOperand(4);
4256bdd1243dSDimitry Andric   auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
42570b57cec5SDimitry Andric   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
42580b57cec5SDimitry Andric 
42590b57cec5SDimitry Andric   // Try to fold a load. No need to check alignment.
42600b57cec5SDimitry Andric   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
42610b57cec5SDimitry Andric   if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
42620b57cec5SDimitry Andric     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
426306c3fb27SDimitry Andric                       N2.getOperand(0), InGlue };
42640b57cec5SDimitry Andric     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
42650b57cec5SDimitry Andric     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
426606c3fb27SDimitry Andric     InGlue = SDValue(CNode, 3);
42670b57cec5SDimitry Andric     // Update the chain.
42680b57cec5SDimitry Andric     ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
42690b57cec5SDimitry Andric     // Record the mem-refs
42700b57cec5SDimitry Andric     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
42710b57cec5SDimitry Andric     return CNode;
42720b57cec5SDimitry Andric   }
42730b57cec5SDimitry Andric 
427406c3fb27SDimitry Andric   SDValue Ops[] = { N0, N2, Imm, InGlue };
42750b57cec5SDimitry Andric   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
42760b57cec5SDimitry Andric   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
427706c3fb27SDimitry Andric   InGlue = SDValue(CNode, 2);
42780b57cec5SDimitry Andric   return CNode;
42790b57cec5SDimitry Andric }
42800b57cec5SDimitry Andric 
tryShiftAmountMod(SDNode * N)42810b57cec5SDimitry Andric bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
42820b57cec5SDimitry Andric   EVT VT = N->getValueType(0);
42830b57cec5SDimitry Andric 
42840b57cec5SDimitry Andric   // Only handle scalar shifts.
42850b57cec5SDimitry Andric   if (VT.isVector())
42860b57cec5SDimitry Andric     return false;
42870b57cec5SDimitry Andric 
42880b57cec5SDimitry Andric   // Narrower shifts only mask to 5 bits in hardware.
42890b57cec5SDimitry Andric   unsigned Size = VT == MVT::i64 ? 64 : 32;
42900b57cec5SDimitry Andric 
42910b57cec5SDimitry Andric   SDValue OrigShiftAmt = N->getOperand(1);
42920b57cec5SDimitry Andric   SDValue ShiftAmt = OrigShiftAmt;
42930b57cec5SDimitry Andric   SDLoc DL(N);
42940b57cec5SDimitry Andric 
42950b57cec5SDimitry Andric   // Skip over a truncate of the shift amount.
42960b57cec5SDimitry Andric   if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
42970b57cec5SDimitry Andric     ShiftAmt = ShiftAmt->getOperand(0);
42980b57cec5SDimitry Andric 
42990b57cec5SDimitry Andric   // This function is called after X86DAGToDAGISel::matchBitExtract(),
43000b57cec5SDimitry Andric   // so we are not afraid that we might mess up BZHI/BEXTR pattern.
43010b57cec5SDimitry Andric 
43020b57cec5SDimitry Andric   SDValue NewShiftAmt;
4303bdd1243dSDimitry Andric   if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB ||
4304bdd1243dSDimitry Andric       ShiftAmt->getOpcode() == ISD::XOR) {
43050b57cec5SDimitry Andric     SDValue Add0 = ShiftAmt->getOperand(0);
43060b57cec5SDimitry Andric     SDValue Add1 = ShiftAmt->getOperand(1);
4307fe6060f1SDimitry Andric     auto *Add0C = dyn_cast<ConstantSDNode>(Add0);
4308fe6060f1SDimitry Andric     auto *Add1C = dyn_cast<ConstantSDNode>(Add1);
4309bdd1243dSDimitry Andric     // If we are shifting by X+/-/^N where N == 0 mod Size, then just shift by X
4310bdd1243dSDimitry Andric     // to avoid the ADD/SUB/XOR.
4311fe6060f1SDimitry Andric     if (Add1C && Add1C->getAPIntValue().urem(Size) == 0) {
43120b57cec5SDimitry Andric       NewShiftAmt = Add0;
4313bdd1243dSDimitry Andric 
431406c3fb27SDimitry Andric     } else if (ShiftAmt->getOpcode() != ISD::ADD && ShiftAmt.hasOneUse() &&
4315bdd1243dSDimitry Andric                ((Add0C && Add0C->getAPIntValue().urem(Size) == Size - 1) ||
4316bdd1243dSDimitry Andric                 (Add1C && Add1C->getAPIntValue().urem(Size) == Size - 1))) {
4317bdd1243dSDimitry Andric       // If we are doing a NOT on just the lower bits with (Size*N-1) -/^ X
4318bdd1243dSDimitry Andric       // we can replace it with a NOT. In the XOR case it may save some code
4319bdd1243dSDimitry Andric       // size, in the SUB case it also may save a move.
4320bdd1243dSDimitry Andric       assert(Add0C == nullptr || Add1C == nullptr);
4321bdd1243dSDimitry Andric 
4322bdd1243dSDimitry Andric       // We can only do N-X, not X-N
4323bdd1243dSDimitry Andric       if (ShiftAmt->getOpcode() == ISD::SUB && Add0C == nullptr)
4324bdd1243dSDimitry Andric         return false;
4325bdd1243dSDimitry Andric 
4326bdd1243dSDimitry Andric       EVT OpVT = ShiftAmt.getValueType();
4327bdd1243dSDimitry Andric 
43281ac55f4cSDimitry Andric       SDValue AllOnes = CurDAG->getAllOnesConstant(DL, OpVT);
43291ac55f4cSDimitry Andric       NewShiftAmt = CurDAG->getNode(ISD::XOR, DL, OpVT,
43301ac55f4cSDimitry Andric                                     Add0C == nullptr ? Add0 : Add1, AllOnes);
43311ac55f4cSDimitry Andric       insertDAGNode(*CurDAG, OrigShiftAmt, AllOnes);
4332bdd1243dSDimitry Andric       insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4333bdd1243dSDimitry Andric       // If we are shifting by N-X where N == 0 mod Size, then just shift by
4334bdd1243dSDimitry Andric       // -X to generate a NEG instead of a SUB of a constant.
4335fe6060f1SDimitry Andric     } else if (ShiftAmt->getOpcode() == ISD::SUB && Add0C &&
4336fe6060f1SDimitry Andric                Add0C->getZExtValue() != 0) {
4337fe6060f1SDimitry Andric       EVT SubVT = ShiftAmt.getValueType();
4338fe6060f1SDimitry Andric       SDValue X;
4339fe6060f1SDimitry Andric       if (Add0C->getZExtValue() % Size == 0)
4340fe6060f1SDimitry Andric         X = Add1;
4341fe6060f1SDimitry Andric       else if (ShiftAmt.hasOneUse() && Size == 64 &&
4342fe6060f1SDimitry Andric                Add0C->getZExtValue() % 32 == 0) {
4343fe6060f1SDimitry Andric         // We have a 64-bit shift by (n*32-x), turn it into -(x+n*32).
4344fe6060f1SDimitry Andric         // This is mainly beneficial if we already compute (x+n*32).
4345fe6060f1SDimitry Andric         if (Add1.getOpcode() == ISD::TRUNCATE) {
4346fe6060f1SDimitry Andric           Add1 = Add1.getOperand(0);
4347fe6060f1SDimitry Andric           SubVT = Add1.getValueType();
4348fe6060f1SDimitry Andric         }
4349fe6060f1SDimitry Andric         if (Add0.getValueType() != SubVT) {
4350fe6060f1SDimitry Andric           Add0 = CurDAG->getZExtOrTrunc(Add0, DL, SubVT);
4351fe6060f1SDimitry Andric           insertDAGNode(*CurDAG, OrigShiftAmt, Add0);
4352fe6060f1SDimitry Andric         }
4353fe6060f1SDimitry Andric 
4354fe6060f1SDimitry Andric         X = CurDAG->getNode(ISD::ADD, DL, SubVT, Add1, Add0);
4355fe6060f1SDimitry Andric         insertDAGNode(*CurDAG, OrigShiftAmt, X);
4356fe6060f1SDimitry Andric       } else
4357fe6060f1SDimitry Andric         return false;
43580b57cec5SDimitry Andric       // Insert a negate op.
43590b57cec5SDimitry Andric       // TODO: This isn't guaranteed to replace the sub if there is a logic cone
43600b57cec5SDimitry Andric       // that uses it that's not a shift.
43610b57cec5SDimitry Andric       SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
4362fe6060f1SDimitry Andric       SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, X);
43630b57cec5SDimitry Andric       NewShiftAmt = Neg;
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric       // Insert these operands into a valid topological order so they can
43660b57cec5SDimitry Andric       // get selected independently.
43670b57cec5SDimitry Andric       insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
43680b57cec5SDimitry Andric       insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
43690b57cec5SDimitry Andric     } else
43700b57cec5SDimitry Andric       return false;
43710b57cec5SDimitry Andric   } else
43720b57cec5SDimitry Andric     return false;
43730b57cec5SDimitry Andric 
43740b57cec5SDimitry Andric   if (NewShiftAmt.getValueType() != MVT::i8) {
43750b57cec5SDimitry Andric     // Need to truncate the shift amount.
43760b57cec5SDimitry Andric     NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
43770b57cec5SDimitry Andric     // Add to a correct topological ordering.
43780b57cec5SDimitry Andric     insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
43790b57cec5SDimitry Andric   }
43800b57cec5SDimitry Andric 
43810b57cec5SDimitry Andric   // Insert a new mask to keep the shift amount legal. This should be removed
43820b57cec5SDimitry Andric   // by isel patterns.
43830b57cec5SDimitry Andric   NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
43840b57cec5SDimitry Andric                                 CurDAG->getConstant(Size - 1, DL, MVT::i8));
43850b57cec5SDimitry Andric   // Place in a correct topological ordering.
43860b57cec5SDimitry Andric   insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
43870b57cec5SDimitry Andric 
43880b57cec5SDimitry Andric   SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
43890b57cec5SDimitry Andric                                                    NewShiftAmt);
43900b57cec5SDimitry Andric   if (UpdatedNode != N) {
43910b57cec5SDimitry Andric     // If we found an existing node, we should replace ourselves with that node
43920b57cec5SDimitry Andric     // and wait for it to be selected after its other users.
43930b57cec5SDimitry Andric     ReplaceNode(N, UpdatedNode);
43940b57cec5SDimitry Andric     return true;
43950b57cec5SDimitry Andric   }
43960b57cec5SDimitry Andric 
43970b57cec5SDimitry Andric   // If the original shift amount is now dead, delete it so that we don't run
43980b57cec5SDimitry Andric   // it through isel.
43990b57cec5SDimitry Andric   if (OrigShiftAmt.getNode()->use_empty())
44000b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
44010b57cec5SDimitry Andric 
44020b57cec5SDimitry Andric   // Now that we've optimized the shift amount, defer to normal isel to get
44030b57cec5SDimitry Andric   // load folding and legacy vs BMI2 selection without repeating it here.
44040b57cec5SDimitry Andric   SelectCode(N);
44050b57cec5SDimitry Andric   return true;
44060b57cec5SDimitry Andric }
44070b57cec5SDimitry Andric 
tryShrinkShlLogicImm(SDNode * N)44080b57cec5SDimitry Andric bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) {
44090b57cec5SDimitry Andric   MVT NVT = N->getSimpleValueType(0);
44100b57cec5SDimitry Andric   unsigned Opcode = N->getOpcode();
44110b57cec5SDimitry Andric   SDLoc dl(N);
44120b57cec5SDimitry Andric 
44130b57cec5SDimitry Andric   // For operations of the form (x << C1) op C2, check if we can use a smaller
44140b57cec5SDimitry Andric   // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
44150b57cec5SDimitry Andric   SDValue Shift = N->getOperand(0);
44160b57cec5SDimitry Andric   SDValue N1 = N->getOperand(1);
44170b57cec5SDimitry Andric 
4418bdd1243dSDimitry Andric   auto *Cst = dyn_cast<ConstantSDNode>(N1);
44190b57cec5SDimitry Andric   if (!Cst)
44200b57cec5SDimitry Andric     return false;
44210b57cec5SDimitry Andric 
44220b57cec5SDimitry Andric   int64_t Val = Cst->getSExtValue();
44230b57cec5SDimitry Andric 
44240b57cec5SDimitry Andric   // If we have an any_extend feeding the AND, look through it to see if there
44250b57cec5SDimitry Andric   // is a shift behind it. But only if the AND doesn't use the extended bits.
44260b57cec5SDimitry Andric   // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
44270b57cec5SDimitry Andric   bool FoundAnyExtend = false;
44280b57cec5SDimitry Andric   if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
44290b57cec5SDimitry Andric       Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
44300b57cec5SDimitry Andric       isUInt<32>(Val)) {
44310b57cec5SDimitry Andric     FoundAnyExtend = true;
44320b57cec5SDimitry Andric     Shift = Shift.getOperand(0);
44330b57cec5SDimitry Andric   }
44340b57cec5SDimitry Andric 
44350b57cec5SDimitry Andric   if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())
44360b57cec5SDimitry Andric     return false;
44370b57cec5SDimitry Andric 
44380b57cec5SDimitry Andric   // i8 is unshrinkable, i16 should be promoted to i32.
44390b57cec5SDimitry Andric   if (NVT != MVT::i32 && NVT != MVT::i64)
44400b57cec5SDimitry Andric     return false;
44410b57cec5SDimitry Andric 
4442bdd1243dSDimitry Andric   auto *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
44430b57cec5SDimitry Andric   if (!ShlCst)
44440b57cec5SDimitry Andric     return false;
44450b57cec5SDimitry Andric 
44460b57cec5SDimitry Andric   uint64_t ShAmt = ShlCst->getZExtValue();
44470b57cec5SDimitry Andric 
44480b57cec5SDimitry Andric   // Make sure that we don't change the operation by removing bits.
44490b57cec5SDimitry Andric   // This only matters for OR and XOR, AND is unaffected.
44500b57cec5SDimitry Andric   uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;
44510b57cec5SDimitry Andric   if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
44520b57cec5SDimitry Andric     return false;
44530b57cec5SDimitry Andric 
44540b57cec5SDimitry Andric   // Check the minimum bitwidth for the new constant.
44550b57cec5SDimitry Andric   // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
44560b57cec5SDimitry Andric   auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {
44570b57cec5SDimitry Andric     if (Opcode == ISD::AND) {
44580b57cec5SDimitry Andric       // AND32ri is the same as AND64ri32 with zext imm.
44590b57cec5SDimitry Andric       // Try this before sign extended immediates below.
44600b57cec5SDimitry Andric       ShiftedVal = (uint64_t)Val >> ShAmt;
44610b57cec5SDimitry Andric       if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
44620b57cec5SDimitry Andric         return true;
44630b57cec5SDimitry Andric       // Also swap order when the AND can become MOVZX.
44640b57cec5SDimitry Andric       if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX)
44650b57cec5SDimitry Andric         return true;
44660b57cec5SDimitry Andric     }
44670b57cec5SDimitry Andric     ShiftedVal = Val >> ShAmt;
44680b57cec5SDimitry Andric     if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||
44690b57cec5SDimitry Andric         (!isInt<32>(Val) && isInt<32>(ShiftedVal)))
44700b57cec5SDimitry Andric       return true;
44710b57cec5SDimitry Andric     if (Opcode != ISD::AND) {
44720b57cec5SDimitry Andric       // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr
44730b57cec5SDimitry Andric       ShiftedVal = (uint64_t)Val >> ShAmt;
44740b57cec5SDimitry Andric       if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
44750b57cec5SDimitry Andric         return true;
44760b57cec5SDimitry Andric     }
44770b57cec5SDimitry Andric     return false;
44780b57cec5SDimitry Andric   };
44790b57cec5SDimitry Andric 
44800b57cec5SDimitry Andric   int64_t ShiftedVal;
44810b57cec5SDimitry Andric   if (!CanShrinkImmediate(ShiftedVal))
44820b57cec5SDimitry Andric     return false;
44830b57cec5SDimitry Andric 
44840b57cec5SDimitry Andric   // Ok, we can reorder to get a smaller immediate.
44850b57cec5SDimitry Andric 
44860b57cec5SDimitry Andric   // But, its possible the original immediate allowed an AND to become MOVZX.
44870b57cec5SDimitry Andric   // Doing this late due to avoid the MakedValueIsZero call as late as
44880b57cec5SDimitry Andric   // possible.
44890b57cec5SDimitry Andric   if (Opcode == ISD::AND) {
44900b57cec5SDimitry Andric     // Find the smallest zext this could possibly be.
44910b57cec5SDimitry Andric     unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();
449206c3fb27SDimitry Andric     ZExtWidth = llvm::bit_ceil(std::max(ZExtWidth, 8U));
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric     // Figure out which bits need to be zero to achieve that mask.
44950b57cec5SDimitry Andric     APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),
44960b57cec5SDimitry Andric                                             ZExtWidth);
44970b57cec5SDimitry Andric     NeededMask &= ~Cst->getAPIntValue();
44980b57cec5SDimitry Andric 
44990b57cec5SDimitry Andric     if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask))
45000b57cec5SDimitry Andric       return false;
45010b57cec5SDimitry Andric   }
45020b57cec5SDimitry Andric 
45030b57cec5SDimitry Andric   SDValue X = Shift.getOperand(0);
45040b57cec5SDimitry Andric   if (FoundAnyExtend) {
45050b57cec5SDimitry Andric     SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);
45060b57cec5SDimitry Andric     insertDAGNode(*CurDAG, SDValue(N, 0), NewX);
45070b57cec5SDimitry Andric     X = NewX;
45080b57cec5SDimitry Andric   }
45090b57cec5SDimitry Andric 
45100b57cec5SDimitry Andric   SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT);
45110b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(N, 0), NewCst);
45120b57cec5SDimitry Andric   SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);
45130b57cec5SDimitry Andric   insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp);
45140b57cec5SDimitry Andric   SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,
45150b57cec5SDimitry Andric                                    Shift.getOperand(1));
45160b57cec5SDimitry Andric   ReplaceNode(N, NewSHL.getNode());
45170b57cec5SDimitry Andric   SelectCode(NewSHL.getNode());
45180b57cec5SDimitry Andric   return true;
45190b57cec5SDimitry Andric }
45200b57cec5SDimitry Andric 
matchVPTERNLOG(SDNode * Root,SDNode * ParentA,SDNode * ParentB,SDNode * ParentC,SDValue A,SDValue B,SDValue C,uint8_t Imm)4521e8d8bef9SDimitry Andric bool X86DAGToDAGISel::matchVPTERNLOG(SDNode *Root, SDNode *ParentA,
4522349cc55cSDimitry Andric                                      SDNode *ParentB, SDNode *ParentC,
4523349cc55cSDimitry Andric                                      SDValue A, SDValue B, SDValue C,
4524349cc55cSDimitry Andric                                      uint8_t Imm) {
4525349cc55cSDimitry Andric   assert(A.isOperandOf(ParentA) && B.isOperandOf(ParentB) &&
4526349cc55cSDimitry Andric          C.isOperandOf(ParentC) && "Incorrect parent node");
4527e8d8bef9SDimitry Andric 
4528e8d8bef9SDimitry Andric   auto tryFoldLoadOrBCast =
4529e8d8bef9SDimitry Andric       [this](SDNode *Root, SDNode *P, SDValue &L, SDValue &Base, SDValue &Scale,
4530e8d8bef9SDimitry Andric              SDValue &Index, SDValue &Disp, SDValue &Segment) {
4531e8d8bef9SDimitry Andric         if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
4532e8d8bef9SDimitry Andric           return true;
4533e8d8bef9SDimitry Andric 
4534e8d8bef9SDimitry Andric         // Not a load, check for broadcast which may be behind a bitcast.
4535e8d8bef9SDimitry Andric         if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
4536e8d8bef9SDimitry Andric           P = L.getNode();
4537e8d8bef9SDimitry Andric           L = L.getOperand(0);
4538e8d8bef9SDimitry Andric         }
4539e8d8bef9SDimitry Andric 
4540e8d8bef9SDimitry Andric         if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
4541e8d8bef9SDimitry Andric           return false;
4542e8d8bef9SDimitry Andric 
4543e8d8bef9SDimitry Andric         // Only 32 and 64 bit broadcasts are supported.
4544e8d8bef9SDimitry Andric         auto *MemIntr = cast<MemIntrinsicSDNode>(L);
4545e8d8bef9SDimitry Andric         unsigned Size = MemIntr->getMemoryVT().getSizeInBits();
4546e8d8bef9SDimitry Andric         if (Size != 32 && Size != 64)
4547e8d8bef9SDimitry Andric           return false;
4548e8d8bef9SDimitry Andric 
4549e8d8bef9SDimitry Andric         return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
4550e8d8bef9SDimitry Andric       };
4551e8d8bef9SDimitry Andric 
4552e8d8bef9SDimitry Andric   bool FoldedLoad = false;
4553e8d8bef9SDimitry Andric   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4554349cc55cSDimitry Andric   if (tryFoldLoadOrBCast(Root, ParentC, C, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4555e8d8bef9SDimitry Andric     FoldedLoad = true;
4556e8d8bef9SDimitry Andric   } else if (tryFoldLoadOrBCast(Root, ParentA, A, Tmp0, Tmp1, Tmp2, Tmp3,
4557e8d8bef9SDimitry Andric                                 Tmp4)) {
4558e8d8bef9SDimitry Andric     FoldedLoad = true;
4559e8d8bef9SDimitry Andric     std::swap(A, C);
4560e8d8bef9SDimitry Andric     // Swap bits 1/4 and 3/6.
4561e8d8bef9SDimitry Andric     uint8_t OldImm = Imm;
4562e8d8bef9SDimitry Andric     Imm = OldImm & 0xa5;
4563e8d8bef9SDimitry Andric     if (OldImm & 0x02) Imm |= 0x10;
4564e8d8bef9SDimitry Andric     if (OldImm & 0x10) Imm |= 0x02;
4565e8d8bef9SDimitry Andric     if (OldImm & 0x08) Imm |= 0x40;
4566e8d8bef9SDimitry Andric     if (OldImm & 0x40) Imm |= 0x08;
4567349cc55cSDimitry Andric   } else if (tryFoldLoadOrBCast(Root, ParentB, B, Tmp0, Tmp1, Tmp2, Tmp3,
4568e8d8bef9SDimitry Andric                                 Tmp4)) {
4569e8d8bef9SDimitry Andric     FoldedLoad = true;
4570e8d8bef9SDimitry Andric     std::swap(B, C);
4571e8d8bef9SDimitry Andric     // Swap bits 1/2 and 5/6.
4572e8d8bef9SDimitry Andric     uint8_t OldImm = Imm;
4573e8d8bef9SDimitry Andric     Imm = OldImm & 0x99;
4574e8d8bef9SDimitry Andric     if (OldImm & 0x02) Imm |= 0x04;
4575e8d8bef9SDimitry Andric     if (OldImm & 0x04) Imm |= 0x02;
4576e8d8bef9SDimitry Andric     if (OldImm & 0x20) Imm |= 0x40;
4577e8d8bef9SDimitry Andric     if (OldImm & 0x40) Imm |= 0x20;
4578e8d8bef9SDimitry Andric   }
4579e8d8bef9SDimitry Andric 
4580e8d8bef9SDimitry Andric   SDLoc DL(Root);
4581e8d8bef9SDimitry Andric 
4582e8d8bef9SDimitry Andric   SDValue TImm = CurDAG->getTargetConstant(Imm, DL, MVT::i8);
4583e8d8bef9SDimitry Andric 
4584e8d8bef9SDimitry Andric   MVT NVT = Root->getSimpleValueType(0);
4585e8d8bef9SDimitry Andric 
4586e8d8bef9SDimitry Andric   MachineSDNode *MNode;
4587e8d8bef9SDimitry Andric   if (FoldedLoad) {
4588e8d8bef9SDimitry Andric     SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
4589e8d8bef9SDimitry Andric 
4590e8d8bef9SDimitry Andric     unsigned Opc;
4591e8d8bef9SDimitry Andric     if (C.getOpcode() == X86ISD::VBROADCAST_LOAD) {
4592e8d8bef9SDimitry Andric       auto *MemIntr = cast<MemIntrinsicSDNode>(C);
4593e8d8bef9SDimitry Andric       unsigned EltSize = MemIntr->getMemoryVT().getSizeInBits();
4594e8d8bef9SDimitry Andric       assert((EltSize == 32 || EltSize == 64) && "Unexpected broadcast size!");
4595e8d8bef9SDimitry Andric 
4596e8d8bef9SDimitry Andric       bool UseD = EltSize == 32;
4597e8d8bef9SDimitry Andric       if (NVT.is128BitVector())
4598e8d8bef9SDimitry Andric         Opc = UseD ? X86::VPTERNLOGDZ128rmbi : X86::VPTERNLOGQZ128rmbi;
4599e8d8bef9SDimitry Andric       else if (NVT.is256BitVector())
4600e8d8bef9SDimitry Andric         Opc = UseD ? X86::VPTERNLOGDZ256rmbi : X86::VPTERNLOGQZ256rmbi;
4601e8d8bef9SDimitry Andric       else if (NVT.is512BitVector())
4602e8d8bef9SDimitry Andric         Opc = UseD ? X86::VPTERNLOGDZrmbi : X86::VPTERNLOGQZrmbi;
4603e8d8bef9SDimitry Andric       else
4604e8d8bef9SDimitry Andric         llvm_unreachable("Unexpected vector size!");
4605e8d8bef9SDimitry Andric     } else {
4606e8d8bef9SDimitry Andric       bool UseD = NVT.getVectorElementType() == MVT::i32;
4607e8d8bef9SDimitry Andric       if (NVT.is128BitVector())
4608e8d8bef9SDimitry Andric         Opc = UseD ? X86::VPTERNLOGDZ128rmi : X86::VPTERNLOGQZ128rmi;
4609e8d8bef9SDimitry Andric       else if (NVT.is256BitVector())
4610e8d8bef9SDimitry Andric         Opc = UseD ? X86::VPTERNLOGDZ256rmi : X86::VPTERNLOGQZ256rmi;
4611e8d8bef9SDimitry Andric       else if (NVT.is512BitVector())
4612e8d8bef9SDimitry Andric         Opc = UseD ? X86::VPTERNLOGDZrmi : X86::VPTERNLOGQZrmi;
4613e8d8bef9SDimitry Andric       else
4614e8d8bef9SDimitry Andric         llvm_unreachable("Unexpected vector size!");
4615e8d8bef9SDimitry Andric     }
4616e8d8bef9SDimitry Andric 
4617e8d8bef9SDimitry Andric     SDValue Ops[] = {A, B, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, TImm, C.getOperand(0)};
4618e8d8bef9SDimitry Andric     MNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
4619e8d8bef9SDimitry Andric 
4620e8d8bef9SDimitry Andric     // Update the chain.
4621e8d8bef9SDimitry Andric     ReplaceUses(C.getValue(1), SDValue(MNode, 1));
4622e8d8bef9SDimitry Andric     // Record the mem-refs
4623e8d8bef9SDimitry Andric     CurDAG->setNodeMemRefs(MNode, {cast<MemSDNode>(C)->getMemOperand()});
4624e8d8bef9SDimitry Andric   } else {
4625e8d8bef9SDimitry Andric     bool UseD = NVT.getVectorElementType() == MVT::i32;
4626e8d8bef9SDimitry Andric     unsigned Opc;
4627e8d8bef9SDimitry Andric     if (NVT.is128BitVector())
4628e8d8bef9SDimitry Andric       Opc = UseD ? X86::VPTERNLOGDZ128rri : X86::VPTERNLOGQZ128rri;
4629e8d8bef9SDimitry Andric     else if (NVT.is256BitVector())
4630e8d8bef9SDimitry Andric       Opc = UseD ? X86::VPTERNLOGDZ256rri : X86::VPTERNLOGQZ256rri;
4631e8d8bef9SDimitry Andric     else if (NVT.is512BitVector())
4632e8d8bef9SDimitry Andric       Opc = UseD ? X86::VPTERNLOGDZrri : X86::VPTERNLOGQZrri;
4633e8d8bef9SDimitry Andric     else
4634e8d8bef9SDimitry Andric       llvm_unreachable("Unexpected vector size!");
4635e8d8bef9SDimitry Andric 
4636e8d8bef9SDimitry Andric     MNode = CurDAG->getMachineNode(Opc, DL, NVT, {A, B, C, TImm});
4637e8d8bef9SDimitry Andric   }
4638e8d8bef9SDimitry Andric 
4639e8d8bef9SDimitry Andric   ReplaceUses(SDValue(Root, 0), SDValue(MNode, 0));
4640e8d8bef9SDimitry Andric   CurDAG->RemoveDeadNode(Root);
4641e8d8bef9SDimitry Andric   return true;
4642e8d8bef9SDimitry Andric }
4643e8d8bef9SDimitry Andric 
46445ffd83dbSDimitry Andric // Try to match two logic ops to a VPTERNLOG.
46455ffd83dbSDimitry Andric // FIXME: Handle more complex patterns that use an operand more than once?
tryVPTERNLOG(SDNode * N)46465ffd83dbSDimitry Andric bool X86DAGToDAGISel::tryVPTERNLOG(SDNode *N) {
46475ffd83dbSDimitry Andric   MVT NVT = N->getSimpleValueType(0);
46488bcb0991SDimitry Andric 
46495ffd83dbSDimitry Andric   // Make sure we support VPTERNLOG.
46505ffd83dbSDimitry Andric   if (!NVT.isVector() || !Subtarget->hasAVX512() ||
46515ffd83dbSDimitry Andric       NVT.getVectorElementType() == MVT::i1)
46528bcb0991SDimitry Andric     return false;
46538bcb0991SDimitry Andric 
46545ffd83dbSDimitry Andric   // We need VLX for 128/256-bit.
46555ffd83dbSDimitry Andric   if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
46565ffd83dbSDimitry Andric     return false;
46578bcb0991SDimitry Andric 
46585ffd83dbSDimitry Andric   SDValue N0 = N->getOperand(0);
46595ffd83dbSDimitry Andric   SDValue N1 = N->getOperand(1);
46608bcb0991SDimitry Andric 
4661e8d8bef9SDimitry Andric   auto getFoldableLogicOp = [](SDValue Op) {
4662e8d8bef9SDimitry Andric     // Peek through single use bitcast.
4663e8d8bef9SDimitry Andric     if (Op.getOpcode() == ISD::BITCAST && Op.hasOneUse())
4664e8d8bef9SDimitry Andric       Op = Op.getOperand(0);
4665e8d8bef9SDimitry Andric 
4666e8d8bef9SDimitry Andric     if (!Op.hasOneUse())
4667e8d8bef9SDimitry Andric       return SDValue();
4668e8d8bef9SDimitry Andric 
4669e8d8bef9SDimitry Andric     unsigned Opc = Op.getOpcode();
4670e8d8bef9SDimitry Andric     if (Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR ||
4671e8d8bef9SDimitry Andric         Opc == X86ISD::ANDNP)
4672e8d8bef9SDimitry Andric       return Op;
4673e8d8bef9SDimitry Andric 
4674e8d8bef9SDimitry Andric     return SDValue();
46755ffd83dbSDimitry Andric   };
46768bcb0991SDimitry Andric 
4677e8d8bef9SDimitry Andric   SDValue A, FoldableOp;
4678e8d8bef9SDimitry Andric   if ((FoldableOp = getFoldableLogicOp(N1))) {
46795ffd83dbSDimitry Andric     A = N0;
4680e8d8bef9SDimitry Andric   } else if ((FoldableOp = getFoldableLogicOp(N0))) {
46815ffd83dbSDimitry Andric     A = N1;
46825ffd83dbSDimitry Andric   } else
46835ffd83dbSDimitry Andric     return false;
46848bcb0991SDimitry Andric 
4685e8d8bef9SDimitry Andric   SDValue B = FoldableOp.getOperand(0);
4686e8d8bef9SDimitry Andric   SDValue C = FoldableOp.getOperand(1);
4687349cc55cSDimitry Andric   SDNode *ParentA = N;
4688349cc55cSDimitry Andric   SDNode *ParentB = FoldableOp.getNode();
4689349cc55cSDimitry Andric   SDNode *ParentC = FoldableOp.getNode();
4690e8d8bef9SDimitry Andric 
4691e8d8bef9SDimitry Andric   // We can build the appropriate control immediate by performing the logic
4692e8d8bef9SDimitry Andric   // operation we're matching using these constants for A, B, and C.
4693349cc55cSDimitry Andric   uint8_t TernlogMagicA = 0xf0;
4694349cc55cSDimitry Andric   uint8_t TernlogMagicB = 0xcc;
4695349cc55cSDimitry Andric   uint8_t TernlogMagicC = 0xaa;
4696349cc55cSDimitry Andric 
4697349cc55cSDimitry Andric   // Some of the inputs may be inverted, peek through them and invert the
4698349cc55cSDimitry Andric   // magic values accordingly.
4699349cc55cSDimitry Andric   // TODO: There may be a bitcast before the xor that we should peek through.
4700349cc55cSDimitry Andric   auto PeekThroughNot = [](SDValue &Op, SDNode *&Parent, uint8_t &Magic) {
4701349cc55cSDimitry Andric     if (Op.getOpcode() == ISD::XOR && Op.hasOneUse() &&
4702349cc55cSDimitry Andric         ISD::isBuildVectorAllOnes(Op.getOperand(1).getNode())) {
4703349cc55cSDimitry Andric       Magic = ~Magic;
4704349cc55cSDimitry Andric       Parent = Op.getNode();
4705349cc55cSDimitry Andric       Op = Op.getOperand(0);
4706349cc55cSDimitry Andric     }
4707349cc55cSDimitry Andric   };
4708349cc55cSDimitry Andric 
4709349cc55cSDimitry Andric   PeekThroughNot(A, ParentA, TernlogMagicA);
4710349cc55cSDimitry Andric   PeekThroughNot(B, ParentB, TernlogMagicB);
4711349cc55cSDimitry Andric   PeekThroughNot(C, ParentC, TernlogMagicC);
4712e8d8bef9SDimitry Andric 
4713e8d8bef9SDimitry Andric   uint8_t Imm;
4714e8d8bef9SDimitry Andric   switch (FoldableOp.getOpcode()) {
47155ffd83dbSDimitry Andric   default: llvm_unreachable("Unexpected opcode!");
4716e8d8bef9SDimitry Andric   case ISD::AND:      Imm = TernlogMagicB & TernlogMagicC; break;
4717e8d8bef9SDimitry Andric   case ISD::OR:       Imm = TernlogMagicB | TernlogMagicC; break;
4718e8d8bef9SDimitry Andric   case ISD::XOR:      Imm = TernlogMagicB ^ TernlogMagicC; break;
4719e8d8bef9SDimitry Andric   case X86ISD::ANDNP: Imm = ~(TernlogMagicB) & TernlogMagicC; break;
47205ffd83dbSDimitry Andric   }
47218bcb0991SDimitry Andric 
4722e8d8bef9SDimitry Andric   switch (N->getOpcode()) {
4723e8d8bef9SDimitry Andric   default: llvm_unreachable("Unexpected opcode!");
4724e8d8bef9SDimitry Andric   case X86ISD::ANDNP:
4725e8d8bef9SDimitry Andric     if (A == N0)
4726e8d8bef9SDimitry Andric       Imm &= ~TernlogMagicA;
4727e8d8bef9SDimitry Andric     else
4728e8d8bef9SDimitry Andric       Imm = ~(Imm) & TernlogMagicA;
4729e8d8bef9SDimitry Andric     break;
4730e8d8bef9SDimitry Andric   case ISD::AND: Imm &= TernlogMagicA; break;
4731e8d8bef9SDimitry Andric   case ISD::OR:  Imm |= TernlogMagicA; break;
4732e8d8bef9SDimitry Andric   case ISD::XOR: Imm ^= TernlogMagicA; break;
4733e8d8bef9SDimitry Andric   }
4734e8d8bef9SDimitry Andric 
4735349cc55cSDimitry Andric   return matchVPTERNLOG(N, ParentA, ParentB, ParentC, A, B, C, Imm);
47368bcb0991SDimitry Andric }
47378bcb0991SDimitry Andric 
47380b57cec5SDimitry Andric /// If the high bits of an 'and' operand are known zero, try setting the
47390b57cec5SDimitry Andric /// high bits of an 'and' constant operand to produce a smaller encoding by
47400b57cec5SDimitry Andric /// creating a small, sign-extended negative immediate rather than a large
47410b57cec5SDimitry Andric /// positive one. This reverses a transform in SimplifyDemandedBits that
47420b57cec5SDimitry Andric /// shrinks mask constants by clearing bits. There is also a possibility that
47430b57cec5SDimitry Andric /// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
47440b57cec5SDimitry Andric /// case, just replace the 'and'. Return 'true' if the node is replaced.
shrinkAndImmediate(SDNode * And)47450b57cec5SDimitry Andric bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
47460b57cec5SDimitry Andric   // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
47470b57cec5SDimitry Andric   // have immediate operands.
47480b57cec5SDimitry Andric   MVT VT = And->getSimpleValueType(0);
47490b57cec5SDimitry Andric   if (VT != MVT::i32 && VT != MVT::i64)
47500b57cec5SDimitry Andric     return false;
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric   auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
47530b57cec5SDimitry Andric   if (!And1C)
47540b57cec5SDimitry Andric     return false;
47550b57cec5SDimitry Andric 
47560b57cec5SDimitry Andric   // Bail out if the mask constant is already negative. It's can't shrink more.
47570b57cec5SDimitry Andric   // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
47580b57cec5SDimitry Andric   // patterns to use a 32-bit and instead of a 64-bit and by relying on the
47590b57cec5SDimitry Andric   // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
47600b57cec5SDimitry Andric   // are negative too.
47610b57cec5SDimitry Andric   APInt MaskVal = And1C->getAPIntValue();
476206c3fb27SDimitry Andric   unsigned MaskLZ = MaskVal.countl_zero();
47630b57cec5SDimitry Andric   if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
47640b57cec5SDimitry Andric     return false;
47650b57cec5SDimitry Andric 
47660b57cec5SDimitry Andric   // Don't extend into the upper 32 bits of a 64 bit mask.
47670b57cec5SDimitry Andric   if (VT == MVT::i64 && MaskLZ >= 32) {
47680b57cec5SDimitry Andric     MaskLZ -= 32;
47690b57cec5SDimitry Andric     MaskVal = MaskVal.trunc(32);
47700b57cec5SDimitry Andric   }
47710b57cec5SDimitry Andric 
47720b57cec5SDimitry Andric   SDValue And0 = And->getOperand(0);
47730b57cec5SDimitry Andric   APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
47740b57cec5SDimitry Andric   APInt NegMaskVal = MaskVal | HighZeros;
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric   // If a negative constant would not allow a smaller encoding, there's no need
47770b57cec5SDimitry Andric   // to continue. Only change the constant when we know it's a win.
477806c3fb27SDimitry Andric   unsigned MinWidth = NegMaskVal.getSignificantBits();
477906c3fb27SDimitry Andric   if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getSignificantBits() <= 32))
47800b57cec5SDimitry Andric     return false;
47810b57cec5SDimitry Andric 
47820b57cec5SDimitry Andric   // Extend masks if we truncated above.
47830b57cec5SDimitry Andric   if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
47840b57cec5SDimitry Andric     NegMaskVal = NegMaskVal.zext(64);
47850b57cec5SDimitry Andric     HighZeros = HighZeros.zext(64);
47860b57cec5SDimitry Andric   }
47870b57cec5SDimitry Andric 
47880b57cec5SDimitry Andric   // The variable operand must be all zeros in the top bits to allow using the
47890b57cec5SDimitry Andric   // new, negative constant as the mask.
47900b57cec5SDimitry Andric   if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
47910b57cec5SDimitry Andric     return false;
47920b57cec5SDimitry Andric 
47930b57cec5SDimitry Andric   // Check if the mask is -1. In that case, this is an unnecessary instruction
47940b57cec5SDimitry Andric   // that escaped earlier analysis.
4795349cc55cSDimitry Andric   if (NegMaskVal.isAllOnes()) {
47960b57cec5SDimitry Andric     ReplaceNode(And, And0.getNode());
47970b57cec5SDimitry Andric     return true;
47980b57cec5SDimitry Andric   }
47990b57cec5SDimitry Andric 
48000b57cec5SDimitry Andric   // A negative mask allows a smaller encoding. Create a new 'and' node.
48010b57cec5SDimitry Andric   SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
4802e8d8bef9SDimitry Andric   insertDAGNode(*CurDAG, SDValue(And, 0), NewMask);
48030b57cec5SDimitry Andric   SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
48040b57cec5SDimitry Andric   ReplaceNode(And, NewAnd.getNode());
48050b57cec5SDimitry Andric   SelectCode(NewAnd.getNode());
48060b57cec5SDimitry Andric   return true;
48070b57cec5SDimitry Andric }
48080b57cec5SDimitry Andric 
getVPTESTMOpc(MVT TestVT,bool IsTestN,bool FoldedLoad,bool FoldedBCast,bool Masked)48090b57cec5SDimitry Andric static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,
48100b57cec5SDimitry Andric                               bool FoldedBCast, bool Masked) {
48115ffd83dbSDimitry Andric #define VPTESTM_CASE(VT, SUFFIX) \
48125ffd83dbSDimitry Andric case MVT::VT: \
48135ffd83dbSDimitry Andric   if (Masked) \
48145ffd83dbSDimitry Andric     return IsTestN ? X86::VPTESTNM##SUFFIX##k: X86::VPTESTM##SUFFIX##k; \
48155ffd83dbSDimitry Andric   return IsTestN ? X86::VPTESTNM##SUFFIX : X86::VPTESTM##SUFFIX;
48165ffd83dbSDimitry Andric 
48175ffd83dbSDimitry Andric 
48185ffd83dbSDimitry Andric #define VPTESTM_BROADCAST_CASES(SUFFIX) \
48195ffd83dbSDimitry Andric default: llvm_unreachable("Unexpected VT!"); \
48205ffd83dbSDimitry Andric VPTESTM_CASE(v4i32, DZ128##SUFFIX) \
48215ffd83dbSDimitry Andric VPTESTM_CASE(v2i64, QZ128##SUFFIX) \
48225ffd83dbSDimitry Andric VPTESTM_CASE(v8i32, DZ256##SUFFIX) \
48235ffd83dbSDimitry Andric VPTESTM_CASE(v4i64, QZ256##SUFFIX) \
48245ffd83dbSDimitry Andric VPTESTM_CASE(v16i32, DZ##SUFFIX) \
48255ffd83dbSDimitry Andric VPTESTM_CASE(v8i64, QZ##SUFFIX)
48265ffd83dbSDimitry Andric 
48275ffd83dbSDimitry Andric #define VPTESTM_FULL_CASES(SUFFIX) \
48285ffd83dbSDimitry Andric VPTESTM_BROADCAST_CASES(SUFFIX) \
48295ffd83dbSDimitry Andric VPTESTM_CASE(v16i8, BZ128##SUFFIX) \
48305ffd83dbSDimitry Andric VPTESTM_CASE(v8i16, WZ128##SUFFIX) \
48315ffd83dbSDimitry Andric VPTESTM_CASE(v32i8, BZ256##SUFFIX) \
48325ffd83dbSDimitry Andric VPTESTM_CASE(v16i16, WZ256##SUFFIX) \
48335ffd83dbSDimitry Andric VPTESTM_CASE(v64i8, BZ##SUFFIX) \
48345ffd83dbSDimitry Andric VPTESTM_CASE(v32i16, WZ##SUFFIX)
48355ffd83dbSDimitry Andric 
48360b57cec5SDimitry Andric   if (FoldedBCast) {
48370b57cec5SDimitry Andric     switch (TestVT.SimpleTy) {
48385ffd83dbSDimitry Andric     VPTESTM_BROADCAST_CASES(rmb)
48390b57cec5SDimitry Andric     }
48400b57cec5SDimitry Andric   }
48410b57cec5SDimitry Andric 
4842e8d8bef9SDimitry Andric   if (FoldedLoad) {
4843e8d8bef9SDimitry Andric     switch (TestVT.SimpleTy) {
4844e8d8bef9SDimitry Andric     VPTESTM_FULL_CASES(rm)
4845e8d8bef9SDimitry Andric     }
4846e8d8bef9SDimitry Andric   }
4847e8d8bef9SDimitry Andric 
48480b57cec5SDimitry Andric   switch (TestVT.SimpleTy) {
48495ffd83dbSDimitry Andric   VPTESTM_FULL_CASES(rr)
48500b57cec5SDimitry Andric   }
48510b57cec5SDimitry Andric 
48525ffd83dbSDimitry Andric #undef VPTESTM_FULL_CASES
48535ffd83dbSDimitry Andric #undef VPTESTM_BROADCAST_CASES
48545ffd83dbSDimitry Andric #undef VPTESTM_CASE
48550b57cec5SDimitry Andric }
48560b57cec5SDimitry Andric 
48570b57cec5SDimitry Andric // Try to create VPTESTM instruction. If InMask is not null, it will be used
48580b57cec5SDimitry Andric // to form a masked operation.
tryVPTESTM(SDNode * Root,SDValue Setcc,SDValue InMask)48590b57cec5SDimitry Andric bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,
48600b57cec5SDimitry Andric                                  SDValue InMask) {
48610b57cec5SDimitry Andric   assert(Subtarget->hasAVX512() && "Expected AVX512!");
48620b57cec5SDimitry Andric   assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&
48630b57cec5SDimitry Andric          "Unexpected VT!");
48640b57cec5SDimitry Andric 
48650b57cec5SDimitry Andric   // Look for equal and not equal compares.
48660b57cec5SDimitry Andric   ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
48670b57cec5SDimitry Andric   if (CC != ISD::SETEQ && CC != ISD::SETNE)
48680b57cec5SDimitry Andric     return false;
48690b57cec5SDimitry Andric 
48708bcb0991SDimitry Andric   SDValue SetccOp0 = Setcc.getOperand(0);
48718bcb0991SDimitry Andric   SDValue SetccOp1 = Setcc.getOperand(1);
48728bcb0991SDimitry Andric 
48738bcb0991SDimitry Andric   // Canonicalize the all zero vector to the RHS.
48748bcb0991SDimitry Andric   if (ISD::isBuildVectorAllZeros(SetccOp0.getNode()))
48758bcb0991SDimitry Andric     std::swap(SetccOp0, SetccOp1);
48768bcb0991SDimitry Andric 
48778bcb0991SDimitry Andric   // See if we're comparing against zero.
48788bcb0991SDimitry Andric   if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode()))
48790b57cec5SDimitry Andric     return false;
48800b57cec5SDimitry Andric 
48818bcb0991SDimitry Andric   SDValue N0 = SetccOp0;
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric   MVT CmpVT = N0.getSimpleValueType();
48840b57cec5SDimitry Andric   MVT CmpSVT = CmpVT.getVectorElementType();
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric   // Start with both operands the same. We'll try to refine this.
48870b57cec5SDimitry Andric   SDValue Src0 = N0;
48880b57cec5SDimitry Andric   SDValue Src1 = N0;
48890b57cec5SDimitry Andric 
48900b57cec5SDimitry Andric   {
48910b57cec5SDimitry Andric     // Look through single use bitcasts.
48920b57cec5SDimitry Andric     SDValue N0Temp = N0;
48930b57cec5SDimitry Andric     if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())
48940b57cec5SDimitry Andric       N0Temp = N0.getOperand(0);
48950b57cec5SDimitry Andric 
48960b57cec5SDimitry Andric      // Look for single use AND.
48970b57cec5SDimitry Andric     if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {
48980b57cec5SDimitry Andric       Src0 = N0Temp.getOperand(0);
48990b57cec5SDimitry Andric       Src1 = N0Temp.getOperand(1);
49000b57cec5SDimitry Andric     }
49010b57cec5SDimitry Andric   }
49020b57cec5SDimitry Andric 
4903e8d8bef9SDimitry Andric   // Without VLX we need to widen the operation.
49040b57cec5SDimitry Andric   bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();
49050b57cec5SDimitry Andric 
4906e8d8bef9SDimitry Andric   auto tryFoldLoadOrBCast = [&](SDNode *Root, SDNode *P, SDValue &L,
4907e8d8bef9SDimitry Andric                                 SDValue &Base, SDValue &Scale, SDValue &Index,
4908e8d8bef9SDimitry Andric                                 SDValue &Disp, SDValue &Segment) {
4909e8d8bef9SDimitry Andric     // If we need to widen, we can't fold the load.
4910e8d8bef9SDimitry Andric     if (!Widen)
4911e8d8bef9SDimitry Andric       if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
4912e8d8bef9SDimitry Andric         return true;
4913e8d8bef9SDimitry Andric 
4914e8d8bef9SDimitry Andric     // If we didn't fold a load, try to match broadcast. No widening limitation
4915e8d8bef9SDimitry Andric     // for this. But only 32 and 64 bit types are supported.
4916e8d8bef9SDimitry Andric     if (CmpSVT != MVT::i32 && CmpSVT != MVT::i64)
4917e8d8bef9SDimitry Andric       return false;
4918e8d8bef9SDimitry Andric 
4919e8d8bef9SDimitry Andric     // Look through single use bitcasts.
4920e8d8bef9SDimitry Andric     if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
4921e8d8bef9SDimitry Andric       P = L.getNode();
4922e8d8bef9SDimitry Andric       L = L.getOperand(0);
4923e8d8bef9SDimitry Andric     }
4924e8d8bef9SDimitry Andric 
4925e8d8bef9SDimitry Andric     if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
4926e8d8bef9SDimitry Andric       return false;
4927e8d8bef9SDimitry Andric 
4928e8d8bef9SDimitry Andric     auto *MemIntr = cast<MemIntrinsicSDNode>(L);
4929e8d8bef9SDimitry Andric     if (MemIntr->getMemoryVT().getSizeInBits() != CmpSVT.getSizeInBits())
4930e8d8bef9SDimitry Andric       return false;
4931e8d8bef9SDimitry Andric 
4932e8d8bef9SDimitry Andric     return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
4933e8d8bef9SDimitry Andric   };
4934e8d8bef9SDimitry Andric 
49350b57cec5SDimitry Andric   // We can only fold loads if the sources are unique.
49360b57cec5SDimitry Andric   bool CanFoldLoads = Src0 != Src1;
49370b57cec5SDimitry Andric 
49380b57cec5SDimitry Andric   bool FoldedLoad = false;
4939e8d8bef9SDimitry Andric   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4940e8d8bef9SDimitry Andric   if (CanFoldLoads) {
4941e8d8bef9SDimitry Andric     FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src1, Tmp0, Tmp1, Tmp2,
49420b57cec5SDimitry Andric                                     Tmp3, Tmp4);
4943e8d8bef9SDimitry Andric     if (!FoldedLoad) {
4944e8d8bef9SDimitry Andric       // And is commutative.
4945e8d8bef9SDimitry Andric       FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src0, Tmp0, Tmp1,
4946e8d8bef9SDimitry Andric                                       Tmp2, Tmp3, Tmp4);
49470b57cec5SDimitry Andric       if (FoldedLoad)
49480b57cec5SDimitry Andric         std::swap(Src0, Src1);
49490b57cec5SDimitry Andric     }
49500b57cec5SDimitry Andric   }
49510b57cec5SDimitry Andric 
4952e8d8bef9SDimitry Andric   bool FoldedBCast = FoldedLoad && Src1.getOpcode() == X86ISD::VBROADCAST_LOAD;
49530b57cec5SDimitry Andric 
49540b57cec5SDimitry Andric   bool IsMasked = InMask.getNode() != nullptr;
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric   SDLoc dl(Root);
49570b57cec5SDimitry Andric 
49580b57cec5SDimitry Andric   MVT ResVT = Setcc.getSimpleValueType();
49590b57cec5SDimitry Andric   MVT MaskVT = ResVT;
49600b57cec5SDimitry Andric   if (Widen) {
49610b57cec5SDimitry Andric     // Widen the inputs using insert_subreg or copy_to_regclass.
49620b57cec5SDimitry Andric     unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;
49630b57cec5SDimitry Andric     unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;
49640b57cec5SDimitry Andric     unsigned NumElts = CmpVT.getVectorNumElements() * Scale;
49650b57cec5SDimitry Andric     CmpVT = MVT::getVectorVT(CmpSVT, NumElts);
49660b57cec5SDimitry Andric     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
49670b57cec5SDimitry Andric     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,
49680b57cec5SDimitry Andric                                                      CmpVT), 0);
49690b57cec5SDimitry Andric     Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);
49700b57cec5SDimitry Andric 
49710b57cec5SDimitry Andric     if (!FoldedBCast)
49720b57cec5SDimitry Andric       Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);
49730b57cec5SDimitry Andric 
49740b57cec5SDimitry Andric     if (IsMasked) {
49750b57cec5SDimitry Andric       // Widen the mask.
4976e8d8bef9SDimitry Andric       unsigned RegClass = TLI->getRegClassFor(MaskVT)->getID();
49770b57cec5SDimitry Andric       SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
49780b57cec5SDimitry Andric       InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
49790b57cec5SDimitry Andric                                               dl, MaskVT, InMask, RC), 0);
49800b57cec5SDimitry Andric     }
49810b57cec5SDimitry Andric   }
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric   bool IsTestN = CC == ISD::SETEQ;
49840b57cec5SDimitry Andric   unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,
49850b57cec5SDimitry Andric                                IsMasked);
49860b57cec5SDimitry Andric 
49870b57cec5SDimitry Andric   MachineSDNode *CNode;
4988e8d8bef9SDimitry Andric   if (FoldedLoad) {
49890b57cec5SDimitry Andric     SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);
49900b57cec5SDimitry Andric 
49910b57cec5SDimitry Andric     if (IsMasked) {
49920b57cec5SDimitry Andric       SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4993e8d8bef9SDimitry Andric                         Src1.getOperand(0) };
49940b57cec5SDimitry Andric       CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
49950b57cec5SDimitry Andric     } else {
49960b57cec5SDimitry Andric       SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4997e8d8bef9SDimitry Andric                         Src1.getOperand(0) };
49980b57cec5SDimitry Andric       CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
49990b57cec5SDimitry Andric     }
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric     // Update the chain.
5002e8d8bef9SDimitry Andric     ReplaceUses(Src1.getValue(1), SDValue(CNode, 1));
50030b57cec5SDimitry Andric     // Record the mem-refs
5004e8d8bef9SDimitry Andric     CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Src1)->getMemOperand()});
50050b57cec5SDimitry Andric   } else {
50060b57cec5SDimitry Andric     if (IsMasked)
50070b57cec5SDimitry Andric       CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);
50080b57cec5SDimitry Andric     else
50090b57cec5SDimitry Andric       CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);
50100b57cec5SDimitry Andric   }
50110b57cec5SDimitry Andric 
50120b57cec5SDimitry Andric   // If we widened, we need to shrink the mask VT.
50130b57cec5SDimitry Andric   if (Widen) {
5014e8d8bef9SDimitry Andric     unsigned RegClass = TLI->getRegClassFor(ResVT)->getID();
50150b57cec5SDimitry Andric     SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
50160b57cec5SDimitry Andric     CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
50170b57cec5SDimitry Andric                                    dl, ResVT, SDValue(CNode, 0), RC);
50180b57cec5SDimitry Andric   }
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric   ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));
50210b57cec5SDimitry Andric   CurDAG->RemoveDeadNode(Root);
50220b57cec5SDimitry Andric   return true;
50230b57cec5SDimitry Andric }
50240b57cec5SDimitry Andric 
50258bcb0991SDimitry Andric // Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it
50268bcb0991SDimitry Andric // into vpternlog.
tryMatchBitSelect(SDNode * N)50278bcb0991SDimitry Andric bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) {
50288bcb0991SDimitry Andric   assert(N->getOpcode() == ISD::OR && "Unexpected opcode!");
50298bcb0991SDimitry Andric 
50308bcb0991SDimitry Andric   MVT NVT = N->getSimpleValueType(0);
50318bcb0991SDimitry Andric 
50328bcb0991SDimitry Andric   // Make sure we support VPTERNLOG.
50338bcb0991SDimitry Andric   if (!NVT.isVector() || !Subtarget->hasAVX512())
50348bcb0991SDimitry Andric     return false;
50358bcb0991SDimitry Andric 
50368bcb0991SDimitry Andric   // We need VLX for 128/256-bit.
50378bcb0991SDimitry Andric   if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
50388bcb0991SDimitry Andric     return false;
50398bcb0991SDimitry Andric 
50408bcb0991SDimitry Andric   SDValue N0 = N->getOperand(0);
50418bcb0991SDimitry Andric   SDValue N1 = N->getOperand(1);
50428bcb0991SDimitry Andric 
50438bcb0991SDimitry Andric   // Canonicalize AND to LHS.
50448bcb0991SDimitry Andric   if (N1.getOpcode() == ISD::AND)
50458bcb0991SDimitry Andric     std::swap(N0, N1);
50468bcb0991SDimitry Andric 
50478bcb0991SDimitry Andric   if (N0.getOpcode() != ISD::AND ||
50488bcb0991SDimitry Andric       N1.getOpcode() != X86ISD::ANDNP ||
50498bcb0991SDimitry Andric       !N0.hasOneUse() || !N1.hasOneUse())
50508bcb0991SDimitry Andric     return false;
50518bcb0991SDimitry Andric 
50528bcb0991SDimitry Andric   // ANDN is not commutable, use it to pick down A and C.
50538bcb0991SDimitry Andric   SDValue A = N1.getOperand(0);
50548bcb0991SDimitry Andric   SDValue C = N1.getOperand(1);
50558bcb0991SDimitry Andric 
50568bcb0991SDimitry Andric   // AND is commutable, if one operand matches A, the other operand is B.
50578bcb0991SDimitry Andric   // Otherwise this isn't a match.
50588bcb0991SDimitry Andric   SDValue B;
50598bcb0991SDimitry Andric   if (N0.getOperand(0) == A)
50608bcb0991SDimitry Andric     B = N0.getOperand(1);
50618bcb0991SDimitry Andric   else if (N0.getOperand(1) == A)
50628bcb0991SDimitry Andric     B = N0.getOperand(0);
50638bcb0991SDimitry Andric   else
50648bcb0991SDimitry Andric     return false;
50658bcb0991SDimitry Andric 
50668bcb0991SDimitry Andric   SDLoc dl(N);
50678bcb0991SDimitry Andric   SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8);
50688bcb0991SDimitry Andric   SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm);
50698bcb0991SDimitry Andric   ReplaceNode(N, Ternlog.getNode());
5070e8d8bef9SDimitry Andric 
5071e8d8bef9SDimitry Andric   return matchVPTERNLOG(Ternlog.getNode(), Ternlog.getNode(), Ternlog.getNode(),
5072349cc55cSDimitry Andric                         Ternlog.getNode(), A, B, C, 0xCA);
50738bcb0991SDimitry Andric }
50748bcb0991SDimitry Andric 
Select(SDNode * Node)50750b57cec5SDimitry Andric void X86DAGToDAGISel::Select(SDNode *Node) {
50760b57cec5SDimitry Andric   MVT NVT = Node->getSimpleValueType(0);
50770b57cec5SDimitry Andric   unsigned Opcode = Node->getOpcode();
50780b57cec5SDimitry Andric   SDLoc dl(Node);
50790b57cec5SDimitry Andric 
50800b57cec5SDimitry Andric   if (Node->isMachineOpcode()) {
50810b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
50820b57cec5SDimitry Andric     Node->setNodeId(-1);
50830b57cec5SDimitry Andric     return;   // Already selected.
50840b57cec5SDimitry Andric   }
50850b57cec5SDimitry Andric 
50860b57cec5SDimitry Andric   switch (Opcode) {
50870b57cec5SDimitry Andric   default: break;
5088e8d8bef9SDimitry Andric   case ISD::INTRINSIC_W_CHAIN: {
5089e8d8bef9SDimitry Andric     unsigned IntNo = Node->getConstantOperandVal(1);
5090e8d8bef9SDimitry Andric     switch (IntNo) {
5091e8d8bef9SDimitry Andric     default: break;
5092e8d8bef9SDimitry Andric     case Intrinsic::x86_encodekey128:
5093e8d8bef9SDimitry Andric     case Intrinsic::x86_encodekey256: {
5094e8d8bef9SDimitry Andric       if (!Subtarget->hasKL())
5095e8d8bef9SDimitry Andric         break;
5096e8d8bef9SDimitry Andric 
5097e8d8bef9SDimitry Andric       unsigned Opcode;
5098e8d8bef9SDimitry Andric       switch (IntNo) {
5099e8d8bef9SDimitry Andric       default: llvm_unreachable("Impossible intrinsic");
5100*0fca6ea1SDimitry Andric       case Intrinsic::x86_encodekey128:
5101*0fca6ea1SDimitry Andric         Opcode = X86::ENCODEKEY128;
5102*0fca6ea1SDimitry Andric         break;
5103*0fca6ea1SDimitry Andric       case Intrinsic::x86_encodekey256:
5104*0fca6ea1SDimitry Andric         Opcode = X86::ENCODEKEY256;
5105*0fca6ea1SDimitry Andric         break;
5106e8d8bef9SDimitry Andric       }
5107e8d8bef9SDimitry Andric 
5108e8d8bef9SDimitry Andric       SDValue Chain = Node->getOperand(0);
5109e8d8bef9SDimitry Andric       Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(3),
5110e8d8bef9SDimitry Andric                                    SDValue());
5111e8d8bef9SDimitry Andric       if (Opcode == X86::ENCODEKEY256)
5112e8d8bef9SDimitry Andric         Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(4),
5113e8d8bef9SDimitry Andric                                      Chain.getValue(1));
5114e8d8bef9SDimitry Andric 
5115e8d8bef9SDimitry Andric       MachineSDNode *Res = CurDAG->getMachineNode(
5116e8d8bef9SDimitry Andric           Opcode, dl, Node->getVTList(),
5117e8d8bef9SDimitry Andric           {Node->getOperand(2), Chain, Chain.getValue(1)});
5118e8d8bef9SDimitry Andric       ReplaceNode(Node, Res);
5119e8d8bef9SDimitry Andric       return;
5120e8d8bef9SDimitry Andric     }
5121fe6060f1SDimitry Andric     case Intrinsic::x86_tileloadd64_internal:
5122fe6060f1SDimitry Andric     case Intrinsic::x86_tileloaddt164_internal: {
5123e8d8bef9SDimitry Andric       if (!Subtarget->hasAMXTILE())
5124e8d8bef9SDimitry Andric         break;
5125*0fca6ea1SDimitry Andric       auto *MFI =
5126*0fca6ea1SDimitry Andric           CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5127*0fca6ea1SDimitry Andric       MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);
5128fe6060f1SDimitry Andric       unsigned Opc = IntNo == Intrinsic::x86_tileloadd64_internal
5129fe6060f1SDimitry Andric                          ? X86::PTILELOADDV
5130fe6060f1SDimitry Andric                          : X86::PTILELOADDT1V;
5131e8d8bef9SDimitry Andric       // _tile_loadd_internal(row, col, buf, STRIDE)
5132e8d8bef9SDimitry Andric       SDValue Base = Node->getOperand(4);
5133e8d8bef9SDimitry Andric       SDValue Scale = getI8Imm(1, dl);
5134e8d8bef9SDimitry Andric       SDValue Index = Node->getOperand(5);
5135e8d8bef9SDimitry Andric       SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
5136e8d8bef9SDimitry Andric       SDValue Segment = CurDAG->getRegister(0, MVT::i16);
5137e8d8bef9SDimitry Andric       SDValue Chain = Node->getOperand(0);
5138e8d8bef9SDimitry Andric       MachineSDNode *CNode;
5139e8d8bef9SDimitry Andric       SDValue Ops[] = {Node->getOperand(2),
5140e8d8bef9SDimitry Andric                        Node->getOperand(3),
5141e8d8bef9SDimitry Andric                        Base,
5142e8d8bef9SDimitry Andric                        Scale,
5143e8d8bef9SDimitry Andric                        Index,
5144e8d8bef9SDimitry Andric                        Disp,
5145e8d8bef9SDimitry Andric                        Segment,
5146e8d8bef9SDimitry Andric                        Chain};
5147e8d8bef9SDimitry Andric       CNode = CurDAG->getMachineNode(Opc, dl, {MVT::x86amx, MVT::Other}, Ops);
5148e8d8bef9SDimitry Andric       ReplaceNode(Node, CNode);
5149e8d8bef9SDimitry Andric       return;
5150e8d8bef9SDimitry Andric     }
5151e8d8bef9SDimitry Andric     }
5152e8d8bef9SDimitry Andric     break;
5153e8d8bef9SDimitry Andric   }
51540b57cec5SDimitry Andric   case ISD::INTRINSIC_VOID: {
51550b57cec5SDimitry Andric     unsigned IntNo = Node->getConstantOperandVal(1);
51560b57cec5SDimitry Andric     switch (IntNo) {
51570b57cec5SDimitry Andric     default: break;
51580b57cec5SDimitry Andric     case Intrinsic::x86_sse3_monitor:
51590b57cec5SDimitry Andric     case Intrinsic::x86_monitorx:
51600b57cec5SDimitry Andric     case Intrinsic::x86_clzero: {
51610b57cec5SDimitry Andric       bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;
51620b57cec5SDimitry Andric 
51630b57cec5SDimitry Andric       unsigned Opc = 0;
51640b57cec5SDimitry Andric       switch (IntNo) {
51658bcb0991SDimitry Andric       default: llvm_unreachable("Unexpected intrinsic!");
51660b57cec5SDimitry Andric       case Intrinsic::x86_sse3_monitor:
51670b57cec5SDimitry Andric         if (!Subtarget->hasSSE3())
51680b57cec5SDimitry Andric           break;
51690b57cec5SDimitry Andric         Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;
51700b57cec5SDimitry Andric         break;
51710b57cec5SDimitry Andric       case Intrinsic::x86_monitorx:
51720b57cec5SDimitry Andric         if (!Subtarget->hasMWAITX())
51730b57cec5SDimitry Andric           break;
51740b57cec5SDimitry Andric         Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;
51750b57cec5SDimitry Andric         break;
51760b57cec5SDimitry Andric       case Intrinsic::x86_clzero:
51770b57cec5SDimitry Andric         if (!Subtarget->hasCLZERO())
51780b57cec5SDimitry Andric           break;
51790b57cec5SDimitry Andric         Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;
51800b57cec5SDimitry Andric         break;
51810b57cec5SDimitry Andric       }
51820b57cec5SDimitry Andric 
51830b57cec5SDimitry Andric       if (Opc) {
51840b57cec5SDimitry Andric         unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;
51850b57cec5SDimitry Andric         SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,
51860b57cec5SDimitry Andric                                              Node->getOperand(2), SDValue());
518706c3fb27SDimitry Andric         SDValue InGlue = Chain.getValue(1);
51880b57cec5SDimitry Andric 
51890b57cec5SDimitry Andric         if (IntNo == Intrinsic::x86_sse3_monitor ||
51900b57cec5SDimitry Andric             IntNo == Intrinsic::x86_monitorx) {
51910b57cec5SDimitry Andric           // Copy the other two operands to ECX and EDX.
51920b57cec5SDimitry Andric           Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),
519306c3fb27SDimitry Andric                                        InGlue);
519406c3fb27SDimitry Andric           InGlue = Chain.getValue(1);
51950b57cec5SDimitry Andric           Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),
519606c3fb27SDimitry Andric                                        InGlue);
519706c3fb27SDimitry Andric           InGlue = Chain.getValue(1);
51980b57cec5SDimitry Andric         }
51990b57cec5SDimitry Andric 
52000b57cec5SDimitry Andric         MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
520106c3fb27SDimitry Andric                                                       { Chain, InGlue});
52020b57cec5SDimitry Andric         ReplaceNode(Node, CNode);
52030b57cec5SDimitry Andric         return;
52040b57cec5SDimitry Andric       }
5205480093f4SDimitry Andric 
5206480093f4SDimitry Andric       break;
52070b57cec5SDimitry Andric     }
5208e8d8bef9SDimitry Andric     case Intrinsic::x86_tilestored64_internal: {
5209*0fca6ea1SDimitry Andric       auto *MFI =
5210*0fca6ea1SDimitry Andric           CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5211*0fca6ea1SDimitry Andric       MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);
5212e8d8bef9SDimitry Andric       unsigned Opc = X86::PTILESTOREDV;
5213e8d8bef9SDimitry Andric       // _tile_stored_internal(row, col, buf, STRIDE, c)
5214e8d8bef9SDimitry Andric       SDValue Base = Node->getOperand(4);
5215e8d8bef9SDimitry Andric       SDValue Scale = getI8Imm(1, dl);
5216e8d8bef9SDimitry Andric       SDValue Index = Node->getOperand(5);
5217e8d8bef9SDimitry Andric       SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
5218e8d8bef9SDimitry Andric       SDValue Segment = CurDAG->getRegister(0, MVT::i16);
5219e8d8bef9SDimitry Andric       SDValue Chain = Node->getOperand(0);
5220e8d8bef9SDimitry Andric       MachineSDNode *CNode;
5221e8d8bef9SDimitry Andric       SDValue Ops[] = {Node->getOperand(2),
5222e8d8bef9SDimitry Andric                        Node->getOperand(3),
5223e8d8bef9SDimitry Andric                        Base,
5224e8d8bef9SDimitry Andric                        Scale,
5225e8d8bef9SDimitry Andric                        Index,
5226e8d8bef9SDimitry Andric                        Disp,
5227e8d8bef9SDimitry Andric                        Segment,
5228e8d8bef9SDimitry Andric                        Node->getOperand(6),
5229e8d8bef9SDimitry Andric                        Chain};
5230e8d8bef9SDimitry Andric       CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
5231e8d8bef9SDimitry Andric       ReplaceNode(Node, CNode);
5232e8d8bef9SDimitry Andric       return;
5233e8d8bef9SDimitry Andric     }
52345ffd83dbSDimitry Andric     case Intrinsic::x86_tileloadd64:
52355ffd83dbSDimitry Andric     case Intrinsic::x86_tileloaddt164:
52365ffd83dbSDimitry Andric     case Intrinsic::x86_tilestored64: {
52375ffd83dbSDimitry Andric       if (!Subtarget->hasAMXTILE())
52385ffd83dbSDimitry Andric         break;
5239*0fca6ea1SDimitry Andric       auto *MFI =
5240*0fca6ea1SDimitry Andric           CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5241*0fca6ea1SDimitry Andric       MFI->setAMXProgModel(AMXProgModelEnum::DirectReg);
52425ffd83dbSDimitry Andric       unsigned Opc;
52435ffd83dbSDimitry Andric       switch (IntNo) {
52445ffd83dbSDimitry Andric       default: llvm_unreachable("Unexpected intrinsic!");
52455ffd83dbSDimitry Andric       case Intrinsic::x86_tileloadd64:   Opc = X86::PTILELOADD; break;
52465ffd83dbSDimitry Andric       case Intrinsic::x86_tileloaddt164: Opc = X86::PTILELOADDT1; break;
52475ffd83dbSDimitry Andric       case Intrinsic::x86_tilestored64:  Opc = X86::PTILESTORED; break;
52480b57cec5SDimitry Andric       }
52495ffd83dbSDimitry Andric       // FIXME: Match displacement and scale.
52505ffd83dbSDimitry Andric       unsigned TIndex = Node->getConstantOperandVal(2);
52515ffd83dbSDimitry Andric       SDValue TReg = getI8Imm(TIndex, dl);
52525ffd83dbSDimitry Andric       SDValue Base = Node->getOperand(3);
52535ffd83dbSDimitry Andric       SDValue Scale = getI8Imm(1, dl);
52545ffd83dbSDimitry Andric       SDValue Index = Node->getOperand(4);
52555ffd83dbSDimitry Andric       SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
52565ffd83dbSDimitry Andric       SDValue Segment = CurDAG->getRegister(0, MVT::i16);
52575ffd83dbSDimitry Andric       SDValue Chain = Node->getOperand(0);
52585ffd83dbSDimitry Andric       MachineSDNode *CNode;
52595ffd83dbSDimitry Andric       if (Opc == X86::PTILESTORED) {
52605ffd83dbSDimitry Andric         SDValue Ops[] = { Base, Scale, Index, Disp, Segment, TReg, Chain };
52615ffd83dbSDimitry Andric         CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
52625ffd83dbSDimitry Andric       } else {
52635ffd83dbSDimitry Andric         SDValue Ops[] = { TReg, Base, Scale, Index, Disp, Segment, Chain };
52645ffd83dbSDimitry Andric         CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
52655ffd83dbSDimitry Andric       }
52665ffd83dbSDimitry Andric       ReplaceNode(Node, CNode);
52675ffd83dbSDimitry Andric       return;
52685ffd83dbSDimitry Andric     }
52695ffd83dbSDimitry Andric     }
52700b57cec5SDimitry Andric     break;
52710b57cec5SDimitry Andric   }
5272fe6060f1SDimitry Andric   case ISD::BRIND:
5273fe6060f1SDimitry Andric   case X86ISD::NT_BRIND: {
52740b57cec5SDimitry Andric     if (Subtarget->isTargetNaCl())
52750b57cec5SDimitry Andric       // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
52760b57cec5SDimitry Andric       // leave the instruction alone.
52770b57cec5SDimitry Andric       break;
52780b57cec5SDimitry Andric     if (Subtarget->isTarget64BitILP32()) {
52790b57cec5SDimitry Andric       // Converts a 32-bit register to a 64-bit, zero-extended version of
52800b57cec5SDimitry Andric       // it. This is needed because x86-64 can do many things, but jmp %r32
52810b57cec5SDimitry Andric       // ain't one of them.
52825ffd83dbSDimitry Andric       SDValue Target = Node->getOperand(1);
52835ffd83dbSDimitry Andric       assert(Target.getValueType() == MVT::i32 && "Unexpected VT!");
52845ffd83dbSDimitry Andric       SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, MVT::i64);
5285fe6060f1SDimitry Andric       SDValue Brind = CurDAG->getNode(Opcode, dl, MVT::Other,
52860b57cec5SDimitry Andric                                       Node->getOperand(0), ZextTarget);
52870b57cec5SDimitry Andric       ReplaceNode(Node, Brind.getNode());
52880b57cec5SDimitry Andric       SelectCode(ZextTarget.getNode());
52890b57cec5SDimitry Andric       SelectCode(Brind.getNode());
52900b57cec5SDimitry Andric       return;
52910b57cec5SDimitry Andric     }
52920b57cec5SDimitry Andric     break;
52930b57cec5SDimitry Andric   }
52940b57cec5SDimitry Andric   case X86ISD::GlobalBaseReg:
52950b57cec5SDimitry Andric     ReplaceNode(Node, getGlobalBaseReg());
52960b57cec5SDimitry Andric     return;
52970b57cec5SDimitry Andric 
52980b57cec5SDimitry Andric   case ISD::BITCAST:
52990b57cec5SDimitry Andric     // Just drop all 128/256/512-bit bitcasts.
53000b57cec5SDimitry Andric     if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
53010b57cec5SDimitry Andric         NVT == MVT::f128) {
53020b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
53030b57cec5SDimitry Andric       CurDAG->RemoveDeadNode(Node);
53040b57cec5SDimitry Andric       return;
53050b57cec5SDimitry Andric     }
53060b57cec5SDimitry Andric     break;
53070b57cec5SDimitry Andric 
53080b57cec5SDimitry Andric   case ISD::SRL:
53090b57cec5SDimitry Andric     if (matchBitExtract(Node))
53100b57cec5SDimitry Andric       return;
5311bdd1243dSDimitry Andric     [[fallthrough]];
53120b57cec5SDimitry Andric   case ISD::SRA:
53130b57cec5SDimitry Andric   case ISD::SHL:
53140b57cec5SDimitry Andric     if (tryShiftAmountMod(Node))
53150b57cec5SDimitry Andric       return;
53160b57cec5SDimitry Andric     break;
53170b57cec5SDimitry Andric 
5318e8d8bef9SDimitry Andric   case X86ISD::VPTERNLOG: {
5319647cbc5dSDimitry Andric     uint8_t Imm = Node->getConstantOperandVal(3);
5320349cc55cSDimitry Andric     if (matchVPTERNLOG(Node, Node, Node, Node, Node->getOperand(0),
5321e8d8bef9SDimitry Andric                        Node->getOperand(1), Node->getOperand(2), Imm))
5322e8d8bef9SDimitry Andric       return;
5323e8d8bef9SDimitry Andric     break;
5324e8d8bef9SDimitry Andric   }
5325e8d8bef9SDimitry Andric 
5326e8d8bef9SDimitry Andric   case X86ISD::ANDNP:
5327e8d8bef9SDimitry Andric     if (tryVPTERNLOG(Node))
5328e8d8bef9SDimitry Andric       return;
5329e8d8bef9SDimitry Andric     break;
5330e8d8bef9SDimitry Andric 
53310b57cec5SDimitry Andric   case ISD::AND:
53320b57cec5SDimitry Andric     if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) {
53330b57cec5SDimitry Andric       // Try to form a masked VPTESTM. Operands can be in either order.
53340b57cec5SDimitry Andric       SDValue N0 = Node->getOperand(0);
53350b57cec5SDimitry Andric       SDValue N1 = Node->getOperand(1);
53360b57cec5SDimitry Andric       if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() &&
53370b57cec5SDimitry Andric           tryVPTESTM(Node, N0, N1))
53380b57cec5SDimitry Andric         return;
53390b57cec5SDimitry Andric       if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
53400b57cec5SDimitry Andric           tryVPTESTM(Node, N1, N0))
53410b57cec5SDimitry Andric         return;
53420b57cec5SDimitry Andric     }
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric     if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
53450b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
53460b57cec5SDimitry Andric       CurDAG->RemoveDeadNode(Node);
53470b57cec5SDimitry Andric       return;
53480b57cec5SDimitry Andric     }
53490b57cec5SDimitry Andric     if (matchBitExtract(Node))
53500b57cec5SDimitry Andric       return;
53510b57cec5SDimitry Andric     if (AndImmShrink && shrinkAndImmediate(Node))
53520b57cec5SDimitry Andric       return;
53530b57cec5SDimitry Andric 
5354bdd1243dSDimitry Andric     [[fallthrough]];
53550b57cec5SDimitry Andric   case ISD::OR:
53560b57cec5SDimitry Andric   case ISD::XOR:
53570b57cec5SDimitry Andric     if (tryShrinkShlLogicImm(Node))
53580b57cec5SDimitry Andric       return;
53598bcb0991SDimitry Andric     if (Opcode == ISD::OR && tryMatchBitSelect(Node))
53608bcb0991SDimitry Andric       return;
53615ffd83dbSDimitry Andric     if (tryVPTERNLOG(Node))
53625ffd83dbSDimitry Andric       return;
53638bcb0991SDimitry Andric 
5364bdd1243dSDimitry Andric     [[fallthrough]];
53650b57cec5SDimitry Andric   case ISD::ADD:
536606c3fb27SDimitry Andric     if (Opcode == ISD::ADD && matchBitExtract(Node))
536706c3fb27SDimitry Andric       return;
536806c3fb27SDimitry Andric     [[fallthrough]];
53690b57cec5SDimitry Andric   case ISD::SUB: {
53700b57cec5SDimitry Andric     // Try to avoid folding immediates with multiple uses for optsize.
53710b57cec5SDimitry Andric     // This code tries to select to register form directly to avoid going
53720b57cec5SDimitry Andric     // through the isel table which might fold the immediate. We can't change
53730b57cec5SDimitry Andric     // the patterns on the add/sub/and/or/xor with immediate paterns in the
53740b57cec5SDimitry Andric     // tablegen files to check immediate use count without making the patterns
53750b57cec5SDimitry Andric     // unavailable to the fast-isel table.
53765ffd83dbSDimitry Andric     if (!CurDAG->shouldOptForSize())
53770b57cec5SDimitry Andric       break;
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric     // Only handle i8/i16/i32/i64.
53800b57cec5SDimitry Andric     if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64)
53810b57cec5SDimitry Andric       break;
53820b57cec5SDimitry Andric 
53830b57cec5SDimitry Andric     SDValue N0 = Node->getOperand(0);
53840b57cec5SDimitry Andric     SDValue N1 = Node->getOperand(1);
53850b57cec5SDimitry Andric 
5386bdd1243dSDimitry Andric     auto *Cst = dyn_cast<ConstantSDNode>(N1);
53870b57cec5SDimitry Andric     if (!Cst)
53880b57cec5SDimitry Andric       break;
53890b57cec5SDimitry Andric 
53900b57cec5SDimitry Andric     int64_t Val = Cst->getSExtValue();
53910b57cec5SDimitry Andric 
53920b57cec5SDimitry Andric     // Make sure its an immediate that is considered foldable.
53930b57cec5SDimitry Andric     // FIXME: Handle unsigned 32 bit immediates for 64-bit AND.
53940b57cec5SDimitry Andric     if (!isInt<8>(Val) && !isInt<32>(Val))
53950b57cec5SDimitry Andric       break;
53960b57cec5SDimitry Andric 
53978bcb0991SDimitry Andric     // If this can match to INC/DEC, let it go.
53988bcb0991SDimitry Andric     if (Opcode == ISD::ADD && (Val == 1 || Val == -1))
53998bcb0991SDimitry Andric       break;
54008bcb0991SDimitry Andric 
54010b57cec5SDimitry Andric     // Check if we should avoid folding this immediate.
54020b57cec5SDimitry Andric     if (!shouldAvoidImmediateInstFormsForSize(N1.getNode()))
54030b57cec5SDimitry Andric       break;
54040b57cec5SDimitry Andric 
54050b57cec5SDimitry Andric     // We should not fold the immediate. So we need a register form instead.
54060b57cec5SDimitry Andric     unsigned ROpc, MOpc;
54070b57cec5SDimitry Andric     switch (NVT.SimpleTy) {
54080b57cec5SDimitry Andric     default: llvm_unreachable("Unexpected VT!");
54090b57cec5SDimitry Andric     case MVT::i8:
54100b57cec5SDimitry Andric       switch (Opcode) {
54110b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
5412*0fca6ea1SDimitry Andric       case ISD::ADD:
5413*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::ADD8rr);
5414*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::ADD8rm);
5415*0fca6ea1SDimitry Andric         break;
5416*0fca6ea1SDimitry Andric       case ISD::SUB:
5417*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::SUB8rr);
5418*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::SUB8rm);
5419*0fca6ea1SDimitry Andric         break;
5420*0fca6ea1SDimitry Andric       case ISD::AND:
5421*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::AND8rr);
5422*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::AND8rm);
5423*0fca6ea1SDimitry Andric         break;
5424*0fca6ea1SDimitry Andric       case ISD::OR:
5425*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::OR8rr);
5426*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::OR8rm);
5427*0fca6ea1SDimitry Andric         break;
5428*0fca6ea1SDimitry Andric       case ISD::XOR:
5429*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::XOR8rr);
5430*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::XOR8rm);
5431*0fca6ea1SDimitry Andric         break;
54320b57cec5SDimitry Andric       }
54330b57cec5SDimitry Andric       break;
54340b57cec5SDimitry Andric     case MVT::i16:
54350b57cec5SDimitry Andric       switch (Opcode) {
54360b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
5437*0fca6ea1SDimitry Andric       case ISD::ADD:
5438*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::ADD16rr);
5439*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::ADD16rm);
5440*0fca6ea1SDimitry Andric         break;
5441*0fca6ea1SDimitry Andric       case ISD::SUB:
5442*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::SUB16rr);
5443*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::SUB16rm);
5444*0fca6ea1SDimitry Andric         break;
5445*0fca6ea1SDimitry Andric       case ISD::AND:
5446*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::AND16rr);
5447*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::AND16rm);
5448*0fca6ea1SDimitry Andric         break;
5449*0fca6ea1SDimitry Andric       case ISD::OR:
5450*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::OR16rr);
5451*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::OR16rm);
5452*0fca6ea1SDimitry Andric         break;
5453*0fca6ea1SDimitry Andric       case ISD::XOR:
5454*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::XOR16rr);
5455*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::XOR16rm);
5456*0fca6ea1SDimitry Andric         break;
54570b57cec5SDimitry Andric       }
54580b57cec5SDimitry Andric       break;
54590b57cec5SDimitry Andric     case MVT::i32:
54600b57cec5SDimitry Andric       switch (Opcode) {
54610b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
5462*0fca6ea1SDimitry Andric       case ISD::ADD:
5463*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::ADD32rr);
5464*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::ADD32rm);
5465*0fca6ea1SDimitry Andric         break;
5466*0fca6ea1SDimitry Andric       case ISD::SUB:
5467*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::SUB32rr);
5468*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::SUB32rm);
5469*0fca6ea1SDimitry Andric         break;
5470*0fca6ea1SDimitry Andric       case ISD::AND:
5471*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::AND32rr);
5472*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::AND32rm);
5473*0fca6ea1SDimitry Andric         break;
5474*0fca6ea1SDimitry Andric       case ISD::OR:
5475*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::OR32rr);
5476*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::OR32rm);
5477*0fca6ea1SDimitry Andric         break;
5478*0fca6ea1SDimitry Andric       case ISD::XOR:
5479*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::XOR32rr);
5480*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::XOR32rm);
5481*0fca6ea1SDimitry Andric         break;
54820b57cec5SDimitry Andric       }
54830b57cec5SDimitry Andric       break;
54840b57cec5SDimitry Andric     case MVT::i64:
54850b57cec5SDimitry Andric       switch (Opcode) {
54860b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected opcode!");
5487*0fca6ea1SDimitry Andric       case ISD::ADD:
5488*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::ADD64rr);
5489*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::ADD64rm);
5490*0fca6ea1SDimitry Andric         break;
5491*0fca6ea1SDimitry Andric       case ISD::SUB:
5492*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::SUB64rr);
5493*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::SUB64rm);
5494*0fca6ea1SDimitry Andric         break;
5495*0fca6ea1SDimitry Andric       case ISD::AND:
5496*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::AND64rr);
5497*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::AND64rm);
5498*0fca6ea1SDimitry Andric         break;
5499*0fca6ea1SDimitry Andric       case ISD::OR:
5500*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::OR64rr);
5501*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::OR64rm);
5502*0fca6ea1SDimitry Andric         break;
5503*0fca6ea1SDimitry Andric       case ISD::XOR:
5504*0fca6ea1SDimitry Andric         ROpc = GET_ND_IF_ENABLED(X86::XOR64rr);
5505*0fca6ea1SDimitry Andric         MOpc = GET_ND_IF_ENABLED(X86::XOR64rm);
5506*0fca6ea1SDimitry Andric         break;
55070b57cec5SDimitry Andric       }
55080b57cec5SDimitry Andric       break;
55090b57cec5SDimitry Andric     }
55100b57cec5SDimitry Andric 
55110b57cec5SDimitry Andric     // Ok this is a AND/OR/XOR/ADD/SUB with constant.
55120b57cec5SDimitry Andric 
55130b57cec5SDimitry Andric     // If this is a not a subtract, we can still try to fold a load.
55140b57cec5SDimitry Andric     if (Opcode != ISD::SUB) {
55150b57cec5SDimitry Andric       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
55160b57cec5SDimitry Andric       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
55170b57cec5SDimitry Andric         SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
55180b57cec5SDimitry Andric         SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
55190b57cec5SDimitry Andric         MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
55200b57cec5SDimitry Andric         // Update the chain.
55210b57cec5SDimitry Andric         ReplaceUses(N0.getValue(1), SDValue(CNode, 2));
55220b57cec5SDimitry Andric         // Record the mem-refs
55230b57cec5SDimitry Andric         CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()});
55240b57cec5SDimitry Andric         ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
55250b57cec5SDimitry Andric         CurDAG->RemoveDeadNode(Node);
55260b57cec5SDimitry Andric         return;
55270b57cec5SDimitry Andric       }
55280b57cec5SDimitry Andric     }
55290b57cec5SDimitry Andric 
55300b57cec5SDimitry Andric     CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1);
55310b57cec5SDimitry Andric     return;
55320b57cec5SDimitry Andric   }
55330b57cec5SDimitry Andric 
55340b57cec5SDimitry Andric   case X86ISD::SMUL:
55350b57cec5SDimitry Andric     // i16/i32/i64 are handled with isel patterns.
55360b57cec5SDimitry Andric     if (NVT != MVT::i8)
55370b57cec5SDimitry Andric       break;
5538bdd1243dSDimitry Andric     [[fallthrough]];
55390b57cec5SDimitry Andric   case X86ISD::UMUL: {
55400b57cec5SDimitry Andric     SDValue N0 = Node->getOperand(0);
55410b57cec5SDimitry Andric     SDValue N1 = Node->getOperand(1);
55420b57cec5SDimitry Andric 
55430b57cec5SDimitry Andric     unsigned LoReg, ROpc, MOpc;
55440b57cec5SDimitry Andric     switch (NVT.SimpleTy) {
55450b57cec5SDimitry Andric     default: llvm_unreachable("Unsupported VT!");
55460b57cec5SDimitry Andric     case MVT::i8:
55470b57cec5SDimitry Andric       LoReg = X86::AL;
55480b57cec5SDimitry Andric       ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;
55490b57cec5SDimitry Andric       MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;
55500b57cec5SDimitry Andric       break;
55510b57cec5SDimitry Andric     case MVT::i16:
55520b57cec5SDimitry Andric       LoReg = X86::AX;
55530b57cec5SDimitry Andric       ROpc = X86::MUL16r;
55540b57cec5SDimitry Andric       MOpc = X86::MUL16m;
55550b57cec5SDimitry Andric       break;
55560b57cec5SDimitry Andric     case MVT::i32:
55570b57cec5SDimitry Andric       LoReg = X86::EAX;
55580b57cec5SDimitry Andric       ROpc = X86::MUL32r;
55590b57cec5SDimitry Andric       MOpc = X86::MUL32m;
55600b57cec5SDimitry Andric       break;
55610b57cec5SDimitry Andric     case MVT::i64:
55620b57cec5SDimitry Andric       LoReg = X86::RAX;
55630b57cec5SDimitry Andric       ROpc = X86::MUL64r;
55640b57cec5SDimitry Andric       MOpc = X86::MUL64m;
55650b57cec5SDimitry Andric       break;
55660b57cec5SDimitry Andric     }
55670b57cec5SDimitry Andric 
55680b57cec5SDimitry Andric     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
55690b57cec5SDimitry Andric     bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
55705ffd83dbSDimitry Andric     // Multiply is commutative.
55710b57cec5SDimitry Andric     if (!FoldedLoad) {
55720b57cec5SDimitry Andric       FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
55730b57cec5SDimitry Andric       if (FoldedLoad)
55740b57cec5SDimitry Andric         std::swap(N0, N1);
55750b57cec5SDimitry Andric     }
55760b57cec5SDimitry Andric 
557706c3fb27SDimitry Andric     SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
55780b57cec5SDimitry Andric                                           N0, SDValue()).getValue(1);
55790b57cec5SDimitry Andric 
55800b57cec5SDimitry Andric     MachineSDNode *CNode;
55810b57cec5SDimitry Andric     if (FoldedLoad) {
55820b57cec5SDimitry Andric       // i16/i32/i64 use an instruction that produces a low and high result even
55830b57cec5SDimitry Andric       // though only the low result is used.
55840b57cec5SDimitry Andric       SDVTList VTs;
55850b57cec5SDimitry Andric       if (NVT == MVT::i8)
55860b57cec5SDimitry Andric         VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
55870b57cec5SDimitry Andric       else
55880b57cec5SDimitry Andric         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);
55890b57cec5SDimitry Andric 
55900b57cec5SDimitry Andric       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
559106c3fb27SDimitry Andric                         InGlue };
55920b57cec5SDimitry Andric       CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
55930b57cec5SDimitry Andric 
55940b57cec5SDimitry Andric       // Update the chain.
55950b57cec5SDimitry Andric       ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));
55960b57cec5SDimitry Andric       // Record the mem-refs
55970b57cec5SDimitry Andric       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
55980b57cec5SDimitry Andric     } else {
55990b57cec5SDimitry Andric       // i16/i32/i64 use an instruction that produces a low and high result even
56000b57cec5SDimitry Andric       // though only the low result is used.
56010b57cec5SDimitry Andric       SDVTList VTs;
56020b57cec5SDimitry Andric       if (NVT == MVT::i8)
56030b57cec5SDimitry Andric         VTs = CurDAG->getVTList(NVT, MVT::i32);
56040b57cec5SDimitry Andric       else
56050b57cec5SDimitry Andric         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
56060b57cec5SDimitry Andric 
560706c3fb27SDimitry Andric       CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InGlue});
56080b57cec5SDimitry Andric     }
56090b57cec5SDimitry Andric 
56100b57cec5SDimitry Andric     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
56110b57cec5SDimitry Andric     ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));
56120b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(Node);
56130b57cec5SDimitry Andric     return;
56140b57cec5SDimitry Andric   }
56150b57cec5SDimitry Andric 
56160b57cec5SDimitry Andric   case ISD::SMUL_LOHI:
56170b57cec5SDimitry Andric   case ISD::UMUL_LOHI: {
56180b57cec5SDimitry Andric     SDValue N0 = Node->getOperand(0);
56190b57cec5SDimitry Andric     SDValue N1 = Node->getOperand(1);
56200b57cec5SDimitry Andric 
56210b57cec5SDimitry Andric     unsigned Opc, MOpc;
56225ffd83dbSDimitry Andric     unsigned LoReg, HiReg;
56235ffd83dbSDimitry Andric     bool IsSigned = Opcode == ISD::SMUL_LOHI;
56245ffd83dbSDimitry Andric     bool UseMULX = !IsSigned && Subtarget->hasBMI2();
56255ffd83dbSDimitry Andric     bool UseMULXHi = UseMULX && SDValue(Node, 0).use_empty();
56260b57cec5SDimitry Andric     switch (NVT.SimpleTy) {
56270b57cec5SDimitry Andric     default: llvm_unreachable("Unsupported VT!");
56285ffd83dbSDimitry Andric     case MVT::i32:
56297a6dacacSDimitry Andric       Opc = UseMULXHi  ? X86::MULX32Hrr
56307a6dacacSDimitry Andric             : UseMULX  ? GET_EGPR_IF_ENABLED(X86::MULX32rr)
56317a6dacacSDimitry Andric             : IsSigned ? X86::IMUL32r
56327a6dacacSDimitry Andric                        : X86::MUL32r;
56337a6dacacSDimitry Andric       MOpc = UseMULXHi  ? X86::MULX32Hrm
56347a6dacacSDimitry Andric              : UseMULX  ? GET_EGPR_IF_ENABLED(X86::MULX32rm)
56357a6dacacSDimitry Andric              : IsSigned ? X86::IMUL32m
56367a6dacacSDimitry Andric                         : X86::MUL32m;
56375ffd83dbSDimitry Andric       LoReg = UseMULX ? X86::EDX : X86::EAX;
56385ffd83dbSDimitry Andric       HiReg = X86::EDX;
56390b57cec5SDimitry Andric       break;
56405ffd83dbSDimitry Andric     case MVT::i64:
56417a6dacacSDimitry Andric       Opc = UseMULXHi  ? X86::MULX64Hrr
56427a6dacacSDimitry Andric             : UseMULX  ? GET_EGPR_IF_ENABLED(X86::MULX64rr)
56437a6dacacSDimitry Andric             : IsSigned ? X86::IMUL64r
56447a6dacacSDimitry Andric                        : X86::MUL64r;
56457a6dacacSDimitry Andric       MOpc = UseMULXHi  ? X86::MULX64Hrm
56467a6dacacSDimitry Andric              : UseMULX  ? GET_EGPR_IF_ENABLED(X86::MULX64rm)
56477a6dacacSDimitry Andric              : IsSigned ? X86::IMUL64m
56487a6dacacSDimitry Andric                         : X86::MUL64m;
56495ffd83dbSDimitry Andric       LoReg = UseMULX ? X86::RDX : X86::RAX;
56505ffd83dbSDimitry Andric       HiReg = X86::RDX;
56510b57cec5SDimitry Andric       break;
56520b57cec5SDimitry Andric     }
56530b57cec5SDimitry Andric 
56540b57cec5SDimitry Andric     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
56550b57cec5SDimitry Andric     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
5656bdd1243dSDimitry Andric     // Multiply is commutative.
56570b57cec5SDimitry Andric     if (!foldedLoad) {
56580b57cec5SDimitry Andric       foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
56590b57cec5SDimitry Andric       if (foldedLoad)
56600b57cec5SDimitry Andric         std::swap(N0, N1);
56610b57cec5SDimitry Andric     }
56620b57cec5SDimitry Andric 
566306c3fb27SDimitry Andric     SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
56640b57cec5SDimitry Andric                                           N0, SDValue()).getValue(1);
56655ffd83dbSDimitry Andric     SDValue ResHi, ResLo;
56660b57cec5SDimitry Andric     if (foldedLoad) {
56670b57cec5SDimitry Andric       SDValue Chain;
56680b57cec5SDimitry Andric       MachineSDNode *CNode = nullptr;
56690b57cec5SDimitry Andric       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
567006c3fb27SDimitry Andric                         InGlue };
56715ffd83dbSDimitry Andric       if (UseMULXHi) {
56725ffd83dbSDimitry Andric         SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
56735ffd83dbSDimitry Andric         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
56745ffd83dbSDimitry Andric         ResHi = SDValue(CNode, 0);
56755ffd83dbSDimitry Andric         Chain = SDValue(CNode, 1);
56765ffd83dbSDimitry Andric       } else if (UseMULX) {
56775ffd83dbSDimitry Andric         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other);
56785ffd83dbSDimitry Andric         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
56795ffd83dbSDimitry Andric         ResHi = SDValue(CNode, 0);
56805ffd83dbSDimitry Andric         ResLo = SDValue(CNode, 1);
56815ffd83dbSDimitry Andric         Chain = SDValue(CNode, 2);
56825ffd83dbSDimitry Andric       } else {
56830b57cec5SDimitry Andric         SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
56840b57cec5SDimitry Andric         CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
56850b57cec5SDimitry Andric         Chain = SDValue(CNode, 0);
568606c3fb27SDimitry Andric         InGlue = SDValue(CNode, 1);
56875ffd83dbSDimitry Andric       }
56880b57cec5SDimitry Andric 
56890b57cec5SDimitry Andric       // Update the chain.
56900b57cec5SDimitry Andric       ReplaceUses(N1.getValue(1), Chain);
56910b57cec5SDimitry Andric       // Record the mem-refs
56920b57cec5SDimitry Andric       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
56930b57cec5SDimitry Andric     } else {
569406c3fb27SDimitry Andric       SDValue Ops[] = { N1, InGlue };
56955ffd83dbSDimitry Andric       if (UseMULXHi) {
56965ffd83dbSDimitry Andric         SDVTList VTs = CurDAG->getVTList(NVT);
56975ffd83dbSDimitry Andric         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
56985ffd83dbSDimitry Andric         ResHi = SDValue(CNode, 0);
56995ffd83dbSDimitry Andric       } else if (UseMULX) {
57005ffd83dbSDimitry Andric         SDVTList VTs = CurDAG->getVTList(NVT, NVT);
57015ffd83dbSDimitry Andric         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
57025ffd83dbSDimitry Andric         ResHi = SDValue(CNode, 0);
57035ffd83dbSDimitry Andric         ResLo = SDValue(CNode, 1);
57045ffd83dbSDimitry Andric       } else {
57050b57cec5SDimitry Andric         SDVTList VTs = CurDAG->getVTList(MVT::Glue);
57060b57cec5SDimitry Andric         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
570706c3fb27SDimitry Andric         InGlue = SDValue(CNode, 0);
57080b57cec5SDimitry Andric       }
57095ffd83dbSDimitry Andric     }
57100b57cec5SDimitry Andric 
57110b57cec5SDimitry Andric     // Copy the low half of the result, if it is needed.
57120b57cec5SDimitry Andric     if (!SDValue(Node, 0).use_empty()) {
57135ffd83dbSDimitry Andric       if (!ResLo) {
57140b57cec5SDimitry Andric         assert(LoReg && "Register for low half is not defined!");
57155ffd83dbSDimitry Andric         ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,
571606c3fb27SDimitry Andric                                        NVT, InGlue);
571706c3fb27SDimitry Andric         InGlue = ResLo.getValue(2);
57185ffd83dbSDimitry Andric       }
57190b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 0), ResLo);
57200b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
57210b57cec5SDimitry Andric                  dbgs() << '\n');
57220b57cec5SDimitry Andric     }
57230b57cec5SDimitry Andric     // Copy the high half of the result, if it is needed.
57240b57cec5SDimitry Andric     if (!SDValue(Node, 1).use_empty()) {
57255ffd83dbSDimitry Andric       if (!ResHi) {
57260b57cec5SDimitry Andric         assert(HiReg && "Register for high half is not defined!");
57275ffd83dbSDimitry Andric         ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,
572806c3fb27SDimitry Andric                                        NVT, InGlue);
572906c3fb27SDimitry Andric         InGlue = ResHi.getValue(2);
57305ffd83dbSDimitry Andric       }
57310b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 1), ResHi);
57320b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
57330b57cec5SDimitry Andric                  dbgs() << '\n');
57340b57cec5SDimitry Andric     }
57350b57cec5SDimitry Andric 
57360b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(Node);
57370b57cec5SDimitry Andric     return;
57380b57cec5SDimitry Andric   }
57390b57cec5SDimitry Andric 
57400b57cec5SDimitry Andric   case ISD::SDIVREM:
57410b57cec5SDimitry Andric   case ISD::UDIVREM: {
57420b57cec5SDimitry Andric     SDValue N0 = Node->getOperand(0);
57430b57cec5SDimitry Andric     SDValue N1 = Node->getOperand(1);
57440b57cec5SDimitry Andric 
57455ffd83dbSDimitry Andric     unsigned ROpc, MOpc;
57460b57cec5SDimitry Andric     bool isSigned = Opcode == ISD::SDIVREM;
57470b57cec5SDimitry Andric     if (!isSigned) {
57480b57cec5SDimitry Andric       switch (NVT.SimpleTy) {
57490b57cec5SDimitry Andric       default: llvm_unreachable("Unsupported VT!");
57505ffd83dbSDimitry Andric       case MVT::i8:  ROpc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
57515ffd83dbSDimitry Andric       case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break;
57525ffd83dbSDimitry Andric       case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break;
57535ffd83dbSDimitry Andric       case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break;
57540b57cec5SDimitry Andric       }
57550b57cec5SDimitry Andric     } else {
57560b57cec5SDimitry Andric       switch (NVT.SimpleTy) {
57570b57cec5SDimitry Andric       default: llvm_unreachable("Unsupported VT!");
57585ffd83dbSDimitry Andric       case MVT::i8:  ROpc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
57595ffd83dbSDimitry Andric       case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
57605ffd83dbSDimitry Andric       case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
57615ffd83dbSDimitry Andric       case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
57620b57cec5SDimitry Andric       }
57630b57cec5SDimitry Andric     }
57640b57cec5SDimitry Andric 
57650b57cec5SDimitry Andric     unsigned LoReg, HiReg, ClrReg;
57660b57cec5SDimitry Andric     unsigned SExtOpcode;
57670b57cec5SDimitry Andric     switch (NVT.SimpleTy) {
57680b57cec5SDimitry Andric     default: llvm_unreachable("Unsupported VT!");
57690b57cec5SDimitry Andric     case MVT::i8:
57700b57cec5SDimitry Andric       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
57718bcb0991SDimitry Andric       SExtOpcode = 0; // Not used.
57720b57cec5SDimitry Andric       break;
57730b57cec5SDimitry Andric     case MVT::i16:
57740b57cec5SDimitry Andric       LoReg = X86::AX;  HiReg = X86::DX;
57750b57cec5SDimitry Andric       ClrReg = X86::DX;
57760b57cec5SDimitry Andric       SExtOpcode = X86::CWD;
57770b57cec5SDimitry Andric       break;
57780b57cec5SDimitry Andric     case MVT::i32:
57790b57cec5SDimitry Andric       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
57800b57cec5SDimitry Andric       SExtOpcode = X86::CDQ;
57810b57cec5SDimitry Andric       break;
57820b57cec5SDimitry Andric     case MVT::i64:
57830b57cec5SDimitry Andric       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
57840b57cec5SDimitry Andric       SExtOpcode = X86::CQO;
57850b57cec5SDimitry Andric       break;
57860b57cec5SDimitry Andric     }
57870b57cec5SDimitry Andric 
57880b57cec5SDimitry Andric     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
57890b57cec5SDimitry Andric     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
57900b57cec5SDimitry Andric     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
57910b57cec5SDimitry Andric 
579206c3fb27SDimitry Andric     SDValue InGlue;
57938bcb0991SDimitry Andric     if (NVT == MVT::i8) {
57940b57cec5SDimitry Andric       // Special case for div8, just use a move with zero extension to AX to
57950b57cec5SDimitry Andric       // clear the upper 8 bits (AH).
57960b57cec5SDimitry Andric       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
57970b57cec5SDimitry Andric       MachineSDNode *Move;
57980b57cec5SDimitry Andric       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
57990b57cec5SDimitry Andric         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
58008bcb0991SDimitry Andric         unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm8
58018bcb0991SDimitry Andric                                                     : X86::MOVZX16rm8;
58028bcb0991SDimitry Andric         Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops);
58030b57cec5SDimitry Andric         Chain = SDValue(Move, 1);
58040b57cec5SDimitry Andric         ReplaceUses(N0.getValue(1), Chain);
58050b57cec5SDimitry Andric         // Record the mem-refs
58060b57cec5SDimitry Andric         CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
58070b57cec5SDimitry Andric       } else {
58088bcb0991SDimitry Andric         unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr8
58098bcb0991SDimitry Andric                                                     : X86::MOVZX16rr8;
58108bcb0991SDimitry Andric         Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0);
58110b57cec5SDimitry Andric         Chain = CurDAG->getEntryNode();
58120b57cec5SDimitry Andric       }
58138bcb0991SDimitry Andric       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0),
58140b57cec5SDimitry Andric                                     SDValue());
581506c3fb27SDimitry Andric       InGlue = Chain.getValue(1);
58160b57cec5SDimitry Andric     } else {
581706c3fb27SDimitry Andric       InGlue =
58180b57cec5SDimitry Andric         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
58190b57cec5SDimitry Andric                              LoReg, N0, SDValue()).getValue(1);
58200b57cec5SDimitry Andric       if (isSigned && !signBitIsZero) {
58210b57cec5SDimitry Andric         // Sign extend the low part into the high part.
582206c3fb27SDimitry Andric         InGlue =
582306c3fb27SDimitry Andric           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InGlue),0);
58240b57cec5SDimitry Andric       } else {
58250b57cec5SDimitry Andric         // Zero out the high part, effectively zero extending the input.
58265ffd83dbSDimitry Andric         SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
5827bdd1243dSDimitry Andric         SDValue ClrNode = SDValue(
5828bdd1243dSDimitry Andric             CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, std::nullopt), 0);
58290b57cec5SDimitry Andric         switch (NVT.SimpleTy) {
58300b57cec5SDimitry Andric         case MVT::i16:
58310b57cec5SDimitry Andric           ClrNode =
58320b57cec5SDimitry Andric               SDValue(CurDAG->getMachineNode(
58330b57cec5SDimitry Andric                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
58340b57cec5SDimitry Andric                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
58350b57cec5SDimitry Andric                                                     MVT::i32)),
58360b57cec5SDimitry Andric                       0);
58370b57cec5SDimitry Andric           break;
58380b57cec5SDimitry Andric         case MVT::i32:
58390b57cec5SDimitry Andric           break;
58400b57cec5SDimitry Andric         case MVT::i64:
58410b57cec5SDimitry Andric           ClrNode =
58420b57cec5SDimitry Andric               SDValue(CurDAG->getMachineNode(
58430b57cec5SDimitry Andric                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
58440b57cec5SDimitry Andric                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
58450b57cec5SDimitry Andric                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
58460b57cec5SDimitry Andric                                                     MVT::i32)),
58470b57cec5SDimitry Andric                       0);
58480b57cec5SDimitry Andric           break;
58490b57cec5SDimitry Andric         default:
58500b57cec5SDimitry Andric           llvm_unreachable("Unexpected division source");
58510b57cec5SDimitry Andric         }
58520b57cec5SDimitry Andric 
585306c3fb27SDimitry Andric         InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
585406c3fb27SDimitry Andric                                       ClrNode, InGlue).getValue(1);
58550b57cec5SDimitry Andric       }
58560b57cec5SDimitry Andric     }
58570b57cec5SDimitry Andric 
58580b57cec5SDimitry Andric     if (foldedLoad) {
58590b57cec5SDimitry Andric       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
586006c3fb27SDimitry Andric                         InGlue };
58610b57cec5SDimitry Andric       MachineSDNode *CNode =
58620b57cec5SDimitry Andric         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
586306c3fb27SDimitry Andric       InGlue = SDValue(CNode, 1);
58640b57cec5SDimitry Andric       // Update the chain.
58650b57cec5SDimitry Andric       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
58660b57cec5SDimitry Andric       // Record the mem-refs
58670b57cec5SDimitry Andric       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
58680b57cec5SDimitry Andric     } else {
586906c3fb27SDimitry Andric       InGlue =
587006c3fb27SDimitry Andric         SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InGlue), 0);
58710b57cec5SDimitry Andric     }
58720b57cec5SDimitry Andric 
58730b57cec5SDimitry Andric     // Prevent use of AH in a REX instruction by explicitly copying it to
58740b57cec5SDimitry Andric     // an ABCD_L register.
58750b57cec5SDimitry Andric     //
58760b57cec5SDimitry Andric     // The current assumption of the register allocator is that isel
58770b57cec5SDimitry Andric     // won't generate explicit references to the GR8_ABCD_H registers. If
58780b57cec5SDimitry Andric     // the allocator and/or the backend get enhanced to be more robust in
58790b57cec5SDimitry Andric     // that regard, this can be, and should be, removed.
58800b57cec5SDimitry Andric     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
58810b57cec5SDimitry Andric       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
58820b57cec5SDimitry Andric       unsigned AHExtOpcode =
58830b57cec5SDimitry Andric           isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
58840b57cec5SDimitry Andric 
58850b57cec5SDimitry Andric       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
588606c3fb27SDimitry Andric                                              MVT::Glue, AHCopy, InGlue);
58870b57cec5SDimitry Andric       SDValue Result(RNode, 0);
588806c3fb27SDimitry Andric       InGlue = SDValue(RNode, 1);
58890b57cec5SDimitry Andric 
58900b57cec5SDimitry Andric       Result =
58910b57cec5SDimitry Andric           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
58920b57cec5SDimitry Andric 
58930b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 1), Result);
58940b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
58950b57cec5SDimitry Andric                  dbgs() << '\n');
58960b57cec5SDimitry Andric     }
58970b57cec5SDimitry Andric     // Copy the division (low) result, if it is needed.
58980b57cec5SDimitry Andric     if (!SDValue(Node, 0).use_empty()) {
58990b57cec5SDimitry Andric       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
590006c3fb27SDimitry Andric                                                 LoReg, NVT, InGlue);
590106c3fb27SDimitry Andric       InGlue = Result.getValue(2);
59020b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 0), Result);
59030b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
59040b57cec5SDimitry Andric                  dbgs() << '\n');
59050b57cec5SDimitry Andric     }
59060b57cec5SDimitry Andric     // Copy the remainder (high) result, if it is needed.
59070b57cec5SDimitry Andric     if (!SDValue(Node, 1).use_empty()) {
59080b57cec5SDimitry Andric       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
590906c3fb27SDimitry Andric                                               HiReg, NVT, InGlue);
591006c3fb27SDimitry Andric       InGlue = Result.getValue(2);
59110b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 1), Result);
59120b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
59130b57cec5SDimitry Andric                  dbgs() << '\n');
59140b57cec5SDimitry Andric     }
59150b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(Node);
59160b57cec5SDimitry Andric     return;
59170b57cec5SDimitry Andric   }
59180b57cec5SDimitry Andric 
59195ffd83dbSDimitry Andric   case X86ISD::FCMP:
59205ffd83dbSDimitry Andric   case X86ISD::STRICT_FCMP:
59215ffd83dbSDimitry Andric   case X86ISD::STRICT_FCMPS: {
59225ffd83dbSDimitry Andric     bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP ||
59235ffd83dbSDimitry Andric                        Node->getOpcode() == X86ISD::STRICT_FCMPS;
59245ffd83dbSDimitry Andric     SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0);
59255ffd83dbSDimitry Andric     SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1);
59265ffd83dbSDimitry Andric 
59275ffd83dbSDimitry Andric     // Save the original VT of the compare.
59285ffd83dbSDimitry Andric     MVT CmpVT = N0.getSimpleValueType();
59295ffd83dbSDimitry Andric 
59305ffd83dbSDimitry Andric     // Floating point needs special handling if we don't have FCOMI.
593181ad6265SDimitry Andric     if (Subtarget->canUseCMOV())
59325ffd83dbSDimitry Andric       break;
59335ffd83dbSDimitry Andric 
59345ffd83dbSDimitry Andric     bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS;
59355ffd83dbSDimitry Andric 
59365ffd83dbSDimitry Andric     unsigned Opc;
59375ffd83dbSDimitry Andric     switch (CmpVT.SimpleTy) {
59385ffd83dbSDimitry Andric     default: llvm_unreachable("Unexpected type!");
59395ffd83dbSDimitry Andric     case MVT::f32:
59405ffd83dbSDimitry Andric       Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32;
59415ffd83dbSDimitry Andric       break;
59425ffd83dbSDimitry Andric     case MVT::f64:
59435ffd83dbSDimitry Andric       Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64;
59445ffd83dbSDimitry Andric       break;
59455ffd83dbSDimitry Andric     case MVT::f80:
59465ffd83dbSDimitry Andric       Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80;
59475ffd83dbSDimitry Andric       break;
59485ffd83dbSDimitry Andric     }
59495ffd83dbSDimitry Andric 
59505ffd83dbSDimitry Andric     SDValue Chain =
59515ffd83dbSDimitry Andric         IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode();
5952fe6060f1SDimitry Andric     SDValue Glue;
59535ffd83dbSDimitry Andric     if (IsStrictCmp) {
5954fe6060f1SDimitry Andric       SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
5955fe6060f1SDimitry Andric       Chain = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0);
5956fe6060f1SDimitry Andric       Glue = Chain.getValue(1);
59575ffd83dbSDimitry Andric     } else {
5958fe6060f1SDimitry Andric       Glue = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N0, N1), 0);
59595ffd83dbSDimitry Andric     }
59605ffd83dbSDimitry Andric 
59615ffd83dbSDimitry Andric     // Move FPSW to AX.
59625ffd83dbSDimitry Andric     SDValue FNSTSW =
5963fe6060f1SDimitry Andric         SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, Glue), 0);
59645ffd83dbSDimitry Andric 
59655ffd83dbSDimitry Andric     // Extract upper 8-bits of AX.
59665ffd83dbSDimitry Andric     SDValue Extract =
59675ffd83dbSDimitry Andric         CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW);
59685ffd83dbSDimitry Andric 
59695ffd83dbSDimitry Andric     // Move AH into flags.
59705ffd83dbSDimitry Andric     // Some 64-bit targets lack SAHF support, but they do support FCOMI.
597181ad6265SDimitry Andric     assert(Subtarget->canUseLAHFSAHF() &&
59725ffd83dbSDimitry Andric            "Target doesn't support SAHF or FCOMI?");
59735ffd83dbSDimitry Andric     SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue());
59745ffd83dbSDimitry Andric     Chain = AH;
59755ffd83dbSDimitry Andric     SDValue SAHF = SDValue(
59765ffd83dbSDimitry Andric         CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0);
59775ffd83dbSDimitry Andric 
59785ffd83dbSDimitry Andric     if (IsStrictCmp)
59795ffd83dbSDimitry Andric       ReplaceUses(SDValue(Node, 1), Chain);
59805ffd83dbSDimitry Andric 
59815ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 0), SAHF);
59825ffd83dbSDimitry Andric     CurDAG->RemoveDeadNode(Node);
59835ffd83dbSDimitry Andric     return;
59845ffd83dbSDimitry Andric   }
59855ffd83dbSDimitry Andric 
59860b57cec5SDimitry Andric   case X86ISD::CMP: {
59870b57cec5SDimitry Andric     SDValue N0 = Node->getOperand(0);
59880b57cec5SDimitry Andric     SDValue N1 = Node->getOperand(1);
59890b57cec5SDimitry Andric 
59900b57cec5SDimitry Andric     // Optimizations for TEST compares.
59910b57cec5SDimitry Andric     if (!isNullConstant(N1))
59920b57cec5SDimitry Andric       break;
59930b57cec5SDimitry Andric 
59940b57cec5SDimitry Andric     // Save the original VT of the compare.
59950b57cec5SDimitry Andric     MVT CmpVT = N0.getSimpleValueType();
59960b57cec5SDimitry Andric 
59970b57cec5SDimitry Andric     // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
59980b57cec5SDimitry Andric     // by a test instruction. The test should be removed later by
59990b57cec5SDimitry Andric     // analyzeCompare if we are using only the zero flag.
60000b57cec5SDimitry Andric     // TODO: Should we check the users and use the BEXTR flags directly?
60010b57cec5SDimitry Andric     if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
60020b57cec5SDimitry Andric       if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
60030b57cec5SDimitry Andric         unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
60040b57cec5SDimitry Andric                                              : X86::TEST32rr;
60050b57cec5SDimitry Andric         SDValue BEXTR = SDValue(NewNode, 0);
60060b57cec5SDimitry Andric         NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
60070b57cec5SDimitry Andric         ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
60080b57cec5SDimitry Andric         CurDAG->RemoveDeadNode(Node);
60090b57cec5SDimitry Andric         return;
60100b57cec5SDimitry Andric       }
60110b57cec5SDimitry Andric     }
60120b57cec5SDimitry Andric 
60130b57cec5SDimitry Andric     // We can peek through truncates, but we need to be careful below.
60140b57cec5SDimitry Andric     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
60150b57cec5SDimitry Andric       N0 = N0.getOperand(0);
60160b57cec5SDimitry Andric 
60170b57cec5SDimitry Andric     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
60180b57cec5SDimitry Andric     // use a smaller encoding.
60190b57cec5SDimitry Andric     // Look past the truncate if CMP is the only use of it.
602081ad6265SDimitry Andric     if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
60210b57cec5SDimitry Andric         N0.getValueType() != MVT::i8) {
602281ad6265SDimitry Andric       auto *MaskC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
602381ad6265SDimitry Andric       if (!MaskC)
602481ad6265SDimitry Andric         break;
602581ad6265SDimitry Andric 
6026fe6060f1SDimitry Andric       // We may have looked through a truncate so mask off any bits that
6027fe6060f1SDimitry Andric       // shouldn't be part of the compare.
602881ad6265SDimitry Andric       uint64_t Mask = MaskC->getZExtValue();
6029fe6060f1SDimitry Andric       Mask &= maskTrailingOnes<uint64_t>(CmpVT.getScalarSizeInBits());
60300b57cec5SDimitry Andric 
603181ad6265SDimitry Andric       // Check if we can replace AND+IMM{32,64} with a shift. This is possible
603281ad6265SDimitry Andric       // for masks like 0xFF000000 or 0x00FFFFFF and if we care only about the
603381ad6265SDimitry Andric       // zero flag.
603481ad6265SDimitry Andric       if (CmpVT == MVT::i64 && !isInt<8>(Mask) && isShiftedMask_64(Mask) &&
60350b57cec5SDimitry Andric           onlyUsesZeroFlag(SDValue(Node, 0))) {
603681ad6265SDimitry Andric         unsigned ShiftOpcode = ISD::DELETED_NODE;
603781ad6265SDimitry Andric         unsigned ShiftAmt;
603881ad6265SDimitry Andric         unsigned SubRegIdx;
603981ad6265SDimitry Andric         MVT SubRegVT;
604081ad6265SDimitry Andric         unsigned TestOpcode;
604106c3fb27SDimitry Andric         unsigned LeadingZeros = llvm::countl_zero(Mask);
604206c3fb27SDimitry Andric         unsigned TrailingZeros = llvm::countr_zero(Mask);
604381ad6265SDimitry Andric 
604481ad6265SDimitry Andric         // With leading/trailing zeros, the transform is profitable if we can
604581ad6265SDimitry Andric         // eliminate a movabsq or shrink a 32-bit immediate to 8-bit without
604681ad6265SDimitry Andric         // incurring any extra register moves.
604781ad6265SDimitry Andric         bool SavesBytes = !isInt<32>(Mask) || N0.getOperand(0).hasOneUse();
604881ad6265SDimitry Andric         if (LeadingZeros == 0 && SavesBytes) {
604981ad6265SDimitry Andric           // If the mask covers the most significant bit, then we can replace
605081ad6265SDimitry Andric           // TEST+AND with a SHR and check eflags.
605181ad6265SDimitry Andric           // This emits a redundant TEST which is subsequently eliminated.
6052*0fca6ea1SDimitry Andric           ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
605381ad6265SDimitry Andric           ShiftAmt = TrailingZeros;
605481ad6265SDimitry Andric           SubRegIdx = 0;
605581ad6265SDimitry Andric           TestOpcode = X86::TEST64rr;
605681ad6265SDimitry Andric         } else if (TrailingZeros == 0 && SavesBytes) {
605781ad6265SDimitry Andric           // If the mask covers the least significant bit, then we can replace
605881ad6265SDimitry Andric           // TEST+AND with a SHL and check eflags.
605981ad6265SDimitry Andric           // This emits a redundant TEST which is subsequently eliminated.
6060*0fca6ea1SDimitry Andric           ShiftOpcode = GET_ND_IF_ENABLED(X86::SHL64ri);
606181ad6265SDimitry Andric           ShiftAmt = LeadingZeros;
606281ad6265SDimitry Andric           SubRegIdx = 0;
606381ad6265SDimitry Andric           TestOpcode = X86::TEST64rr;
606481ad6265SDimitry Andric         } else if (MaskC->hasOneUse() && !isInt<32>(Mask)) {
606581ad6265SDimitry Andric           // If the shifted mask extends into the high half and is 8/16/32 bits
606681ad6265SDimitry Andric           // wide, then replace it with a SHR and a TEST8rr/TEST16rr/TEST32rr.
606781ad6265SDimitry Andric           unsigned PopCount = 64 - LeadingZeros - TrailingZeros;
606881ad6265SDimitry Andric           if (PopCount == 8) {
6069*0fca6ea1SDimitry Andric             ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
607081ad6265SDimitry Andric             ShiftAmt = TrailingZeros;
607181ad6265SDimitry Andric             SubRegIdx = X86::sub_8bit;
607281ad6265SDimitry Andric             SubRegVT = MVT::i8;
607381ad6265SDimitry Andric             TestOpcode = X86::TEST8rr;
607481ad6265SDimitry Andric           } else if (PopCount == 16) {
6075*0fca6ea1SDimitry Andric             ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
607681ad6265SDimitry Andric             ShiftAmt = TrailingZeros;
607781ad6265SDimitry Andric             SubRegIdx = X86::sub_16bit;
607881ad6265SDimitry Andric             SubRegVT = MVT::i16;
607981ad6265SDimitry Andric             TestOpcode = X86::TEST16rr;
608081ad6265SDimitry Andric           } else if (PopCount == 32) {
6081*0fca6ea1SDimitry Andric             ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
608281ad6265SDimitry Andric             ShiftAmt = TrailingZeros;
608381ad6265SDimitry Andric             SubRegIdx = X86::sub_32bit;
608481ad6265SDimitry Andric             SubRegVT = MVT::i32;
608581ad6265SDimitry Andric             TestOpcode = X86::TEST32rr;
608681ad6265SDimitry Andric           }
608781ad6265SDimitry Andric         }
608881ad6265SDimitry Andric         if (ShiftOpcode != ISD::DELETED_NODE) {
608981ad6265SDimitry Andric           SDValue ShiftC = CurDAG->getTargetConstant(ShiftAmt, dl, MVT::i64);
609081ad6265SDimitry Andric           SDValue Shift = SDValue(
609181ad6265SDimitry Andric               CurDAG->getMachineNode(ShiftOpcode, dl, MVT::i64, MVT::i32,
609281ad6265SDimitry Andric                                      N0.getOperand(0), ShiftC),
609381ad6265SDimitry Andric               0);
609481ad6265SDimitry Andric           if (SubRegIdx != 0) {
609581ad6265SDimitry Andric             Shift =
609681ad6265SDimitry Andric                 CurDAG->getTargetExtractSubreg(SubRegIdx, dl, SubRegVT, Shift);
609781ad6265SDimitry Andric           }
609881ad6265SDimitry Andric           MachineSDNode *Test =
609981ad6265SDimitry Andric               CurDAG->getMachineNode(TestOpcode, dl, MVT::i32, Shift, Shift);
61000b57cec5SDimitry Andric           ReplaceNode(Node, Test);
61010b57cec5SDimitry Andric           return;
61020b57cec5SDimitry Andric         }
61030b57cec5SDimitry Andric       }
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric       MVT VT;
61060b57cec5SDimitry Andric       int SubRegOp;
61070b57cec5SDimitry Andric       unsigned ROpc, MOpc;
61080b57cec5SDimitry Andric 
61090b57cec5SDimitry Andric       // For each of these checks we need to be careful if the sign flag is
61100b57cec5SDimitry Andric       // being used. It is only safe to use the sign flag in two conditions,
61110b57cec5SDimitry Andric       // either the sign bit in the shrunken mask is zero or the final test
61120b57cec5SDimitry Andric       // size is equal to the original compare size.
61130b57cec5SDimitry Andric 
61140b57cec5SDimitry Andric       if (isUInt<8>(Mask) &&
61150b57cec5SDimitry Andric           (!(Mask & 0x80) || CmpVT == MVT::i8 ||
61160b57cec5SDimitry Andric            hasNoSignFlagUses(SDValue(Node, 0)))) {
61170b57cec5SDimitry Andric         // For example, convert "testl %eax, $8" to "testb %al, $8"
61180b57cec5SDimitry Andric         VT = MVT::i8;
61190b57cec5SDimitry Andric         SubRegOp = X86::sub_8bit;
61200b57cec5SDimitry Andric         ROpc = X86::TEST8ri;
61210b57cec5SDimitry Andric         MOpc = X86::TEST8mi;
61220b57cec5SDimitry Andric       } else if (OptForMinSize && isUInt<16>(Mask) &&
61230b57cec5SDimitry Andric                  (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
61240b57cec5SDimitry Andric                   hasNoSignFlagUses(SDValue(Node, 0)))) {
61250b57cec5SDimitry Andric         // For example, "testl %eax, $32776" to "testw %ax, $32776".
61260b57cec5SDimitry Andric         // NOTE: We only want to form TESTW instructions if optimizing for
61270b57cec5SDimitry Andric         // min size. Otherwise we only save one byte and possibly get a length
61280b57cec5SDimitry Andric         // changing prefix penalty in the decoders.
61290b57cec5SDimitry Andric         VT = MVT::i16;
61300b57cec5SDimitry Andric         SubRegOp = X86::sub_16bit;
61310b57cec5SDimitry Andric         ROpc = X86::TEST16ri;
61320b57cec5SDimitry Andric         MOpc = X86::TEST16mi;
61330b57cec5SDimitry Andric       } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
61340b57cec5SDimitry Andric                  ((!(Mask & 0x80000000) &&
61350b57cec5SDimitry Andric                    // Without minsize 16-bit Cmps can get here so we need to
61360b57cec5SDimitry Andric                    // be sure we calculate the correct sign flag if needed.
61370b57cec5SDimitry Andric                    (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
61380b57cec5SDimitry Andric                   CmpVT == MVT::i32 ||
61390b57cec5SDimitry Andric                   hasNoSignFlagUses(SDValue(Node, 0)))) {
61400b57cec5SDimitry Andric         // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
61410b57cec5SDimitry Andric         // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
61420b57cec5SDimitry Andric         // Otherwize, we find ourselves in a position where we have to do
61430b57cec5SDimitry Andric         // promotion. If previous passes did not promote the and, we assume
61440b57cec5SDimitry Andric         // they had a good reason not to and do not promote here.
61450b57cec5SDimitry Andric         VT = MVT::i32;
61460b57cec5SDimitry Andric         SubRegOp = X86::sub_32bit;
61470b57cec5SDimitry Andric         ROpc = X86::TEST32ri;
61480b57cec5SDimitry Andric         MOpc = X86::TEST32mi;
61490b57cec5SDimitry Andric       } else {
61500b57cec5SDimitry Andric         // No eligible transformation was found.
61510b57cec5SDimitry Andric         break;
61520b57cec5SDimitry Andric       }
61530b57cec5SDimitry Andric 
61540b57cec5SDimitry Andric       SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
61550b57cec5SDimitry Andric       SDValue Reg = N0.getOperand(0);
61560b57cec5SDimitry Andric 
61570b57cec5SDimitry Andric       // Emit a testl or testw.
61580b57cec5SDimitry Andric       MachineSDNode *NewNode;
61590b57cec5SDimitry Andric       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
61600b57cec5SDimitry Andric       if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
6161480093f4SDimitry Andric         if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) {
6162480093f4SDimitry Andric           if (!LoadN->isSimple()) {
6163480093f4SDimitry Andric             unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits();
6164fe6060f1SDimitry Andric             if ((MOpc == X86::TEST8mi && NumVolBits != 8) ||
6165fe6060f1SDimitry Andric                 (MOpc == X86::TEST16mi && NumVolBits != 16) ||
6166fe6060f1SDimitry Andric                 (MOpc == X86::TEST32mi && NumVolBits != 32))
6167480093f4SDimitry Andric               break;
6168480093f4SDimitry Andric           }
6169480093f4SDimitry Andric         }
61700b57cec5SDimitry Andric         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
61710b57cec5SDimitry Andric                           Reg.getOperand(0) };
61720b57cec5SDimitry Andric         NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
61730b57cec5SDimitry Andric         // Update the chain.
61740b57cec5SDimitry Andric         ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
61750b57cec5SDimitry Andric         // Record the mem-refs
61760b57cec5SDimitry Andric         CurDAG->setNodeMemRefs(NewNode,
61770b57cec5SDimitry Andric                                {cast<LoadSDNode>(Reg)->getMemOperand()});
61780b57cec5SDimitry Andric       } else {
61790b57cec5SDimitry Andric         // Extract the subregister if necessary.
61800b57cec5SDimitry Andric         if (N0.getValueType() != VT)
61810b57cec5SDimitry Andric           Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
61820b57cec5SDimitry Andric 
61830b57cec5SDimitry Andric         NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
61840b57cec5SDimitry Andric       }
61850b57cec5SDimitry Andric       // Replace CMP with TEST.
61860b57cec5SDimitry Andric       ReplaceNode(Node, NewNode);
61870b57cec5SDimitry Andric       return;
61880b57cec5SDimitry Andric     }
61890b57cec5SDimitry Andric     break;
61900b57cec5SDimitry Andric   }
61910b57cec5SDimitry Andric   case X86ISD::PCMPISTR: {
61920b57cec5SDimitry Andric     if (!Subtarget->hasSSE42())
61930b57cec5SDimitry Andric       break;
61940b57cec5SDimitry Andric 
61950b57cec5SDimitry Andric     bool NeedIndex = !SDValue(Node, 0).use_empty();
61960b57cec5SDimitry Andric     bool NeedMask = !SDValue(Node, 1).use_empty();
61970b57cec5SDimitry Andric     // We can't fold a load if we are going to make two instructions.
61980b57cec5SDimitry Andric     bool MayFoldLoad = !NeedIndex || !NeedMask;
61990b57cec5SDimitry Andric 
62000b57cec5SDimitry Andric     MachineSDNode *CNode;
62010b57cec5SDimitry Andric     if (NeedMask) {
6202*0fca6ea1SDimitry Andric       unsigned ROpc =
6203*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPISTRMrri : X86::PCMPISTRMrri;
6204*0fca6ea1SDimitry Andric       unsigned MOpc =
6205*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPISTRMrmi : X86::PCMPISTRMrmi;
62060b57cec5SDimitry Andric       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
62070b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
62080b57cec5SDimitry Andric     }
62090b57cec5SDimitry Andric     if (NeedIndex || !NeedMask) {
6210*0fca6ea1SDimitry Andric       unsigned ROpc =
6211*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPISTRIrri : X86::PCMPISTRIrri;
6212*0fca6ea1SDimitry Andric       unsigned MOpc =
6213*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPISTRIrmi : X86::PCMPISTRIrmi;
62140b57cec5SDimitry Andric       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
62150b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
62160b57cec5SDimitry Andric     }
62170b57cec5SDimitry Andric 
62180b57cec5SDimitry Andric     // Connect the flag usage to the last instruction created.
62190b57cec5SDimitry Andric     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
62200b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(Node);
62210b57cec5SDimitry Andric     return;
62220b57cec5SDimitry Andric   }
62230b57cec5SDimitry Andric   case X86ISD::PCMPESTR: {
62240b57cec5SDimitry Andric     if (!Subtarget->hasSSE42())
62250b57cec5SDimitry Andric       break;
62260b57cec5SDimitry Andric 
62270b57cec5SDimitry Andric     // Copy the two implicit register inputs.
622806c3fb27SDimitry Andric     SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
62290b57cec5SDimitry Andric                                           Node->getOperand(1),
62300b57cec5SDimitry Andric                                           SDValue()).getValue(1);
623106c3fb27SDimitry Andric     InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
623206c3fb27SDimitry Andric                                   Node->getOperand(3), InGlue).getValue(1);
62330b57cec5SDimitry Andric 
62340b57cec5SDimitry Andric     bool NeedIndex = !SDValue(Node, 0).use_empty();
62350b57cec5SDimitry Andric     bool NeedMask = !SDValue(Node, 1).use_empty();
62360b57cec5SDimitry Andric     // We can't fold a load if we are going to make two instructions.
62370b57cec5SDimitry Andric     bool MayFoldLoad = !NeedIndex || !NeedMask;
62380b57cec5SDimitry Andric 
62390b57cec5SDimitry Andric     MachineSDNode *CNode;
62400b57cec5SDimitry Andric     if (NeedMask) {
6241*0fca6ea1SDimitry Andric       unsigned ROpc =
6242*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPESTRMrri : X86::PCMPESTRMrri;
6243*0fca6ea1SDimitry Andric       unsigned MOpc =
6244*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPESTRMrmi : X86::PCMPESTRMrmi;
6245*0fca6ea1SDimitry Andric       CNode =
6246*0fca6ea1SDimitry Andric           emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node, InGlue);
62470b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
62480b57cec5SDimitry Andric     }
62490b57cec5SDimitry Andric     if (NeedIndex || !NeedMask) {
6250*0fca6ea1SDimitry Andric       unsigned ROpc =
6251*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPESTRIrri : X86::PCMPESTRIrri;
6252*0fca6ea1SDimitry Andric       unsigned MOpc =
6253*0fca6ea1SDimitry Andric           Subtarget->hasAVX() ? X86::VPCMPESTRIrmi : X86::PCMPESTRIrmi;
625406c3fb27SDimitry Andric       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InGlue);
62550b57cec5SDimitry Andric       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
62560b57cec5SDimitry Andric     }
62570b57cec5SDimitry Andric     // Connect the flag usage to the last instruction created.
62580b57cec5SDimitry Andric     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
62590b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(Node);
62600b57cec5SDimitry Andric     return;
62610b57cec5SDimitry Andric   }
62620b57cec5SDimitry Andric 
62630b57cec5SDimitry Andric   case ISD::SETCC: {
62640b57cec5SDimitry Andric     if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue()))
62650b57cec5SDimitry Andric       return;
62660b57cec5SDimitry Andric 
62670b57cec5SDimitry Andric     break;
62680b57cec5SDimitry Andric   }
62690b57cec5SDimitry Andric 
62700b57cec5SDimitry Andric   case ISD::STORE:
62710b57cec5SDimitry Andric     if (foldLoadStoreIntoMemOperand(Node))
62720b57cec5SDimitry Andric       return;
62730b57cec5SDimitry Andric     break;
62745ffd83dbSDimitry Andric 
62755ffd83dbSDimitry Andric   case X86ISD::SETCC_CARRY: {
627681ad6265SDimitry Andric     MVT VT = Node->getSimpleValueType(0);
627781ad6265SDimitry Andric     SDValue Result;
627881ad6265SDimitry Andric     if (Subtarget->hasSBBDepBreaking()) {
62795ffd83dbSDimitry Andric       // We have to do this manually because tblgen will put the eflags copy in
62805ffd83dbSDimitry Andric       // the wrong place if we use an extract_subreg in the pattern.
62815ffd83dbSDimitry Andric       // Copy flags to the EFLAGS register and glue it to next node.
62825ffd83dbSDimitry Andric       SDValue EFLAGS =
62835ffd83dbSDimitry Andric           CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
62845ffd83dbSDimitry Andric                                Node->getOperand(1), SDValue());
62855ffd83dbSDimitry Andric 
62865ffd83dbSDimitry Andric       // Create a 64-bit instruction if the result is 64-bits otherwise use the
62875ffd83dbSDimitry Andric       // 32-bit version.
62885ffd83dbSDimitry Andric       unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r;
62895ffd83dbSDimitry Andric       MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
629081ad6265SDimitry Andric       Result = SDValue(
629181ad6265SDimitry Andric           CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)),
629281ad6265SDimitry Andric           0);
629381ad6265SDimitry Andric     } else {
629481ad6265SDimitry Andric       // The target does not recognize sbb with the same reg operand as a
629581ad6265SDimitry Andric       // no-source idiom, so we explicitly zero the input values.
629681ad6265SDimitry Andric       Result = getSBBZero(Node);
629781ad6265SDimitry Andric     }
62985ffd83dbSDimitry Andric 
62995ffd83dbSDimitry Andric     // For less than 32-bits we need to extract from the 32-bit node.
63005ffd83dbSDimitry Andric     if (VT == MVT::i8 || VT == MVT::i16) {
63015ffd83dbSDimitry Andric       int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
63025ffd83dbSDimitry Andric       Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
63035ffd83dbSDimitry Andric     }
63045ffd83dbSDimitry Andric 
63055ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 0), Result);
63065ffd83dbSDimitry Andric     CurDAG->RemoveDeadNode(Node);
63075ffd83dbSDimitry Andric     return;
63085ffd83dbSDimitry Andric   }
63095ffd83dbSDimitry Andric   case X86ISD::SBB: {
63105ffd83dbSDimitry Andric     if (isNullConstant(Node->getOperand(0)) &&
63115ffd83dbSDimitry Andric         isNullConstant(Node->getOperand(1))) {
631281ad6265SDimitry Andric       SDValue Result = getSBBZero(Node);
63135ffd83dbSDimitry Andric 
63145ffd83dbSDimitry Andric       // Replace the flag use.
63155ffd83dbSDimitry Andric       ReplaceUses(SDValue(Node, 1), Result.getValue(1));
63165ffd83dbSDimitry Andric 
63175ffd83dbSDimitry Andric       // Replace the result use.
63185ffd83dbSDimitry Andric       if (!SDValue(Node, 0).use_empty()) {
63195ffd83dbSDimitry Andric         // For less than 32-bits we need to extract from the 32-bit node.
632081ad6265SDimitry Andric         MVT VT = Node->getSimpleValueType(0);
63215ffd83dbSDimitry Andric         if (VT == MVT::i8 || VT == MVT::i16) {
63225ffd83dbSDimitry Andric           int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
63235ffd83dbSDimitry Andric           Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
63245ffd83dbSDimitry Andric         }
63255ffd83dbSDimitry Andric         ReplaceUses(SDValue(Node, 0), Result);
63265ffd83dbSDimitry Andric       }
63275ffd83dbSDimitry Andric 
63285ffd83dbSDimitry Andric       CurDAG->RemoveDeadNode(Node);
63295ffd83dbSDimitry Andric       return;
63305ffd83dbSDimitry Andric     }
63315ffd83dbSDimitry Andric     break;
63325ffd83dbSDimitry Andric   }
63335ffd83dbSDimitry Andric   case X86ISD::MGATHER: {
63345ffd83dbSDimitry Andric     auto *Mgt = cast<X86MaskedGatherSDNode>(Node);
63355ffd83dbSDimitry Andric     SDValue IndexOp = Mgt->getIndex();
63365ffd83dbSDimitry Andric     SDValue Mask = Mgt->getMask();
63375ffd83dbSDimitry Andric     MVT IndexVT = IndexOp.getSimpleValueType();
63385ffd83dbSDimitry Andric     MVT ValueVT = Node->getSimpleValueType(0);
63395ffd83dbSDimitry Andric     MVT MaskVT = Mask.getSimpleValueType();
63405ffd83dbSDimitry Andric 
63415ffd83dbSDimitry Andric     // This is just to prevent crashes if the nodes are malformed somehow. We're
63425ffd83dbSDimitry Andric     // otherwise only doing loose type checking in here based on type what
63435ffd83dbSDimitry Andric     // a type constraint would say just like table based isel.
63445ffd83dbSDimitry Andric     if (!ValueVT.isVector() || !MaskVT.isVector())
63455ffd83dbSDimitry Andric       break;
63465ffd83dbSDimitry Andric 
63475ffd83dbSDimitry Andric     unsigned NumElts = ValueVT.getVectorNumElements();
63485ffd83dbSDimitry Andric     MVT ValueSVT = ValueVT.getVectorElementType();
63495ffd83dbSDimitry Andric 
63505ffd83dbSDimitry Andric     bool IsFP = ValueSVT.isFloatingPoint();
63515ffd83dbSDimitry Andric     unsigned EltSize = ValueSVT.getSizeInBits();
63525ffd83dbSDimitry Andric 
63535ffd83dbSDimitry Andric     unsigned Opc = 0;
63545ffd83dbSDimitry Andric     bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1;
63555ffd83dbSDimitry Andric     if (AVX512Gather) {
63565ffd83dbSDimitry Andric       if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
63575ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm;
63585ffd83dbSDimitry Andric       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
63595ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm;
63605ffd83dbSDimitry Andric       else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
63615ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm;
63625ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
63635ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm;
63645ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
63655ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm;
63665ffd83dbSDimitry Andric       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
63675ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm;
63685ffd83dbSDimitry Andric       else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
63695ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm;
63705ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
63715ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm;
63725ffd83dbSDimitry Andric       else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
63735ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm;
63745ffd83dbSDimitry Andric       else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
63755ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm;
63765ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
63775ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm;
63785ffd83dbSDimitry Andric       else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
63795ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm;
63805ffd83dbSDimitry Andric     } else {
63815ffd83dbSDimitry Andric       assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() &&
63825ffd83dbSDimitry Andric              "Unexpected mask VT!");
63835ffd83dbSDimitry Andric       if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
63845ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm;
63855ffd83dbSDimitry Andric       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
63865ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm;
63875ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
63885ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm;
63895ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
63905ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm;
63915ffd83dbSDimitry Andric       else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
63925ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm;
63935ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
63945ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm;
63955ffd83dbSDimitry Andric       else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
63965ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm;
63975ffd83dbSDimitry Andric       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
63985ffd83dbSDimitry Andric         Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm;
63995ffd83dbSDimitry Andric     }
64005ffd83dbSDimitry Andric 
64015ffd83dbSDimitry Andric     if (!Opc)
64025ffd83dbSDimitry Andric       break;
64035ffd83dbSDimitry Andric 
64045ffd83dbSDimitry Andric     SDValue Base, Scale, Index, Disp, Segment;
64055ffd83dbSDimitry Andric     if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(),
64065ffd83dbSDimitry Andric                           Base, Scale, Index, Disp, Segment))
64075ffd83dbSDimitry Andric       break;
64085ffd83dbSDimitry Andric 
64095ffd83dbSDimitry Andric     SDValue PassThru = Mgt->getPassThru();
64105ffd83dbSDimitry Andric     SDValue Chain = Mgt->getChain();
64115ffd83dbSDimitry Andric     // Gather instructions have a mask output not in the ISD node.
64125ffd83dbSDimitry Andric     SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other);
64135ffd83dbSDimitry Andric 
64145ffd83dbSDimitry Andric     MachineSDNode *NewNode;
64155ffd83dbSDimitry Andric     if (AVX512Gather) {
64165ffd83dbSDimitry Andric       SDValue Ops[] = {PassThru, Mask, Base,    Scale,
64175ffd83dbSDimitry Andric                        Index,    Disp, Segment, Chain};
64185ffd83dbSDimitry Andric       NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
64195ffd83dbSDimitry Andric     } else {
64205ffd83dbSDimitry Andric       SDValue Ops[] = {PassThru, Base,    Scale, Index,
64215ffd83dbSDimitry Andric                        Disp,     Segment, Mask,  Chain};
64225ffd83dbSDimitry Andric       NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
64235ffd83dbSDimitry Andric     }
64245ffd83dbSDimitry Andric     CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()});
64255ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
64265ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2));
64275ffd83dbSDimitry Andric     CurDAG->RemoveDeadNode(Node);
64285ffd83dbSDimitry Andric     return;
64295ffd83dbSDimitry Andric   }
64305ffd83dbSDimitry Andric   case X86ISD::MSCATTER: {
64315ffd83dbSDimitry Andric     auto *Sc = cast<X86MaskedScatterSDNode>(Node);
64325ffd83dbSDimitry Andric     SDValue Value = Sc->getValue();
64335ffd83dbSDimitry Andric     SDValue IndexOp = Sc->getIndex();
64345ffd83dbSDimitry Andric     MVT IndexVT = IndexOp.getSimpleValueType();
64355ffd83dbSDimitry Andric     MVT ValueVT = Value.getSimpleValueType();
64365ffd83dbSDimitry Andric 
64375ffd83dbSDimitry Andric     // This is just to prevent crashes if the nodes are malformed somehow. We're
64385ffd83dbSDimitry Andric     // otherwise only doing loose type checking in here based on type what
64395ffd83dbSDimitry Andric     // a type constraint would say just like table based isel.
64405ffd83dbSDimitry Andric     if (!ValueVT.isVector())
64415ffd83dbSDimitry Andric       break;
64425ffd83dbSDimitry Andric 
64435ffd83dbSDimitry Andric     unsigned NumElts = ValueVT.getVectorNumElements();
64445ffd83dbSDimitry Andric     MVT ValueSVT = ValueVT.getVectorElementType();
64455ffd83dbSDimitry Andric 
64465ffd83dbSDimitry Andric     bool IsFP = ValueSVT.isFloatingPoint();
64475ffd83dbSDimitry Andric     unsigned EltSize = ValueSVT.getSizeInBits();
64485ffd83dbSDimitry Andric 
64495ffd83dbSDimitry Andric     unsigned Opc;
64505ffd83dbSDimitry Andric     if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
64515ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr;
64525ffd83dbSDimitry Andric     else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
64535ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr;
64545ffd83dbSDimitry Andric     else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
64555ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr;
64565ffd83dbSDimitry Andric     else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
64575ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr;
64585ffd83dbSDimitry Andric     else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
64595ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr;
64605ffd83dbSDimitry Andric     else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
64615ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr;
64625ffd83dbSDimitry Andric     else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
64635ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr;
64645ffd83dbSDimitry Andric     else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
64655ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr;
64665ffd83dbSDimitry Andric     else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
64675ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr;
64685ffd83dbSDimitry Andric     else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
64695ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr;
64705ffd83dbSDimitry Andric     else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
64715ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr;
64725ffd83dbSDimitry Andric     else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
64735ffd83dbSDimitry Andric       Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr;
64745ffd83dbSDimitry Andric     else
64755ffd83dbSDimitry Andric       break;
64765ffd83dbSDimitry Andric 
64775ffd83dbSDimitry Andric     SDValue Base, Scale, Index, Disp, Segment;
64785ffd83dbSDimitry Andric     if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(),
64795ffd83dbSDimitry Andric                           Base, Scale, Index, Disp, Segment))
64805ffd83dbSDimitry Andric       break;
64815ffd83dbSDimitry Andric 
64825ffd83dbSDimitry Andric     SDValue Mask = Sc->getMask();
64835ffd83dbSDimitry Andric     SDValue Chain = Sc->getChain();
64845ffd83dbSDimitry Andric     // Scatter instructions have a mask output not in the ISD node.
64855ffd83dbSDimitry Andric     SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other);
64865ffd83dbSDimitry Andric     SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain};
64875ffd83dbSDimitry Andric 
64885ffd83dbSDimitry Andric     MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
64895ffd83dbSDimitry Andric     CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()});
64905ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1));
64915ffd83dbSDimitry Andric     CurDAG->RemoveDeadNode(Node);
64925ffd83dbSDimitry Andric     return;
64935ffd83dbSDimitry Andric   }
64945ffd83dbSDimitry Andric   case ISD::PREALLOCATED_SETUP: {
64955ffd83dbSDimitry Andric     auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
64965ffd83dbSDimitry Andric     auto CallId = MFI->getPreallocatedIdForCallSite(
64975ffd83dbSDimitry Andric         cast<SrcValueSDNode>(Node->getOperand(1))->getValue());
64985ffd83dbSDimitry Andric     SDValue Chain = Node->getOperand(0);
64995ffd83dbSDimitry Andric     SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);
65005ffd83dbSDimitry Andric     MachineSDNode *New = CurDAG->getMachineNode(
65015ffd83dbSDimitry Andric         TargetOpcode::PREALLOCATED_SETUP, dl, MVT::Other, CallIdValue, Chain);
65025ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Chain
65035ffd83dbSDimitry Andric     CurDAG->RemoveDeadNode(Node);
65045ffd83dbSDimitry Andric     return;
65055ffd83dbSDimitry Andric   }
65065ffd83dbSDimitry Andric   case ISD::PREALLOCATED_ARG: {
65075ffd83dbSDimitry Andric     auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
65085ffd83dbSDimitry Andric     auto CallId = MFI->getPreallocatedIdForCallSite(
65095ffd83dbSDimitry Andric         cast<SrcValueSDNode>(Node->getOperand(1))->getValue());
65105ffd83dbSDimitry Andric     SDValue Chain = Node->getOperand(0);
65115ffd83dbSDimitry Andric     SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);
65125ffd83dbSDimitry Andric     SDValue ArgIndex = Node->getOperand(2);
65135ffd83dbSDimitry Andric     SDValue Ops[3];
65145ffd83dbSDimitry Andric     Ops[0] = CallIdValue;
65155ffd83dbSDimitry Andric     Ops[1] = ArgIndex;
65165ffd83dbSDimitry Andric     Ops[2] = Chain;
65175ffd83dbSDimitry Andric     MachineSDNode *New = CurDAG->getMachineNode(
65185ffd83dbSDimitry Andric         TargetOpcode::PREALLOCATED_ARG, dl,
65195ffd83dbSDimitry Andric         CurDAG->getVTList(TLI->getPointerTy(CurDAG->getDataLayout()),
65205ffd83dbSDimitry Andric                           MVT::Other),
65215ffd83dbSDimitry Andric         Ops);
65225ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Arg pointer
65235ffd83dbSDimitry Andric     ReplaceUses(SDValue(Node, 1), SDValue(New, 1)); // Chain
65245ffd83dbSDimitry Andric     CurDAG->RemoveDeadNode(Node);
65255ffd83dbSDimitry Andric     return;
65265ffd83dbSDimitry Andric   }
6527e8d8bef9SDimitry Andric   case X86ISD::AESENCWIDE128KL:
6528e8d8bef9SDimitry Andric   case X86ISD::AESDECWIDE128KL:
6529e8d8bef9SDimitry Andric   case X86ISD::AESENCWIDE256KL:
6530e8d8bef9SDimitry Andric   case X86ISD::AESDECWIDE256KL: {
6531e8d8bef9SDimitry Andric     if (!Subtarget->hasWIDEKL())
6532e8d8bef9SDimitry Andric       break;
6533e8d8bef9SDimitry Andric 
6534e8d8bef9SDimitry Andric     unsigned Opcode;
6535e8d8bef9SDimitry Andric     switch (Node->getOpcode()) {
6536e8d8bef9SDimitry Andric     default:
6537e8d8bef9SDimitry Andric       llvm_unreachable("Unexpected opcode!");
6538e8d8bef9SDimitry Andric     case X86ISD::AESENCWIDE128KL:
6539e8d8bef9SDimitry Andric       Opcode = X86::AESENCWIDE128KL;
6540e8d8bef9SDimitry Andric       break;
6541e8d8bef9SDimitry Andric     case X86ISD::AESDECWIDE128KL:
6542e8d8bef9SDimitry Andric       Opcode = X86::AESDECWIDE128KL;
6543e8d8bef9SDimitry Andric       break;
6544e8d8bef9SDimitry Andric     case X86ISD::AESENCWIDE256KL:
6545e8d8bef9SDimitry Andric       Opcode = X86::AESENCWIDE256KL;
6546e8d8bef9SDimitry Andric       break;
6547e8d8bef9SDimitry Andric     case X86ISD::AESDECWIDE256KL:
6548e8d8bef9SDimitry Andric       Opcode = X86::AESDECWIDE256KL;
6549e8d8bef9SDimitry Andric       break;
6550e8d8bef9SDimitry Andric     }
6551e8d8bef9SDimitry Andric 
6552e8d8bef9SDimitry Andric     SDValue Chain = Node->getOperand(0);
6553e8d8bef9SDimitry Andric     SDValue Addr = Node->getOperand(1);
6554e8d8bef9SDimitry Andric 
6555e8d8bef9SDimitry Andric     SDValue Base, Scale, Index, Disp, Segment;
6556e8d8bef9SDimitry Andric     if (!selectAddr(Node, Addr, Base, Scale, Index, Disp, Segment))
6557e8d8bef9SDimitry Andric       break;
6558e8d8bef9SDimitry Andric 
6559e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(2),
6560e8d8bef9SDimitry Andric                                  SDValue());
6561e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(3),
6562e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6563e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM2, Node->getOperand(4),
6564e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6565e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM3, Node->getOperand(5),
6566e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6567e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM4, Node->getOperand(6),
6568e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6569e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM5, Node->getOperand(7),
6570e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6571e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM6, Node->getOperand(8),
6572e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6573e8d8bef9SDimitry Andric     Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM7, Node->getOperand(9),
6574e8d8bef9SDimitry Andric                                  Chain.getValue(1));
6575e8d8bef9SDimitry Andric 
6576e8d8bef9SDimitry Andric     MachineSDNode *Res = CurDAG->getMachineNode(
6577e8d8bef9SDimitry Andric         Opcode, dl, Node->getVTList(),
6578e8d8bef9SDimitry Andric         {Base, Scale, Index, Disp, Segment, Chain, Chain.getValue(1)});
6579e8d8bef9SDimitry Andric     CurDAG->setNodeMemRefs(Res, cast<MemSDNode>(Node)->getMemOperand());
6580e8d8bef9SDimitry Andric     ReplaceNode(Node, Res);
6581e8d8bef9SDimitry Andric     return;
6582e8d8bef9SDimitry Andric   }
65830b57cec5SDimitry Andric   }
65840b57cec5SDimitry Andric 
65850b57cec5SDimitry Andric   SelectCode(Node);
65860b57cec5SDimitry Andric }
65870b57cec5SDimitry Andric 
SelectInlineAsmMemoryOperand(const SDValue & Op,InlineAsm::ConstraintCode ConstraintID,std::vector<SDValue> & OutOps)65885f757f3fSDimitry Andric bool X86DAGToDAGISel::SelectInlineAsmMemoryOperand(
65895f757f3fSDimitry Andric     const SDValue &Op, InlineAsm::ConstraintCode ConstraintID,
65900b57cec5SDimitry Andric     std::vector<SDValue> &OutOps) {
65910b57cec5SDimitry Andric   SDValue Op0, Op1, Op2, Op3, Op4;
65920b57cec5SDimitry Andric   switch (ConstraintID) {
65930b57cec5SDimitry Andric   default:
65940b57cec5SDimitry Andric     llvm_unreachable("Unexpected asm memory constraint");
65955f757f3fSDimitry Andric   case InlineAsm::ConstraintCode::o: // offsetable        ??
65965f757f3fSDimitry Andric   case InlineAsm::ConstraintCode::v: // not offsetable    ??
65975f757f3fSDimitry Andric   case InlineAsm::ConstraintCode::m: // memory
65985f757f3fSDimitry Andric   case InlineAsm::ConstraintCode::X:
65995f757f3fSDimitry Andric   case InlineAsm::ConstraintCode::p: // address
66000b57cec5SDimitry Andric     if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
66010b57cec5SDimitry Andric       return true;
66020b57cec5SDimitry Andric     break;
66030b57cec5SDimitry Andric   }
66040b57cec5SDimitry Andric 
66050b57cec5SDimitry Andric   OutOps.push_back(Op0);
66060b57cec5SDimitry Andric   OutOps.push_back(Op1);
66070b57cec5SDimitry Andric   OutOps.push_back(Op2);
66080b57cec5SDimitry Andric   OutOps.push_back(Op3);
66090b57cec5SDimitry Andric   OutOps.push_back(Op4);
66100b57cec5SDimitry Andric   return false;
66110b57cec5SDimitry Andric }
66120b57cec5SDimitry Andric 
X86ISelDAGToDAGPass(X86TargetMachine & TM)6613*0fca6ea1SDimitry Andric X86ISelDAGToDAGPass::X86ISelDAGToDAGPass(X86TargetMachine &TM)
6614*0fca6ea1SDimitry Andric     : SelectionDAGISelPass(
6615*0fca6ea1SDimitry Andric           std::make_unique<X86DAGToDAGISel>(TM, TM.getOptLevel())) {}
6616*0fca6ea1SDimitry Andric 
66170b57cec5SDimitry Andric /// This pass converts a legalized DAG into a X86-specific DAG,
66180b57cec5SDimitry Andric /// ready for instruction scheduling.
createX86ISelDag(X86TargetMachine & TM,CodeGenOptLevel OptLevel)66190b57cec5SDimitry Andric FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
66205f757f3fSDimitry Andric                                      CodeGenOptLevel OptLevel) {
6621*0fca6ea1SDimitry Andric   return new X86DAGToDAGISelLegacy(TM, OptLevel);
66220b57cec5SDimitry Andric }
6623