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