LLVM  5.0.0
X86ISelDAGToDAG.cpp
Go to the documentation of this file.
1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/KnownBits.h"
39 #include <stdint.h>
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "x86-isel"
43 
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45 
46 //===----------------------------------------------------------------------===//
47 // Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
49 
50 namespace {
51  /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52  /// numbers for the leaves of the matched tree.
53  struct X86ISelAddressMode {
54  enum {
55  RegBase,
56  FrameIndexBase
57  } BaseType;
58 
59  // This is really a union, discriminated by BaseType!
60  SDValue Base_Reg;
61  int Base_FrameIndex;
62 
63  unsigned Scale;
64  SDValue IndexReg;
65  int32_t Disp;
66  SDValue Segment;
67  const GlobalValue *GV;
68  const Constant *CP;
69  const BlockAddress *BlockAddr;
70  const char *ES;
71  MCSymbol *MCSym;
72  int JT;
73  unsigned Align; // CP alignment.
74  unsigned char SymbolFlags; // X86II::MO_*
75 
76  X86ISelAddressMode()
77  : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
78  Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
79  MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
80 
81  bool hasSymbolicDisplacement() const {
82  return GV != nullptr || CP != nullptr || ES != nullptr ||
83  MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
84  }
85 
86  bool hasBaseOrIndexReg() const {
87  return BaseType == FrameIndexBase ||
88  IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
89  }
90 
91  /// Return true if this addressing mode is already RIP-relative.
92  bool isRIPRelative() const {
93  if (BaseType != RegBase) return false;
94  if (RegisterSDNode *RegNode =
95  dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
96  return RegNode->getReg() == X86::RIP;
97  return false;
98  }
99 
100  void setBaseReg(SDValue Reg) {
101  BaseType = RegBase;
102  Base_Reg = Reg;
103  }
104 
105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
106  void dump() {
107  dbgs() << "X86ISelAddressMode " << this << '\n';
108  dbgs() << "Base_Reg ";
109  if (Base_Reg.getNode())
110  Base_Reg.getNode()->dump();
111  else
112  dbgs() << "nul";
113  dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
114  << " Scale" << Scale << '\n'
115  << "IndexReg ";
116  if (IndexReg.getNode())
117  IndexReg.getNode()->dump();
118  else
119  dbgs() << "nul";
120  dbgs() << " Disp " << Disp << '\n'
121  << "GV ";
122  if (GV)
123  GV->dump();
124  else
125  dbgs() << "nul";
126  dbgs() << " CP ";
127  if (CP)
128  CP->dump();
129  else
130  dbgs() << "nul";
131  dbgs() << '\n'
132  << "ES ";
133  if (ES)
134  dbgs() << ES;
135  else
136  dbgs() << "nul";
137  dbgs() << " MCSym ";
138  if (MCSym)
139  dbgs() << MCSym;
140  else
141  dbgs() << "nul";
142  dbgs() << " JT" << JT << " Align" << Align << '\n';
143  }
144 #endif
145  };
146 }
147 
148 namespace {
149  //===--------------------------------------------------------------------===//
150  /// ISel - X86-specific code to select X86 machine instructions for
151  /// SelectionDAG operations.
152  ///
153  class X86DAGToDAGISel final : public SelectionDAGISel {
154  /// Keep a pointer to the X86Subtarget around so that we can
155  /// make the right decision when generating code for different targets.
156  const X86Subtarget *Subtarget;
157 
158  /// If true, selector should try to optimize for code size instead of
159  /// performance.
160  bool OptForSize;
161 
162  /// If true, selector should try to optimize for minimum code size.
163  bool OptForMinSize;
164 
165  public:
166  explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
167  : SelectionDAGISel(tm, OptLevel), OptForSize(false),
168  OptForMinSize(false) {}
169 
170  StringRef getPassName() const override {
171  return "X86 DAG->DAG Instruction Selection";
172  }
173 
174  bool runOnMachineFunction(MachineFunction &MF) override {
175  // Reset the subtarget each time through.
176  Subtarget = &MF.getSubtarget<X86Subtarget>();
178  return true;
179  }
180 
181  void EmitFunctionEntryCode() override;
182 
183  bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
184 
185  void PreprocessISelDAG() override;
186 
187 // Include the pieces autogenerated from the target description.
188 #include "X86GenDAGISel.inc"
189 
190  private:
191  void Select(SDNode *N) override;
192 
193  bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
194  bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
195  bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
196  bool matchAddress(SDValue N, X86ISelAddressMode &AM);
197  bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
198  bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
199  unsigned Depth);
200  bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201  bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
202  SDValue &Scale, SDValue &Index, SDValue &Disp,
203  SDValue &Segment);
204  bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
205  SDValue &Scale, SDValue &Index, SDValue &Disp,
206  SDValue &Segment);
207  template <class GatherScatterSDNode>
208  bool selectAddrOfGatherScatterNode(GatherScatterSDNode *Parent, SDValue N,
209  SDValue &Base, SDValue &Scale,
210  SDValue &Index, SDValue &Disp,
211  SDValue &Segment);
212  bool selectMOV64Imm32(SDValue N, SDValue &Imm);
213  bool selectLEAAddr(SDValue N, SDValue &Base,
214  SDValue &Scale, SDValue &Index, SDValue &Disp,
215  SDValue &Segment);
216  bool selectLEA64_32Addr(SDValue N, SDValue &Base,
217  SDValue &Scale, SDValue &Index, SDValue &Disp,
218  SDValue &Segment);
219  bool selectTLSADDRAddr(SDValue N, SDValue &Base,
220  SDValue &Scale, SDValue &Index, SDValue &Disp,
221  SDValue &Segment);
222  bool selectScalarSSELoad(SDNode *Root, SDValue N,
223  SDValue &Base, SDValue &Scale,
224  SDValue &Index, SDValue &Disp,
225  SDValue &Segment,
226  SDValue &NodeWithChain);
227  bool selectRelocImm(SDValue N, SDValue &Op);
228 
229  bool tryFoldLoad(SDNode *P, SDValue N,
230  SDValue &Base, SDValue &Scale,
231  SDValue &Index, SDValue &Disp,
232  SDValue &Segment);
233 
234  /// Implement addressing mode selection for inline asm expressions.
235  bool SelectInlineAsmMemoryOperand(const SDValue &Op,
236  unsigned ConstraintID,
237  std::vector<SDValue> &OutOps) override;
238 
239  void emitSpecialCodeForMain();
240 
241  inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
242  SDValue &Base, SDValue &Scale,
243  SDValue &Index, SDValue &Disp,
244  SDValue &Segment) {
245  Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
246  ? CurDAG->getTargetFrameIndex(
247  AM.Base_FrameIndex,
248  TLI->getPointerTy(CurDAG->getDataLayout()))
249  : AM.Base_Reg;
250  Scale = getI8Imm(AM.Scale, DL);
251  Index = AM.IndexReg;
252  // These are 32-bit even in 64-bit mode since RIP-relative offset
253  // is 32-bit.
254  if (AM.GV)
255  Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
256  MVT::i32, AM.Disp,
257  AM.SymbolFlags);
258  else if (AM.CP)
259  Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
260  AM.Align, AM.Disp, AM.SymbolFlags);
261  else if (AM.ES) {
262  assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
263  Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
264  } else if (AM.MCSym) {
265  assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
266  assert(AM.SymbolFlags == 0 && "oo");
267  Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
268  } else if (AM.JT != -1) {
269  assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
270  Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
271  } else if (AM.BlockAddr)
272  Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
273  AM.SymbolFlags);
274  else
275  Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
276 
277  if (AM.Segment.getNode())
278  Segment = AM.Segment;
279  else
280  Segment = CurDAG->getRegister(0, MVT::i32);
281  }
282 
283  // Utility function to determine whether we should avoid selecting
284  // immediate forms of instructions for better code size or not.
285  // At a high level, we'd like to avoid such instructions when
286  // we have similar constants used within the same basic block
287  // that can be kept in a register.
288  //
289  bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
290  uint32_t UseCount = 0;
291 
292  // Do not want to hoist if we're not optimizing for size.
293  // TODO: We'd like to remove this restriction.
294  // See the comment in X86InstrInfo.td for more info.
295  if (!OptForSize)
296  return false;
297 
298  // Walk all the users of the immediate.
299  for (SDNode::use_iterator UI = N->use_begin(),
300  UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
301 
302  SDNode *User = *UI;
303 
304  // This user is already selected. Count it as a legitimate use and
305  // move on.
306  if (User->isMachineOpcode()) {
307  UseCount++;
308  continue;
309  }
310 
311  // We want to count stores of immediates as real uses.
312  if (User->getOpcode() == ISD::STORE &&
313  User->getOperand(1).getNode() == N) {
314  UseCount++;
315  continue;
316  }
317 
318  // We don't currently match users that have > 2 operands (except
319  // for stores, which are handled above)
320  // Those instruction won't match in ISEL, for now, and would
321  // be counted incorrectly.
322  // This may change in the future as we add additional instruction
323  // types.
324  if (User->getNumOperands() != 2)
325  continue;
326 
327  // Immediates that are used for offsets as part of stack
328  // manipulation should be left alone. These are typically
329  // used to indicate SP offsets for argument passing and
330  // will get pulled into stores/pushes (implicitly).
331  if (User->getOpcode() == X86ISD::ADD ||
332  User->getOpcode() == ISD::ADD ||
333  User->getOpcode() == X86ISD::SUB ||
334  User->getOpcode() == ISD::SUB) {
335 
336  // Find the other operand of the add/sub.
337  SDValue OtherOp = User->getOperand(0);
338  if (OtherOp.getNode() == N)
339  OtherOp = User->getOperand(1);
340 
341  // Don't count if the other operand is SP.
342  RegisterSDNode *RegNode;
343  if (OtherOp->getOpcode() == ISD::CopyFromReg &&
344  (RegNode = dyn_cast_or_null<RegisterSDNode>(
345  OtherOp->getOperand(1).getNode())))
346  if ((RegNode->getReg() == X86::ESP) ||
347  (RegNode->getReg() == X86::RSP))
348  continue;
349  }
350 
351  // ... otherwise, count this and move on.
352  UseCount++;
353  }
354 
355  // If we have more than 1 use, then recommend for hoisting.
356  return (UseCount > 1);
357  }
358 
359  /// Return a target constant with the specified value of type i8.
360  inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
361  return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
362  }
363 
364  /// Return a target constant with the specified value, of type i32.
365  inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
366  return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
367  }
368 
369  /// Return an SDNode that returns the value of the global base register.
370  /// Output instructions required to initialize the global base register,
371  /// if necessary.
372  SDNode *getGlobalBaseReg();
373 
374  /// Return a reference to the TargetMachine, casted to the target-specific
375  /// type.
376  const X86TargetMachine &getTargetMachine() const {
377  return static_cast<const X86TargetMachine &>(TM);
378  }
379 
380  /// Return a reference to the TargetInstrInfo, casted to the target-specific
381  /// type.
382  const X86InstrInfo *getInstrInfo() const {
383  return Subtarget->getInstrInfo();
384  }
385 
386  /// \brief Address-mode matching performs shift-of-and to and-of-shift
387  /// reassociation in order to expose more scaled addressing
388  /// opportunities.
389  bool ComplexPatternFuncMutatesDAG() const override {
390  return true;
391  }
392 
393  bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
394 
395  /// Returns whether this is a relocatable immediate in the range
396  /// [-2^Width .. 2^Width-1].
397  template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
398  if (auto *CN = dyn_cast<ConstantSDNode>(N))
399  return isInt<Width>(CN->getSExtValue());
400  return isSExtAbsoluteSymbolRef(Width, N);
401  }
402  };
403 }
404 
405 
406 bool
407 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
408  if (OptLevel == CodeGenOpt::None) return false;
409 
410  if (!N.hasOneUse())
411  return false;
412 
413  if (N.getOpcode() != ISD::LOAD)
414  return true;
415 
416  // If N is a load, do additional profitability checks.
417  if (U == Root) {
418  switch (U->getOpcode()) {
419  default: break;
420  case X86ISD::ADD:
421  case X86ISD::SUB:
422  case X86ISD::AND:
423  case X86ISD::XOR:
424  case X86ISD::OR:
425  case ISD::ADD:
426  case ISD::ADDCARRY:
427  case ISD::AND:
428  case ISD::OR:
429  case ISD::XOR: {
430  SDValue Op1 = U->getOperand(1);
431 
432  // If the other operand is a 8-bit immediate we should fold the immediate
433  // instead. This reduces code size.
434  // e.g.
435  // movl 4(%esp), %eax
436  // addl $4, %eax
437  // vs.
438  // movl $4, %eax
439  // addl 4(%esp), %eax
440  // The former is 2 bytes shorter. In case where the increment is 1, then
441  // the saving can be 4 bytes (by using incl %eax).
442  if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
443  if (Imm->getAPIntValue().isSignedIntN(8))
444  return false;
445 
446  // If the other operand is a TLS address, we should fold it instead.
447  // This produces
448  // movl %gs:0, %eax
449  // leal i@NTPOFF(%eax), %eax
450  // instead of
451  // movl $i@NTPOFF, %eax
452  // addl %gs:0, %eax
453  // if the block also has an access to a second TLS address this will save
454  // a load.
455  // FIXME: This is probably also true for non-TLS addresses.
456  if (Op1.getOpcode() == X86ISD::Wrapper) {
457  SDValue Val = Op1.getOperand(0);
459  return false;
460  }
461  }
462  }
463  }
464 
465  return true;
466 }
467 
468 /// Replace the original chain operand of the call with
469 /// load's chain operand and move load below the call's chain operand.
471  SDValue Call, SDValue OrigChain) {
473  SDValue Chain = OrigChain.getOperand(0);
474  if (Chain.getNode() == Load.getNode())
475  Ops.push_back(Load.getOperand(0));
476  else {
477  assert(Chain.getOpcode() == ISD::TokenFactor &&
478  "Unexpected chain operand");
479  for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
480  if (Chain.getOperand(i).getNode() == Load.getNode())
481  Ops.push_back(Load.getOperand(0));
482  else
483  Ops.push_back(Chain.getOperand(i));
484  SDValue NewChain =
485  CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
486  Ops.clear();
487  Ops.push_back(NewChain);
488  }
489  Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
490  CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
491  CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
492  Load.getOperand(1), Load.getOperand(2));
493 
494  Ops.clear();
495  Ops.push_back(SDValue(Load.getNode(), 1));
496  Ops.append(Call->op_begin() + 1, Call->op_end());
497  CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
498 }
499 
500 /// Return true if call address is a load and it can be
501 /// moved below CALLSEQ_START and the chains leading up to the call.
502 /// Return the CALLSEQ_START by reference as a second output.
503 /// In the case of a tail call, there isn't a callseq node between the call
504 /// chain and the load.
505 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
506  // The transformation is somewhat dangerous if the call's chain was glued to
507  // the call. After MoveBelowOrigChain the load is moved between the call and
508  // the chain, this can create a cycle if the load is not folded. So it is
509  // *really* important that we are sure the load will be folded.
510  if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
511  return false;
512  LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
513  if (!LD ||
514  LD->isVolatile() ||
517  return false;
518 
519  // Now let's find the callseq_start.
520  while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
521  if (!Chain.hasOneUse())
522  return false;
523  Chain = Chain.getOperand(0);
524  }
525 
526  if (!Chain.getNumOperands())
527  return false;
528  // Since we are not checking for AA here, conservatively abort if the chain
529  // writes to memory. It's not safe to move the callee (a load) across a store.
530  if (isa<MemSDNode>(Chain.getNode()) &&
531  cast<MemSDNode>(Chain.getNode())->writeMem())
532  return false;
533  if (Chain.getOperand(0).getNode() == Callee.getNode())
534  return true;
535  if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
536  Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
537  Callee.getValue(1).hasOneUse())
538  return true;
539  return false;
540 }
541 
542 void X86DAGToDAGISel::PreprocessISelDAG() {
543  // OptFor[Min]Size are used in pattern predicates that isel is matching.
544  OptForSize = MF->getFunction()->optForSize();
545  OptForMinSize = MF->getFunction()->optForMinSize();
546  assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
547 
548  for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
549  E = CurDAG->allnodes_end(); I != E; ) {
550  SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
551 
552  if (OptLevel != CodeGenOpt::None &&
553  // Only does this when target favors doesn't favor register indirect
554  // call.
555  ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
556  (N->getOpcode() == X86ISD::TC_RETURN &&
557  // Only does this if load can be folded into TC_RETURN.
558  (Subtarget->is64Bit() ||
559  !getTargetMachine().isPositionIndependent())))) {
560  /// Also try moving call address load from outside callseq_start to just
561  /// before the call to allow it to be folded.
562  ///
563  /// [Load chain]
564  /// ^
565  /// |
566  /// [Load]
567  /// ^ ^
568  /// | |
569  /// / \--
570  /// / |
571  ///[CALLSEQ_START] |
572  /// ^ |
573  /// | |
574  /// [LOAD/C2Reg] |
575  /// | |
576  /// \ /
577  /// \ /
578  /// [CALL]
579  bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
580  SDValue Chain = N->getOperand(0);
581  SDValue Load = N->getOperand(1);
582  if (!isCalleeLoad(Load, Chain, HasCallSeq))
583  continue;
584  moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
585  ++NumLoadMoved;
586  continue;
587  }
588 
589  // Lower fpround and fpextend nodes that target the FP stack to be store and
590  // load to the stack. This is a gross hack. We would like to simply mark
591  // these as being illegal, but when we do that, legalize produces these when
592  // it expands calls, then expands these in the same legalize pass. We would
593  // like dag combine to be able to hack on these between the call expansion
594  // and the node legalization. As such this pass basically does "really
595  // late" legalization of these inline with the X86 isel pass.
596  // FIXME: This should only happen when not compiled with -O0.
597  if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
598  continue;
599 
600  MVT SrcVT = N->getOperand(0).getSimpleValueType();
601  MVT DstVT = N->getSimpleValueType(0);
602 
603  // If any of the sources are vectors, no fp stack involved.
604  if (SrcVT.isVector() || DstVT.isVector())
605  continue;
606 
607  // If the source and destination are SSE registers, then this is a legal
608  // conversion that should not be lowered.
609  const X86TargetLowering *X86Lowering =
610  static_cast<const X86TargetLowering *>(TLI);
611  bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
612  bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
613  if (SrcIsSSE && DstIsSSE)
614  continue;
615 
616  if (!SrcIsSSE && !DstIsSSE) {
617  // If this is an FPStack extension, it is a noop.
618  if (N->getOpcode() == ISD::FP_EXTEND)
619  continue;
620  // If this is a value-preserving FPStack truncation, it is a noop.
621  if (N->getConstantOperandVal(1))
622  continue;
623  }
624 
625  // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
626  // FPStack has extload and truncstore. SSE can fold direct loads into other
627  // operations. Based on this, decide what we want to do.
628  MVT MemVT;
629  if (N->getOpcode() == ISD::FP_ROUND)
630  MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
631  else
632  MemVT = SrcIsSSE ? SrcVT : DstVT;
633 
634  SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
635  SDLoc dl(N);
636 
637  // FIXME: optimize the case where the src/dest is a load or store?
638  SDValue Store =
639  CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
640  MemTmp, MachinePointerInfo(), MemVT);
641  SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
642  MachinePointerInfo(), MemVT);
643 
644  // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
645  // extload we created. This will cause general havok on the dag because
646  // anything below the conversion could be folded into other existing nodes.
647  // To avoid invalidating 'I', back it up to the convert node.
648  --I;
649  CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
650 
651  // Now that we did that, the node is dead. Increment the iterator to the
652  // next node to process, then delete N.
653  ++I;
654  CurDAG->DeleteNode(N);
655  }
656 }
657 
658 
659 /// Emit any code that needs to be executed only in the main function.
660 void X86DAGToDAGISel::emitSpecialCodeForMain() {
661  if (Subtarget->isTargetCygMing()) {
663  auto &DL = CurDAG->getDataLayout();
664 
666  CLI.setChain(CurDAG->getRoot())
667  .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
668  CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
669  std::move(Args));
670  const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
671  std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
672  CurDAG->setRoot(Result.second);
673  }
674 }
675 
676 void X86DAGToDAGISel::EmitFunctionEntryCode() {
677  // If this is main, emit special code for main.
678  if (const Function *Fn = MF->getFunction())
679  if (Fn->hasExternalLinkage() && Fn->getName() == "main")
680  emitSpecialCodeForMain();
681 }
682 
683 static bool isDispSafeForFrameIndex(int64_t Val) {
684  // On 64-bit platforms, we can run into an issue where a frame index
685  // includes a displacement that, when added to the explicit displacement,
686  // will overflow the displacement field. Assuming that the frame index
687  // displacement fits into a 31-bit integer (which is only slightly more
688  // aggressive than the current fundamental assumption that it fits into
689  // a 32-bit integer), a 31-bit disp should always be safe.
690  return isInt<31>(Val);
691 }
692 
693 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
694  X86ISelAddressMode &AM) {
695  // Cannot combine ExternalSymbol displacements with integer offsets.
696  if (Offset != 0 && (AM.ES || AM.MCSym))
697  return true;
698  int64_t Val = AM.Disp + Offset;
699  CodeModel::Model M = TM.getCodeModel();
700  if (Subtarget->is64Bit()) {
702  AM.hasSymbolicDisplacement()))
703  return true;
704  // In addition to the checks required for a register base, check that
705  // we do not try to use an unsafe Disp with a frame index.
706  if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
708  return true;
709  }
710  AM.Disp = Val;
711  return false;
712 
713 }
714 
715 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
716  SDValue Address = N->getOperand(1);
717 
718  // load gs:0 -> GS segment register.
719  // load fs:0 -> FS segment register.
720  //
721  // This optimization is valid because the GNU TLS model defines that
722  // gs:0 (or fs:0 on X86-64) contains its own address.
723  // For more information see http://people.redhat.com/drepper/tls.pdf
724  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
725  if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
726  (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
727  Subtarget->isTargetFuchsia()))
728  switch (N->getPointerInfo().getAddrSpace()) {
729  case 256:
730  AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
731  return false;
732  case 257:
733  AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
734  return false;
735  // Address space 258 is not handled here, because it is not used to
736  // address TLS areas.
737  }
738 
739  return true;
740 }
741 
742 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
743 /// mode. These wrap things that will resolve down into a symbol reference.
744 /// If no match is possible, this returns true, otherwise it returns false.
745 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
746  // If the addressing mode already has a symbol as the displacement, we can
747  // never match another symbol.
748  if (AM.hasSymbolicDisplacement())
749  return true;
750 
751  SDValue N0 = N.getOperand(0);
752  CodeModel::Model M = TM.getCodeModel();
753 
754  // Handle X86-64 rip-relative addresses. We check this before checking direct
755  // folding because RIP is preferable to non-RIP accesses.
756  if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
757  // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
758  // they cannot be folded into immediate fields.
759  // FIXME: This can be improved for kernel and other models?
760  (M == CodeModel::Small || M == CodeModel::Kernel)) {
761  // Base and index reg must be 0 in order to use %rip as base.
762  if (AM.hasBaseOrIndexReg())
763  return true;
764  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
765  X86ISelAddressMode Backup = AM;
766  AM.GV = G->getGlobal();
767  AM.SymbolFlags = G->getTargetFlags();
768  if (foldOffsetIntoAddress(G->getOffset(), AM)) {
769  AM = Backup;
770  return true;
771  }
772  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
773  X86ISelAddressMode Backup = AM;
774  AM.CP = CP->getConstVal();
775  AM.Align = CP->getAlignment();
776  AM.SymbolFlags = CP->getTargetFlags();
777  if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
778  AM = Backup;
779  return true;
780  }
781  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
782  AM.ES = S->getSymbol();
783  AM.SymbolFlags = S->getTargetFlags();
784  } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
785  AM.MCSym = S->getMCSymbol();
786  } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
787  AM.JT = J->getIndex();
788  AM.SymbolFlags = J->getTargetFlags();
789  } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
790  X86ISelAddressMode Backup = AM;
791  AM.BlockAddr = BA->getBlockAddress();
792  AM.SymbolFlags = BA->getTargetFlags();
793  if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
794  AM = Backup;
795  return true;
796  }
797  } else
798  llvm_unreachable("Unhandled symbol reference node.");
799 
800  if (N.getOpcode() == X86ISD::WrapperRIP)
801  AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
802  return false;
803  }
804 
805  // Handle the case when globals fit in our immediate field: This is true for
806  // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
807  // mode, this only applies to a non-RIP-relative computation.
808  if (!Subtarget->is64Bit() ||
809  M == CodeModel::Small || M == CodeModel::Kernel) {
811  "RIP-relative addressing already handled");
812  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
813  AM.GV = G->getGlobal();
814  AM.Disp += G->getOffset();
815  AM.SymbolFlags = G->getTargetFlags();
816  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
817  AM.CP = CP->getConstVal();
818  AM.Align = CP->getAlignment();
819  AM.Disp += CP->getOffset();
820  AM.SymbolFlags = CP->getTargetFlags();
821  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
822  AM.ES = S->getSymbol();
823  AM.SymbolFlags = S->getTargetFlags();
824  } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
825  AM.MCSym = S->getMCSymbol();
826  } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
827  AM.JT = J->getIndex();
828  AM.SymbolFlags = J->getTargetFlags();
829  } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
830  AM.BlockAddr = BA->getBlockAddress();
831  AM.Disp += BA->getOffset();
832  AM.SymbolFlags = BA->getTargetFlags();
833  } else
834  llvm_unreachable("Unhandled symbol reference node.");
835  return false;
836  }
837 
838  return true;
839 }
840 
841 /// Add the specified node to the specified addressing mode, returning true if
842 /// it cannot be done. This just pattern matches for the addressing mode.
843 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
844  if (matchAddressRecursively(N, AM, 0))
845  return true;
846 
847  // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
848  // a smaller encoding and avoids a scaled-index.
849  if (AM.Scale == 2 &&
850  AM.BaseType == X86ISelAddressMode::RegBase &&
851  AM.Base_Reg.getNode() == nullptr) {
852  AM.Base_Reg = AM.IndexReg;
853  AM.Scale = 1;
854  }
855 
856  // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
857  // because it has a smaller encoding.
858  // TODO: Which other code models can use this?
859  if (TM.getCodeModel() == CodeModel::Small &&
860  Subtarget->is64Bit() &&
861  AM.Scale == 1 &&
862  AM.BaseType == X86ISelAddressMode::RegBase &&
863  AM.Base_Reg.getNode() == nullptr &&
864  AM.IndexReg.getNode() == nullptr &&
865  AM.SymbolFlags == X86II::MO_NO_FLAG &&
866  AM.hasSymbolicDisplacement())
867  AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
868 
869  return false;
870 }
871 
872 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
873  unsigned Depth) {
874  // Add an artificial use to this node so that we can keep track of
875  // it if it gets CSE'd with a different node.
876  HandleSDNode Handle(N);
877 
878  X86ISelAddressMode Backup = AM;
879  if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
880  !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
881  return false;
882  AM = Backup;
883 
884  // Try again after commuting the operands.
885  if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
886  !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
887  return false;
888  AM = Backup;
889 
890  // If we couldn't fold both operands into the address at the same time,
891  // see if we can just put each operand into a register and fold at least
892  // the add.
893  if (AM.BaseType == X86ISelAddressMode::RegBase &&
894  !AM.Base_Reg.getNode() &&
895  !AM.IndexReg.getNode()) {
896  N = Handle.getValue();
897  AM.Base_Reg = N.getOperand(0);
898  AM.IndexReg = N.getOperand(1);
899  AM.Scale = 1;
900  return false;
901  }
902  N = Handle.getValue();
903  return true;
904 }
905 
906 // Insert a node into the DAG at least before the Pos node's position. This
907 // will reposition the node as needed, and will assign it a node ID that is <=
908 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
909 // IDs! The selection DAG must no longer depend on their uniqueness when this
910 // is used.
911 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
912  if (N.getNode()->getNodeId() == -1 ||
913  N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
914  DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
915  N.getNode()->setNodeId(Pos.getNode()->getNodeId());
916  }
917 }
918 
919 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
920 // safe. This allows us to convert the shift and and into an h-register
921 // extract and a scaled index. Returns false if the simplification is
922 // performed.
924  uint64_t Mask,
925  SDValue Shift, SDValue X,
926  X86ISelAddressMode &AM) {
927  if (Shift.getOpcode() != ISD::SRL ||
928  !isa<ConstantSDNode>(Shift.getOperand(1)) ||
929  !Shift.hasOneUse())
930  return true;
931 
932  int ScaleLog = 8 - Shift.getConstantOperandVal(1);
933  if (ScaleLog <= 0 || ScaleLog >= 4 ||
934  Mask != (0xffu << ScaleLog))
935  return true;
936 
937  MVT VT = N.getSimpleValueType();
938  SDLoc DL(N);
939  SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
940  SDValue NewMask = DAG.getConstant(0xff, DL, VT);
941  SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
942  SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
943  SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
944  SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
945 
946  // Insert the new nodes into the topological ordering. We must do this in
947  // a valid topological ordering as nothing is going to go back and re-sort
948  // these nodes. We continually insert before 'N' in sequence as this is
949  // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
950  // hierarchy left to express.
951  insertDAGNode(DAG, N, Eight);
952  insertDAGNode(DAG, N, Srl);
953  insertDAGNode(DAG, N, NewMask);
954  insertDAGNode(DAG, N, And);
955  insertDAGNode(DAG, N, ShlCount);
956  insertDAGNode(DAG, N, Shl);
957  DAG.ReplaceAllUsesWith(N, Shl);
958  AM.IndexReg = And;
959  AM.Scale = (1 << ScaleLog);
960  return false;
961 }
962 
963 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
964 // allows us to fold the shift into this addressing mode. Returns false if the
965 // transform succeeded.
967  uint64_t Mask,
968  SDValue Shift, SDValue X,
969  X86ISelAddressMode &AM) {
970  if (Shift.getOpcode() != ISD::SHL ||
971  !isa<ConstantSDNode>(Shift.getOperand(1)))
972  return true;
973 
974  // Not likely to be profitable if either the AND or SHIFT node has more
975  // than one use (unless all uses are for address computation). Besides,
976  // isel mechanism requires their node ids to be reused.
977  if (!N.hasOneUse() || !Shift.hasOneUse())
978  return true;
979 
980  // Verify that the shift amount is something we can fold.
981  unsigned ShiftAmt = Shift.getConstantOperandVal(1);
982  if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
983  return true;
984 
985  MVT VT = N.getSimpleValueType();
986  SDLoc DL(N);
987  SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
988  SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
989  SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
990 
991  // Insert the new nodes into the topological ordering. We must do this in
992  // a valid topological ordering as nothing is going to go back and re-sort
993  // these nodes. We continually insert before 'N' in sequence as this is
994  // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
995  // hierarchy left to express.
996  insertDAGNode(DAG, N, NewMask);
997  insertDAGNode(DAG, N, NewAnd);
998  insertDAGNode(DAG, N, NewShift);
999  DAG.ReplaceAllUsesWith(N, NewShift);
1000 
1001  AM.Scale = 1 << ShiftAmt;
1002  AM.IndexReg = NewAnd;
1003  return false;
1004 }
1005 
1006 // Implement some heroics to detect shifts of masked values where the mask can
1007 // be replaced by extending the shift and undoing that in the addressing mode
1008 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1009 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1010 // the addressing mode. This results in code such as:
1011 //
1012 // int f(short *y, int *lookup_table) {
1013 // ...
1014 // return *y + lookup_table[*y >> 11];
1015 // }
1016 //
1017 // Turning into:
1018 // movzwl (%rdi), %eax
1019 // movl %eax, %ecx
1020 // shrl $11, %ecx
1021 // addl (%rsi,%rcx,4), %eax
1022 //
1023 // Instead of:
1024 // movzwl (%rdi), %eax
1025 // movl %eax, %ecx
1026 // shrl $9, %ecx
1027 // andl $124, %rcx
1028 // addl (%rsi,%rcx), %eax
1029 //
1030 // Note that this function assumes the mask is provided as a mask *after* the
1031 // value is shifted. The input chain may or may not match that, but computing
1032 // such a mask is trivial.
1034  uint64_t Mask,
1035  SDValue Shift, SDValue X,
1036  X86ISelAddressMode &AM) {
1037  if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1038  !isa<ConstantSDNode>(Shift.getOperand(1)))
1039  return true;
1040 
1041  unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1042  unsigned MaskLZ = countLeadingZeros(Mask);
1043  unsigned MaskTZ = countTrailingZeros(Mask);
1044 
1045  // The amount of shift we're trying to fit into the addressing mode is taken
1046  // from the trailing zeros of the mask.
1047  unsigned AMShiftAmt = MaskTZ;
1048 
1049  // There is nothing we can do here unless the mask is removing some bits.
1050  // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1051  if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1052 
1053  // We also need to ensure that mask is a continuous run of bits.
1054  if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1055 
1056  // Scale the leading zero count down based on the actual size of the value.
1057  // Also scale it down based on the size of the shift.
1058  unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1059  if (MaskLZ < ScaleDown)
1060  return true;
1061  MaskLZ -= ScaleDown;
1062 
1063  // The final check is to ensure that any masked out high bits of X are
1064  // already known to be zero. Otherwise, the mask has a semantic impact
1065  // other than masking out a couple of low bits. Unfortunately, because of
1066  // the mask, zero extensions will be removed from operands in some cases.
1067  // This code works extra hard to look through extensions because we can
1068  // replace them with zero extensions cheaply if necessary.
1069  bool ReplacingAnyExtend = false;
1070  if (X.getOpcode() == ISD::ANY_EXTEND) {
1071  unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1073  // Assume that we'll replace the any-extend with a zero-extend, and
1074  // narrow the search to the extended value.
1075  X = X.getOperand(0);
1076  MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1077  ReplacingAnyExtend = true;
1078  }
1079  APInt MaskedHighBits =
1081  KnownBits Known;
1082  DAG.computeKnownBits(X, Known);
1083  if (MaskedHighBits != Known.Zero) return true;
1084 
1085  // We've identified a pattern that can be transformed into a single shift
1086  // and an addressing mode. Make it so.
1087  MVT VT = N.getSimpleValueType();
1088  if (ReplacingAnyExtend) {
1089  assert(X.getValueType() != VT);
1090  // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1091  SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1092  insertDAGNode(DAG, N, NewX);
1093  X = NewX;
1094  }
1095  SDLoc DL(N);
1096  SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1097  SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1098  SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1099  SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1100 
1101  // Insert the new nodes into the topological ordering. We must do this in
1102  // a valid topological ordering as nothing is going to go back and re-sort
1103  // these nodes. We continually insert before 'N' in sequence as this is
1104  // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1105  // hierarchy left to express.
1106  insertDAGNode(DAG, N, NewSRLAmt);
1107  insertDAGNode(DAG, N, NewSRL);
1108  insertDAGNode(DAG, N, NewSHLAmt);
1109  insertDAGNode(DAG, N, NewSHL);
1110  DAG.ReplaceAllUsesWith(N, NewSHL);
1111 
1112  AM.Scale = 1 << AMShiftAmt;
1113  AM.IndexReg = NewSRL;
1114  return false;
1115 }
1116 
1117 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1118  unsigned Depth) {
1119  SDLoc dl(N);
1120  DEBUG({
1121  dbgs() << "MatchAddress: ";
1122  AM.dump();
1123  });
1124  // Limit recursion.
1125  if (Depth > 5)
1126  return matchAddressBase(N, AM);
1127 
1128  // If this is already a %rip relative address, we can only merge immediates
1129  // into it. Instead of handling this in every case, we handle it here.
1130  // RIP relative addressing: %rip + 32-bit displacement!
1131  if (AM.isRIPRelative()) {
1132  // FIXME: JumpTable and ExternalSymbol address currently don't like
1133  // displacements. It isn't very important, but this should be fixed for
1134  // consistency.
1135  if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1136  return true;
1137 
1138  if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1139  if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1140  return false;
1141  return true;
1142  }
1143 
1144  switch (N.getOpcode()) {
1145  default: break;
1146  case ISD::LOCAL_RECOVER: {
1147  if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1148  if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1149  // Use the symbol and don't prefix it.
1150  AM.MCSym = ESNode->getMCSymbol();
1151  return false;
1152  }
1153  break;
1154  }
1155  case ISD::Constant: {
1156  uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1157  if (!foldOffsetIntoAddress(Val, AM))
1158  return false;
1159  break;
1160  }
1161 
1162  case X86ISD::Wrapper:
1163  case X86ISD::WrapperRIP:
1164  if (!matchWrapper(N, AM))
1165  return false;
1166  break;
1167 
1168  case ISD::LOAD:
1169  if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1170  return false;
1171  break;
1172 
1173  case ISD::FrameIndex:
1174  if (AM.BaseType == X86ISelAddressMode::RegBase &&
1175  AM.Base_Reg.getNode() == nullptr &&
1176  (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1177  AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1178  AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1179  return false;
1180  }
1181  break;
1182 
1183  case ISD::SHL:
1184  if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1185  break;
1186 
1187  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1188  unsigned Val = CN->getZExtValue();
1189  // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1190  // that the base operand remains free for further matching. If
1191  // the base doesn't end up getting used, a post-processing step
1192  // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1193  if (Val == 1 || Val == 2 || Val == 3) {
1194  AM.Scale = 1 << Val;
1195  SDValue ShVal = N.getOperand(0);
1196 
1197  // Okay, we know that we have a scale by now. However, if the scaled
1198  // value is an add of something and a constant, we can fold the
1199  // constant into the disp field here.
1200  if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1201  AM.IndexReg = ShVal.getOperand(0);
1202  ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
1203  uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1204  if (!foldOffsetIntoAddress(Disp, AM))
1205  return false;
1206  }
1207 
1208  AM.IndexReg = ShVal;
1209  return false;
1210  }
1211  }
1212  break;
1213 
1214  case ISD::SRL: {
1215  // Scale must not be used already.
1216  if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1217 
1218  SDValue And = N.getOperand(0);
1219  if (And.getOpcode() != ISD::AND) break;
1220  SDValue X = And.getOperand(0);
1221 
1222  // We only handle up to 64-bit values here as those are what matter for
1223  // addressing mode optimizations.
1224  if (X.getSimpleValueType().getSizeInBits() > 64) break;
1225 
1226  // The mask used for the transform is expected to be post-shift, but we
1227  // found the shift first so just apply the shift to the mask before passing
1228  // it down.
1229  if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1230  !isa<ConstantSDNode>(And.getOperand(1)))
1231  break;
1232  uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1233 
1234  // Try to fold the mask and shift into the scale, and return false if we
1235  // succeed.
1236  if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1237  return false;
1238  break;
1239  }
1240 
1241  case ISD::SMUL_LOHI:
1242  case ISD::UMUL_LOHI:
1243  // A mul_lohi where we need the low part can be folded as a plain multiply.
1244  if (N.getResNo() != 0) break;
1246  case ISD::MUL:
1247  case X86ISD::MUL_IMM:
1248  // X*[3,5,9] -> X+X*[2,4,8]
1249  if (AM.BaseType == X86ISelAddressMode::RegBase &&
1250  AM.Base_Reg.getNode() == nullptr &&
1251  AM.IndexReg.getNode() == nullptr) {
1252  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1253  if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1254  CN->getZExtValue() == 9) {
1255  AM.Scale = unsigned(CN->getZExtValue())-1;
1256 
1257  SDValue MulVal = N.getOperand(0);
1258  SDValue Reg;
1259 
1260  // Okay, we know that we have a scale by now. However, if the scaled
1261  // value is an add of something and a constant, we can fold the
1262  // constant into the disp field here.
1263  if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1264  isa<ConstantSDNode>(MulVal.getOperand(1))) {
1265  Reg = MulVal.getOperand(0);
1266  ConstantSDNode *AddVal =
1267  cast<ConstantSDNode>(MulVal.getOperand(1));
1268  uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1269  if (foldOffsetIntoAddress(Disp, AM))
1270  Reg = N.getOperand(0);
1271  } else {
1272  Reg = N.getOperand(0);
1273  }
1274 
1275  AM.IndexReg = AM.Base_Reg = Reg;
1276  return false;
1277  }
1278  }
1279  break;
1280 
1281  case ISD::SUB: {
1282  // Given A-B, if A can be completely folded into the address and
1283  // the index field with the index field unused, use -B as the index.
1284  // This is a win if a has multiple parts that can be folded into
1285  // the address. Also, this saves a mov if the base register has
1286  // other uses, since it avoids a two-address sub instruction, however
1287  // it costs an additional mov if the index register has other uses.
1288 
1289  // Add an artificial use to this node so that we can keep track of
1290  // it if it gets CSE'd with a different node.
1291  HandleSDNode Handle(N);
1292 
1293  // Test if the LHS of the sub can be folded.
1294  X86ISelAddressMode Backup = AM;
1295  if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
1296  AM = Backup;
1297  break;
1298  }
1299  // Test if the index field is free for use.
1300  if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1301  AM = Backup;
1302  break;
1303  }
1304 
1305  int Cost = 0;
1306  SDValue RHS = Handle.getValue().getOperand(1);
1307  // If the RHS involves a register with multiple uses, this
1308  // transformation incurs an extra mov, due to the neg instruction
1309  // clobbering its operand.
1310  if (!RHS.getNode()->hasOneUse() ||
1311  RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1312  RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1313  RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1314  (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1315  RHS.getOperand(0).getValueType() == MVT::i32))
1316  ++Cost;
1317  // If the base is a register with multiple uses, this
1318  // transformation may save a mov.
1319  // FIXME: Don't rely on DELETED_NODEs.
1320  if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1321  AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
1322  !AM.Base_Reg.getNode()->hasOneUse()) ||
1323  AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1324  --Cost;
1325  // If the folded LHS was interesting, this transformation saves
1326  // address arithmetic.
1327  if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1328  ((AM.Disp != 0) && (Backup.Disp == 0)) +
1329  (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1330  --Cost;
1331  // If it doesn't look like it may be an overall win, don't do it.
1332  if (Cost >= 0) {
1333  AM = Backup;
1334  break;
1335  }
1336 
1337  // Ok, the transformation is legal and appears profitable. Go for it.
1338  SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1339  SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1340  AM.IndexReg = Neg;
1341  AM.Scale = 1;
1342 
1343  // Insert the new nodes into the topological ordering.
1344  insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1345  insertDAGNode(*CurDAG, Handle.getValue(), Neg);
1346  return false;
1347  }
1348 
1349  case ISD::ADD:
1350  if (!matchAdd(N, AM, Depth))
1351  return false;
1352  break;
1353 
1354  case ISD::OR:
1355  // We want to look through a transform in InstCombine and DAGCombiner that
1356  // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1357  // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1358  // An 'lea' can then be used to match the shift (multiply) and add:
1359  // and $1, %esi
1360  // lea (%rsi, %rdi, 8), %rax
1361  if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1362  !matchAdd(N, AM, Depth))
1363  return false;
1364  break;
1365 
1366  case ISD::AND: {
1367  // Perform some heroic transforms on an and of a constant-count shift
1368  // with a constant to enable use of the scaled offset field.
1369 
1370  // Scale must not be used already.
1371  if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1372 
1373  SDValue Shift = N.getOperand(0);
1374  if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1375  SDValue X = Shift.getOperand(0);
1376 
1377  // We only handle up to 64-bit values here as those are what matter for
1378  // addressing mode optimizations.
1379  if (X.getSimpleValueType().getSizeInBits() > 64) break;
1380 
1381  if (!isa<ConstantSDNode>(N.getOperand(1)))
1382  break;
1383  uint64_t Mask = N.getConstantOperandVal(1);
1384 
1385  // Try to fold the mask and shift into an extract and scale.
1386  if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1387  return false;
1388 
1389  // Try to fold the mask and shift directly into the scale.
1390  if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1391  return false;
1392 
1393  // Try to swap the mask and shift to place shifts which can be done as
1394  // a scale on the outside of the mask.
1395  if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1396  return false;
1397  break;
1398  }
1399  }
1400 
1401  return matchAddressBase(N, AM);
1402 }
1403 
1404 /// Helper for MatchAddress. Add the specified node to the
1405 /// specified addressing mode without any further recursion.
1406 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1407  // Is the base register already occupied?
1408  if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1409  // If so, check to see if the scale index register is set.
1410  if (!AM.IndexReg.getNode()) {
1411  AM.IndexReg = N;
1412  AM.Scale = 1;
1413  return false;
1414  }
1415 
1416  // Otherwise, we cannot select it.
1417  return true;
1418  }
1419 
1420  // Default, generate it as a register.
1421  AM.BaseType = X86ISelAddressMode::RegBase;
1422  AM.Base_Reg = N;
1423  return false;
1424 }
1425 
1426 template <class GatherScatterSDNode>
1427 bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1428  GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1429  SDValue &Index, SDValue &Disp, SDValue &Segment) {
1430  X86ISelAddressMode AM;
1431  unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1432  // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1433  if (AddrSpace == 256)
1434  AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1435  if (AddrSpace == 257)
1436  AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1437  if (AddrSpace == 258)
1438  AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1439 
1440  SDLoc DL(N);
1441  Base = Mgs->getBasePtr();
1442  Index = Mgs->getIndex();
1443  unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
1444  Scale = getI8Imm(ScalarSize/8, DL);
1445 
1446  // If Base is 0, the whole address is in index and the Scale is 1
1447  if (isa<ConstantSDNode>(Base)) {
1448  assert(cast<ConstantSDNode>(Base)->isNullValue() &&
1449  "Unexpected base in gather/scatter");
1450  Scale = getI8Imm(1, DL);
1451  Base = CurDAG->getRegister(0, MVT::i32);
1452  }
1453  if (AM.Segment.getNode())
1454  Segment = AM.Segment;
1455  else
1456  Segment = CurDAG->getRegister(0, MVT::i32);
1457  Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1458  return true;
1459 }
1460 
1461 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1462  SDValue &Scale, SDValue &Index,
1463  SDValue &Disp, SDValue &Segment) {
1464  if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1465  return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1466  Mgs, N, Base, Scale, Index, Disp, Segment);
1467  if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1468  return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1469  X86Gather, N, Base, Scale, Index, Disp, Segment);
1470  return false;
1471 }
1472 
1473 /// Returns true if it is able to pattern match an addressing mode.
1474 /// It returns the operands which make up the maximal addressing mode it can
1475 /// match by reference.
1476 ///
1477 /// Parent is the parent node of the addr operand that is being matched. It
1478 /// is always a load, store, atomic node, or null. It is only null when
1479 /// checking memory operands for inline asm nodes.
1480 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1481  SDValue &Scale, SDValue &Index,
1482  SDValue &Disp, SDValue &Segment) {
1483  X86ISelAddressMode AM;
1484 
1485  if (Parent &&
1486  // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1487  // that are not a MemSDNode, and thus don't have proper addrspace info.
1488  Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1489  Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1490  Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1491  Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1492  Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1493  unsigned AddrSpace =
1494  cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1495  // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1496  if (AddrSpace == 256)
1497  AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1498  if (AddrSpace == 257)
1499  AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1500  if (AddrSpace == 258)
1501  AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1502  }
1503 
1504  if (matchAddress(N, AM))
1505  return false;
1506 
1507  MVT VT = N.getSimpleValueType();
1508  if (AM.BaseType == X86ISelAddressMode::RegBase) {
1509  if (!AM.Base_Reg.getNode())
1510  AM.Base_Reg = CurDAG->getRegister(0, VT);
1511  }
1512 
1513  if (!AM.IndexReg.getNode())
1514  AM.IndexReg = CurDAG->getRegister(0, VT);
1515 
1516  getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1517  return true;
1518 }
1519 
1520 /// Match a scalar SSE load. In particular, we want to match a load whose top
1521 /// elements are either undef or zeros. The load flavor is derived from the
1522 /// type of N, which is either v4f32 or v2f64.
1523 ///
1524 /// We also return:
1525 /// PatternChainNode: this is the matched node that has a chain input and
1526 /// output.
1527 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
1528  SDValue N, SDValue &Base,
1529  SDValue &Scale, SDValue &Index,
1530  SDValue &Disp, SDValue &Segment,
1531  SDValue &PatternNodeWithChain) {
1532  // We can allow a full vector load here since narrowing a load is ok.
1533  if (ISD::isNON_EXTLoad(N.getNode())) {
1534  PatternNodeWithChain = N;
1535  if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1536  IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1537  LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1538  return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1539  Segment);
1540  }
1541  }
1542 
1543  // We can also match the special zero extended load opcode.
1544  if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1545  PatternNodeWithChain = N;
1546  if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1547  IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
1548  auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1549  return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1550  Segment);
1551  }
1552  }
1553 
1554  // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1555  // once. Otherwise the load might get duplicated and the chain output of the
1556  // duplicate load will not be observed by all dependencies.
1557  if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
1558  PatternNodeWithChain = N.getOperand(0);
1559  if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1560  IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1561  IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1562  LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1563  return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1564  Segment);
1565  }
1566  }
1567 
1568  // Also handle the case where we explicitly require zeros in the top
1569  // elements. This is a vector shuffle from the zero vector.
1570  if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1571  // Check to see if the top elements are all zeros (or bitcast of zeros).
1573  N.getOperand(0).getNode()->hasOneUse()) {
1574  PatternNodeWithChain = N.getOperand(0).getOperand(0);
1575  if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1576  IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1577  IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1578  // Okay, this is a zero extending load. Fold it.
1579  LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1580  return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1581  Segment);
1582  }
1583  }
1584 
1585  return false;
1586 }
1587 
1588 
1589 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
1590  if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1591  uint64_t ImmVal = CN->getZExtValue();
1592  if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1593  return false;
1594 
1595  Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1596  return true;
1597  }
1598 
1599  // In static codegen with small code model, we can get the address of a label
1600  // into a register with 'movl'. TableGen has already made sure we're looking
1601  // at a label of some kind.
1602  assert(N->getOpcode() == X86ISD::Wrapper &&
1603  "Unexpected node type for MOV32ri64");
1604  N = N.getOperand(0);
1605 
1606  // At least GNU as does not accept 'movl' for TPOFF relocations.
1607  // FIXME: We could use 'movl' when we know we are targeting MC.
1608  if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
1609  return false;
1610 
1611  Imm = N;
1612  if (N->getOpcode() != ISD::TargetGlobalAddress)
1613  return TM.getCodeModel() == CodeModel::Small;
1614 
1616  cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1617  if (!CR)
1618  return TM.getCodeModel() == CodeModel::Small;
1619 
1620  return CR->getUnsignedMax().ult(1ull << 32);
1621 }
1622 
1623 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
1624  SDValue &Scale, SDValue &Index,
1625  SDValue &Disp, SDValue &Segment) {
1626  // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1627  SDLoc DL(N);
1628 
1629  if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1630  return false;
1631 
1633  if (RN && RN->getReg() == 0)
1634  Base = CurDAG->getRegister(0, MVT::i64);
1635  else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1636  // Base could already be %rip, particularly in the x32 ABI.
1637  Base = SDValue(CurDAG->getMachineNode(
1638  TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1639  CurDAG->getTargetConstant(0, DL, MVT::i64),
1640  Base,
1641  CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1642  0);
1643  }
1644 
1645  RN = dyn_cast<RegisterSDNode>(Index);
1646  if (RN && RN->getReg() == 0)
1647  Index = CurDAG->getRegister(0, MVT::i64);
1648  else {
1649  assert(Index.getValueType() == MVT::i32 &&
1650  "Expect to be extending 32-bit registers for use in LEA");
1651  Index = SDValue(CurDAG->getMachineNode(
1652  TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1653  CurDAG->getTargetConstant(0, DL, MVT::i64),
1654  Index,
1655  CurDAG->getTargetConstant(X86::sub_32bit, DL,
1656  MVT::i32)),
1657  0);
1658  }
1659 
1660  return true;
1661 }
1662 
1663 /// Calls SelectAddr and determines if the maximal addressing
1664 /// mode it matches can be cost effectively emitted as an LEA instruction.
1665 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
1666  SDValue &Base, SDValue &Scale,
1667  SDValue &Index, SDValue &Disp,
1668  SDValue &Segment) {
1669  X86ISelAddressMode AM;
1670 
1671  // Save the DL and VT before calling matchAddress, it can invalidate N.
1672  SDLoc DL(N);
1673  MVT VT = N.getSimpleValueType();
1674 
1675  // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1676  // segments.
1677  SDValue Copy = AM.Segment;
1678  SDValue T = CurDAG->getRegister(0, MVT::i32);
1679  AM.Segment = T;
1680  if (matchAddress(N, AM))
1681  return false;
1682  assert (T == AM.Segment);
1683  AM.Segment = Copy;
1684 
1685  unsigned Complexity = 0;
1686  if (AM.BaseType == X86ISelAddressMode::RegBase)
1687  if (AM.Base_Reg.getNode())
1688  Complexity = 1;
1689  else
1690  AM.Base_Reg = CurDAG->getRegister(0, VT);
1691  else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1692  Complexity = 4;
1693 
1694  if (AM.IndexReg.getNode())
1695  Complexity++;
1696  else
1697  AM.IndexReg = CurDAG->getRegister(0, VT);
1698 
1699  // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1700  // a simple shift.
1701  if (AM.Scale > 1)
1702  Complexity++;
1703 
1704  // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1705  // to a LEA. This is determined with some experimentation but is by no means
1706  // optimal (especially for code size consideration). LEA is nice because of
1707  // its three-address nature. Tweak the cost function again when we can run
1708  // convertToThreeAddress() at register allocation time.
1709  if (AM.hasSymbolicDisplacement()) {
1710  // For X86-64, always use LEA to materialize RIP-relative addresses.
1711  if (Subtarget->is64Bit())
1712  Complexity = 4;
1713  else
1714  Complexity += 2;
1715  }
1716 
1717  if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1718  Complexity++;
1719 
1720  // If it isn't worth using an LEA, reject it.
1721  if (Complexity <= 2)
1722  return false;
1723 
1724  getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
1725  return true;
1726 }
1727 
1728 /// This is only run on TargetGlobalTLSAddress nodes.
1729 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
1730  SDValue &Scale, SDValue &Index,
1731  SDValue &Disp, SDValue &Segment) {
1733  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1734 
1735  X86ISelAddressMode AM;
1736  AM.GV = GA->getGlobal();
1737  AM.Disp += GA->getOffset();
1738  AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1739  AM.SymbolFlags = GA->getTargetFlags();
1740 
1741  if (N.getValueType() == MVT::i32) {
1742  AM.Scale = 1;
1743  AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1744  } else {
1745  AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1746  }
1747 
1748  getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1749  return true;
1750 }
1751 
1752 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1753  if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1754  Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1755  N.getValueType());
1756  return true;
1757  }
1758 
1759  // Keep track of the original value type and whether this value was
1760  // truncated. If we see a truncation from pointer type to VT that truncates
1761  // bits that are known to be zero, we can use a narrow reference.
1762  EVT VT = N.getValueType();
1763  bool WasTruncated = false;
1764  if (N.getOpcode() == ISD::TRUNCATE) {
1765  WasTruncated = true;
1766  N = N.getOperand(0);
1767  }
1768 
1769  if (N.getOpcode() != X86ISD::Wrapper)
1770  return false;
1771 
1772  // We can only use non-GlobalValues as immediates if they were not truncated,
1773  // as we do not have any range information. If we have a GlobalValue and the
1774  // address was not truncated, we can select it as an operand directly.
1775  unsigned Opc = N.getOperand(0)->getOpcode();
1776  if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1777  Op = N.getOperand(0);
1778  // We can only select the operand directly if we didn't have to look past a
1779  // truncate.
1780  return !WasTruncated;
1781  }
1782 
1783  // Check that the global's range fits into VT.
1784  auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1785  Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1786  if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1787  return false;
1788 
1789  // Okay, we can use a narrow reference.
1790  Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1791  GA->getOffset(), GA->getTargetFlags());
1792  return true;
1793 }
1794 
1795 bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
1796  SDValue &Base, SDValue &Scale,
1797  SDValue &Index, SDValue &Disp,
1798  SDValue &Segment) {
1799  if (!ISD::isNON_EXTLoad(N.getNode()) ||
1800  !IsProfitableToFold(N, P, P) ||
1801  !IsLegalToFold(N, P, P, OptLevel))
1802  return false;
1803 
1804  return selectAddr(N.getNode(),
1805  N.getOperand(1), Base, Scale, Index, Disp, Segment);
1806 }
1807 
1808 /// Return an SDNode that returns the value of the global base register.
1809 /// Output instructions required to initialize the global base register,
1810 /// if necessary.
1811 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1812  unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1813  auto &DL = MF->getDataLayout();
1814  return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1815 }
1816 
1817 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1818  if (N->getOpcode() == ISD::TRUNCATE)
1819  N = N->getOperand(0).getNode();
1820  if (N->getOpcode() != X86ISD::Wrapper)
1821  return false;
1822 
1823  auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1824  if (!GA)
1825  return false;
1826 
1827  Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1828  return CR && CR->getSignedMin().sge(-1ull << Width) &&
1829  CR->getSignedMax().slt(1ull << Width);
1830 }
1831 
1832 /// Test whether the given X86ISD::CMP node has any uses which require the SF
1833 /// or OF bits to be accurate.
1835  // Examine each user of the node.
1836  for (SDNode::use_iterator UI = N->use_begin(),
1837  UE = N->use_end(); UI != UE; ++UI) {
1838  // Only examine CopyToReg uses.
1839  if (UI->getOpcode() != ISD::CopyToReg)
1840  return false;
1841  // Only examine CopyToReg uses that copy to EFLAGS.
1842  if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1843  X86::EFLAGS)
1844  return false;
1845  // Examine each user of the CopyToReg use.
1846  for (SDNode::use_iterator FlagUI = UI->use_begin(),
1847  FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1848  // Only examine the Flag result.
1849  if (FlagUI.getUse().getResNo() != 1) continue;
1850  // Anything unusual: assume conservatively.
1851  if (!FlagUI->isMachineOpcode()) return false;
1852  // Examine the opcode of the user.
1853  switch (FlagUI->getMachineOpcode()) {
1854  // These comparisons don't treat the most significant bit specially.
1855  case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1856  case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1857  case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1858  case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1859  case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1860  case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1861  case X86::CMOVA16rr: case X86::CMOVA16rm:
1862  case X86::CMOVA32rr: case X86::CMOVA32rm:
1863  case X86::CMOVA64rr: case X86::CMOVA64rm:
1864  case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1865  case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1866  case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1867  case X86::CMOVB16rr: case X86::CMOVB16rm:
1868  case X86::CMOVB32rr: case X86::CMOVB32rm:
1869  case X86::CMOVB64rr: case X86::CMOVB64rm:
1870  case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1871  case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1872  case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1873  case X86::CMOVE16rr: case X86::CMOVE16rm:
1874  case X86::CMOVE32rr: case X86::CMOVE32rm:
1875  case X86::CMOVE64rr: case X86::CMOVE64rm:
1876  case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1877  case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1878  case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1879  case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1880  case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1881  case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1882  case X86::CMOVP16rr: case X86::CMOVP16rm:
1883  case X86::CMOVP32rr: case X86::CMOVP32rm:
1884  case X86::CMOVP64rr: case X86::CMOVP64rm:
1885  continue;
1886  // Anything else: assume conservatively.
1887  default: return false;
1888  }
1889  }
1890  }
1891  return true;
1892 }
1893 
1894 /// Check whether or not the chain ending in StoreNode is suitable for doing
1895 /// the {load; increment or decrement; store} to modify transformation.
1896 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1897  SDValue StoredVal, SelectionDAG *CurDAG,
1898  LoadSDNode* &LoadNode, SDValue &InputChain) {
1899 
1900  // is the value stored the result of a DEC or INC?
1901  if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1902 
1903  // is the stored value result 0 of the load?
1904  if (StoredVal.getResNo() != 0) return false;
1905 
1906  // are there other uses of the loaded value than the inc or dec?
1907  if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1908 
1909  // is the store non-extending and non-indexed?
1910  if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
1911  return false;
1912 
1913  SDValue Load = StoredVal->getOperand(0);
1914  // Is the stored value a non-extending and non-indexed load?
1915  if (!ISD::isNormalLoad(Load.getNode())) return false;
1916 
1917  // Return LoadNode by reference.
1918  LoadNode = cast<LoadSDNode>(Load);
1919  // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
1920  EVT LdVT = LoadNode->getMemoryVT();
1921  if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
1922  LdVT != MVT::i8)
1923  return false;
1924 
1925  // Is store the only read of the loaded value?
1926  if (!Load.hasOneUse())
1927  return false;
1928 
1929  // Is the address of the store the same as the load?
1930  if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1931  LoadNode->getOffset() != StoreNode->getOffset())
1932  return false;
1933 
1934  // Check if the chain is produced by the load or is a TokenFactor with
1935  // the load output chain as an operand. Return InputChain by reference.
1936  SDValue Chain = StoreNode->getChain();
1937 
1938  bool ChainCheck = false;
1939  if (Chain == Load.getValue(1)) {
1940  ChainCheck = true;
1941  InputChain = LoadNode->getChain();
1942  } else if (Chain.getOpcode() == ISD::TokenFactor) {
1943  SmallVector<SDValue, 4> ChainOps;
1944  for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1945  SDValue Op = Chain.getOperand(i);
1946  if (Op == Load.getValue(1)) {
1947  ChainCheck = true;
1948  // Drop Load, but keep its chain. No cycle check necessary.
1949  ChainOps.push_back(Load.getOperand(0));
1950  continue;
1951  }
1952 
1953  // Make sure using Op as part of the chain would not cause a cycle here.
1954  // In theory, we could check whether the chain node is a predecessor of
1955  // the load. But that can be very expensive. Instead visit the uses and
1956  // make sure they all have smaller node id than the load.
1957  int LoadId = LoadNode->getNodeId();
1958  for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1959  UE = UI->use_end(); UI != UE; ++UI) {
1960  if (UI.getUse().getResNo() != 0)
1961  continue;
1962  if (UI->getNodeId() > LoadId)
1963  return false;
1964  }
1965 
1966  ChainOps.push_back(Op);
1967  }
1968 
1969  if (ChainCheck)
1970  // Make a new TokenFactor with all the other input chains except
1971  // for the load.
1972  InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
1973  MVT::Other, ChainOps);
1974  }
1975  if (!ChainCheck)
1976  return false;
1977 
1978  return true;
1979 }
1980 
1981 /// Get the appropriate X86 opcode for an in-memory increment or decrement.
1982 /// Opc should be X86ISD::DEC or X86ISD::INC.
1983 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
1984  if (Opc == X86ISD::DEC) {
1985  if (LdVT == MVT::i64) return X86::DEC64m;
1986  if (LdVT == MVT::i32) return X86::DEC32m;
1987  if (LdVT == MVT::i16) return X86::DEC16m;
1988  if (LdVT == MVT::i8) return X86::DEC8m;
1989  } else {
1990  assert(Opc == X86ISD::INC && "unrecognized opcode");
1991  if (LdVT == MVT::i64) return X86::INC64m;
1992  if (LdVT == MVT::i32) return X86::INC32m;
1993  if (LdVT == MVT::i16) return X86::INC16m;
1994  if (LdVT == MVT::i8) return X86::INC8m;
1995  }
1996  llvm_unreachable("unrecognized size for LdVT");
1997 }
1998 
1999 void X86DAGToDAGISel::Select(SDNode *Node) {
2000  MVT NVT = Node->getSimpleValueType(0);
2001  unsigned Opc, MOpc;
2002  unsigned Opcode = Node->getOpcode();
2003  SDLoc dl(Node);
2004 
2005  DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2006 
2007  if (Node->isMachineOpcode()) {
2008  DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
2009  Node->setNodeId(-1);
2010  return; // Already selected.
2011  }
2012 
2013  switch (Opcode) {
2014  default: break;
2015  case ISD::BRIND: {
2016  if (Subtarget->isTargetNaCl())
2017  // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2018  // leave the instruction alone.
2019  break;
2020  if (Subtarget->isTarget64BitILP32()) {
2021  // Converts a 32-bit register to a 64-bit, zero-extended version of
2022  // it. This is needed because x86-64 can do many things, but jmp %r32
2023  // ain't one of them.
2024  const SDValue &Target = Node->getOperand(1);
2026  SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2027  SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2028  Node->getOperand(0), ZextTarget);
2029  ReplaceNode(Node, Brind.getNode());
2030  SelectCode(ZextTarget.getNode());
2031  SelectCode(Brind.getNode());
2032  return;
2033  }
2034  break;
2035  }
2036  case X86ISD::GlobalBaseReg:
2037  ReplaceNode(Node, getGlobalBaseReg());
2038  return;
2039 
2040  case X86ISD::SHRUNKBLEND: {
2041  // SHRUNKBLEND selects like a regular VSELECT.
2042  SDValue VSelect = CurDAG->getNode(
2043  ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2044  Node->getOperand(1), Node->getOperand(2));
2045  ReplaceUses(SDValue(Node, 0), VSelect);
2046  SelectCode(VSelect.getNode());
2047  // We already called ReplaceUses.
2048  return;
2049  }
2050 
2051  case ISD::AND:
2052  case ISD::OR:
2053  case ISD::XOR: {
2054  // For operations of the form (x << C1) op C2, check if we can use a smaller
2055  // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2056  SDValue N0 = Node->getOperand(0);
2057  SDValue N1 = Node->getOperand(1);
2058 
2059  if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2060  break;
2061 
2062  // i8 is unshrinkable, i16 should be promoted to i32.
2063  if (NVT != MVT::i32 && NVT != MVT::i64)
2064  break;
2065 
2067  ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2068  if (!Cst || !ShlCst)
2069  break;
2070 
2071  int64_t Val = Cst->getSExtValue();
2072  uint64_t ShlVal = ShlCst->getZExtValue();
2073 
2074  // Make sure that we don't change the operation by removing bits.
2075  // This only matters for OR and XOR, AND is unaffected.
2076  uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2077  if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2078  break;
2079 
2080  unsigned ShlOp, AddOp, Op;
2081  MVT CstVT = NVT;
2082 
2083  // Check the minimum bitwidth for the new constant.
2084  // TODO: AND32ri is the same as AND64ri32 with zext imm.
2085  // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2086  // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2087  if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2088  CstVT = MVT::i8;
2089  else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2090  CstVT = MVT::i32;
2091 
2092  // Bail if there is no smaller encoding.
2093  if (NVT == CstVT)
2094  break;
2095 
2096  switch (NVT.SimpleTy) {
2097  default: llvm_unreachable("Unsupported VT!");
2098  case MVT::i32:
2099  assert(CstVT == MVT::i8);
2100  ShlOp = X86::SHL32ri;
2101  AddOp = X86::ADD32rr;
2102 
2103  switch (Opcode) {
2104  default: llvm_unreachable("Impossible opcode");
2105  case ISD::AND: Op = X86::AND32ri8; break;
2106  case ISD::OR: Op = X86::OR32ri8; break;
2107  case ISD::XOR: Op = X86::XOR32ri8; break;
2108  }
2109  break;
2110  case MVT::i64:
2111  assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2112  ShlOp = X86::SHL64ri;
2113  AddOp = X86::ADD64rr;
2114 
2115  switch (Opcode) {
2116  default: llvm_unreachable("Impossible opcode");
2117  case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2118  case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2119  case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2120  }
2121  break;
2122  }
2123 
2124  // Emit the smaller op and the shift.
2125  SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2126  SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2127  if (ShlVal == 1)
2128  CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2129  SDValue(New, 0));
2130  else
2131  CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2132  getI8Imm(ShlVal, dl));
2133  return;
2134  }
2135  case X86ISD::UMUL8:
2136  case X86ISD::SMUL8: {
2137  SDValue N0 = Node->getOperand(0);
2138  SDValue N1 = Node->getOperand(1);
2139 
2140  Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2141 
2142  SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2143  N0, SDValue()).getValue(1);
2144 
2145  SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2146  SDValue Ops[] = {N1, InFlag};
2147  SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2148 
2149  ReplaceNode(Node, CNode);
2150  return;
2151  }
2152 
2153  case X86ISD::UMUL: {
2154  SDValue N0 = Node->getOperand(0);
2155  SDValue N1 = Node->getOperand(1);
2156 
2157  unsigned LoReg;
2158  switch (NVT.SimpleTy) {
2159  default: llvm_unreachable("Unsupported VT!");
2160  case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2161  case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2162  case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2163  case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2164  }
2165 
2166  SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2167  N0, SDValue()).getValue(1);
2168 
2169  SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2170  SDValue Ops[] = {N1, InFlag};
2171  SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2172 
2173  ReplaceNode(Node, CNode);
2174  return;
2175  }
2176 
2177  case ISD::SMUL_LOHI:
2178  case ISD::UMUL_LOHI: {
2179  SDValue N0 = Node->getOperand(0);
2180  SDValue N1 = Node->getOperand(1);
2181 
2182  bool isSigned = Opcode == ISD::SMUL_LOHI;
2183  bool hasBMI2 = Subtarget->hasBMI2();
2184  if (!isSigned) {
2185  switch (NVT.SimpleTy) {
2186  default: llvm_unreachable("Unsupported VT!");
2187  case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2188  case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2189  case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2190  MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2191  case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2192  MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2193  }
2194  } else {
2195  switch (NVT.SimpleTy) {
2196  default: llvm_unreachable("Unsupported VT!");
2197  case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2198  case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2199  case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2200  case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2201  }
2202  }
2203 
2204  unsigned SrcReg, LoReg, HiReg;
2205  switch (Opc) {
2206  default: llvm_unreachable("Unknown MUL opcode!");
2207  case X86::IMUL8r:
2208  case X86::MUL8r:
2209  SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2210  break;
2211  case X86::IMUL16r:
2212  case X86::MUL16r:
2213  SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2214  break;
2215  case X86::IMUL32r:
2216  case X86::MUL32r:
2217  SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2218  break;
2219  case X86::IMUL64r:
2220  case X86::MUL64r:
2221  SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2222  break;
2223  case X86::MULX32rr:
2224  SrcReg = X86::EDX; LoReg = HiReg = 0;
2225  break;
2226  case X86::MULX64rr:
2227  SrcReg = X86::RDX; LoReg = HiReg = 0;
2228  break;
2229  }
2230 
2231  SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2232  bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2233  // Multiply is commmutative.
2234  if (!foldedLoad) {
2235  foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2236  if (foldedLoad)
2237  std::swap(N0, N1);
2238  }
2239 
2240  SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2241  N0, SDValue()).getValue(1);
2242  SDValue ResHi, ResLo;
2243 
2244  if (foldedLoad) {
2245  SDValue Chain;
2246  MachineSDNode *CNode = nullptr;
2247  SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2248  InFlag };
2249  if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2250  SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2251  CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2252  ResHi = SDValue(CNode, 0);
2253  ResLo = SDValue(CNode, 1);
2254  Chain = SDValue(CNode, 2);
2255  InFlag = SDValue(CNode, 3);
2256  } else {
2257  SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2258  CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2259  Chain = SDValue(CNode, 0);
2260  InFlag = SDValue(CNode, 1);
2261  }
2262 
2263  // Update the chain.
2264  ReplaceUses(N1.getValue(1), Chain);
2265  // Record the mem-refs
2266  LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2267  if (LoadNode) {
2268  MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2269  MemOp[0] = LoadNode->getMemOperand();
2270  CNode->setMemRefs(MemOp, MemOp + 1);
2271  }
2272  } else {
2273  SDValue Ops[] = { N1, InFlag };
2274  if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2275  SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2276  SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2277  ResHi = SDValue(CNode, 0);
2278  ResLo = SDValue(CNode, 1);
2279  InFlag = SDValue(CNode, 2);
2280  } else {
2281  SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2282  SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2283  InFlag = SDValue(CNode, 0);
2284  }
2285  }
2286 
2287  // Prevent use of AH in a REX instruction by referencing AX instead.
2288  if (HiReg == X86::AH && Subtarget->is64Bit() &&
2289  !SDValue(Node, 1).use_empty()) {
2290  SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2291  X86::AX, MVT::i16, InFlag);
2292  InFlag = Result.getValue(2);
2293  // Get the low part if needed. Don't use getCopyFromReg for aliasing
2294  // registers.
2295  if (!SDValue(Node, 0).use_empty())
2296  ReplaceUses(SDValue(Node, 1),
2297  CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2298 
2299  // Shift AX down 8 bits.
2300  Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2301  Result,
2302  CurDAG->getTargetConstant(8, dl, MVT::i8)),
2303  0);
2304  // Then truncate it down to i8.
2305  ReplaceUses(SDValue(Node, 1),
2306  CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2307  }
2308  // Copy the low half of the result, if it is needed.
2309  if (!SDValue(Node, 0).use_empty()) {
2310  if (!ResLo.getNode()) {
2311  assert(LoReg && "Register for low half is not defined!");
2312  ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2313  InFlag);
2314  InFlag = ResLo.getValue(2);
2315  }
2316  ReplaceUses(SDValue(Node, 0), ResLo);
2317  DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2318  }
2319  // Copy the high half of the result, if it is needed.
2320  if (!SDValue(Node, 1).use_empty()) {
2321  if (!ResHi.getNode()) {
2322  assert(HiReg && "Register for high half is not defined!");
2323  ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2324  InFlag);
2325  InFlag = ResHi.getValue(2);
2326  }
2327  ReplaceUses(SDValue(Node, 1), ResHi);
2328  DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2329  }
2330 
2331  return;
2332  }
2333 
2334  case ISD::SDIVREM:
2335  case ISD::UDIVREM:
2338  SDValue N0 = Node->getOperand(0);
2339  SDValue N1 = Node->getOperand(1);
2340 
2341  bool isSigned = (Opcode == ISD::SDIVREM ||
2342  Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2343  if (!isSigned) {
2344  switch (NVT.SimpleTy) {
2345  default: llvm_unreachable("Unsupported VT!");
2346  case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2347  case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2348  case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2349  case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2350  }
2351  } else {
2352  switch (NVT.SimpleTy) {
2353  default: llvm_unreachable("Unsupported VT!");
2354  case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2355  case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2356  case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2357  case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2358  }
2359  }
2360 
2361  unsigned LoReg, HiReg, ClrReg;
2362  unsigned SExtOpcode;
2363  switch (NVT.SimpleTy) {
2364  default: llvm_unreachable("Unsupported VT!");
2365  case MVT::i8:
2366  LoReg = X86::AL; ClrReg = HiReg = X86::AH;
2367  SExtOpcode = X86::CBW;
2368  break;
2369  case MVT::i16:
2370  LoReg = X86::AX; HiReg = X86::DX;
2371  ClrReg = X86::DX;
2372  SExtOpcode = X86::CWD;
2373  break;
2374  case MVT::i32:
2375  LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2376  SExtOpcode = X86::CDQ;
2377  break;
2378  case MVT::i64:
2379  LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2380  SExtOpcode = X86::CQO;
2381  break;
2382  }
2383 
2384  SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2385  bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2386  bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2387 
2388  SDValue InFlag;
2389  if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2390  // Special case for div8, just use a move with zero extension to AX to
2391  // clear the upper 8 bits (AH).
2392  SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2393  if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2394  SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2395  Move =
2396  SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2397  MVT::Other, Ops), 0);
2398  Chain = Move.getValue(1);
2399  ReplaceUses(N0.getValue(1), Chain);
2400  } else {
2401  Move =
2402  SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2403  Chain = CurDAG->getEntryNode();
2404  }
2405  Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2406  InFlag = Chain.getValue(1);
2407  } else {
2408  InFlag =
2409  CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2410  LoReg, N0, SDValue()).getValue(1);
2411  if (isSigned && !signBitIsZero) {
2412  // Sign extend the low part into the high part.
2413  InFlag =
2414  SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2415  } else {
2416  // Zero out the high part, effectively zero extending the input.
2417  SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2418  switch (NVT.SimpleTy) {
2419  case MVT::i16:
2420  ClrNode =
2421  SDValue(CurDAG->getMachineNode(
2422  TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2423  CurDAG->getTargetConstant(X86::sub_16bit, dl,
2424  MVT::i32)),
2425  0);
2426  break;
2427  case MVT::i32:
2428  break;
2429  case MVT::i64:
2430  ClrNode =
2431  SDValue(CurDAG->getMachineNode(
2432  TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2433  CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2434  CurDAG->getTargetConstant(X86::sub_32bit, dl,
2435  MVT::i32)),
2436  0);
2437  break;
2438  default:
2439  llvm_unreachable("Unexpected division source");
2440  }
2441 
2442  InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2443  ClrNode, InFlag).getValue(1);
2444  }
2445  }
2446 
2447  if (foldedLoad) {
2448  SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2449  InFlag };
2450  SDNode *CNode =
2451  CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2452  InFlag = SDValue(CNode, 1);
2453  // Update the chain.
2454  ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2455  } else {
2456  InFlag =
2457  SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2458  }
2459 
2460  // Prevent use of AH in a REX instruction by explicitly copying it to
2461  // an ABCD_L register.
2462  //
2463  // The current assumption of the register allocator is that isel
2464  // won't generate explicit references to the GR8_ABCD_H registers. If
2465  // the allocator and/or the backend get enhanced to be more robust in
2466  // that regard, this can be, and should be, removed.
2467  if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2468  SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2469  unsigned AHExtOpcode =
2470  isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2471 
2472  SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2473  MVT::Glue, AHCopy, InFlag);
2474  SDValue Result(RNode, 0);
2475  InFlag = SDValue(RNode, 1);
2476 
2477  if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2478  Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2479  if (Node->getValueType(1) == MVT::i64) {
2480  // It's not possible to directly movsx AH to a 64bit register, because
2481  // the latter needs the REX prefix, but the former can't have it.
2482  assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2483  "Unexpected i64 sext of h-register");
2484  Result =
2485  SDValue(CurDAG->getMachineNode(
2486  TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2487  CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2488  CurDAG->getTargetConstant(X86::sub_32bit, dl,
2489  MVT::i32)),
2490  0);
2491  }
2492  } else {
2493  Result =
2494  CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2495  }
2496  ReplaceUses(SDValue(Node, 1), Result);
2497  DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2498  }
2499  // Copy the division (low) result, if it is needed.
2500  if (!SDValue(Node, 0).use_empty()) {
2501  SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2502  LoReg, NVT, InFlag);
2503  InFlag = Result.getValue(2);
2504  ReplaceUses(SDValue(Node, 0), Result);
2505  DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2506  }
2507  // Copy the remainder (high) result, if it is needed.
2508  if (!SDValue(Node, 1).use_empty()) {
2509  SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2510  HiReg, NVT, InFlag);
2511  InFlag = Result.getValue(2);
2512  ReplaceUses(SDValue(Node, 1), Result);
2513  DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2514  }
2515  return;
2516  }
2517 
2518  case X86ISD::CMP:
2519  case X86ISD::SUB: {
2520  // Sometimes a SUB is used to perform comparison.
2521  if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2522  // This node is not a CMP.
2523  break;
2524  SDValue N0 = Node->getOperand(0);
2525  SDValue N1 = Node->getOperand(1);
2526 
2527  if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2529  N0 = N0.getOperand(0);
2530 
2531  // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2532  // use a smaller encoding.
2533  // Look past the truncate if CMP is the only use of it.
2534  if ((N0.getNode()->getOpcode() == ISD::AND ||
2535  (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2536  N0.getNode()->hasOneUse() &&
2537  N0.getValueType() != MVT::i8 &&
2538  X86::isZeroNode(N1)) {
2540  if (!C) break;
2541 
2542  // For example, convert "testl %eax, $8" to "testb %al, $8"
2543  if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2544  (!(C->getZExtValue() & 0x80) ||
2545  hasNoSignedComparisonUses(Node))) {
2546  SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2547  SDValue Reg = N0.getOperand(0);
2548 
2549  // On x86-32, only the ABCD registers have 8-bit subregisters.
2550  if (!Subtarget->is64Bit()) {
2551  const TargetRegisterClass *TRC;
2552  switch (N0.getSimpleValueType().SimpleTy) {
2553  case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2554  case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2555  default: llvm_unreachable("Unsupported TEST operand type!");
2556  }
2557  SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2558  Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2559  Reg.getValueType(), Reg, RC), 0);
2560  }
2561 
2562  // Extract the l-register.
2563  SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2564  MVT::i8, Reg);
2565 
2566  // Emit a testb.
2567  SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2568  Subreg, Imm);
2569  // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2570  // one, do not call ReplaceAllUsesWith.
2571  ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2572  SDValue(NewNode, 0));
2573  return;
2574  }
2575 
2576  // For example, "testl %eax, $2048" to "testb %ah, $8".
2577  if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2578  (!(C->getZExtValue() & 0x8000) ||
2579  hasNoSignedComparisonUses(Node))) {
2580  // Shift the immediate right by 8 bits.
2581  SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2582  dl, MVT::i8);
2583  SDValue Reg = N0.getOperand(0);
2584 
2585  // Put the value in an ABCD register.
2586  const TargetRegisterClass *TRC;
2587  switch (N0.getSimpleValueType().SimpleTy) {
2588  case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2589  case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2590  case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2591  default: llvm_unreachable("Unsupported TEST operand type!");
2592  }
2593  SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2594  Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2595  Reg.getValueType(), Reg, RC), 0);
2596 
2597  // Extract the h-register.
2598  SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2599  MVT::i8, Reg);
2600 
2601  // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2602  // target GR8_NOREX registers, so make sure the register class is
2603  // forced.
2604  SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2605  MVT::i32, Subreg, ShiftedImm);
2606  // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2607  // one, do not call ReplaceAllUsesWith.
2608  ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2609  SDValue(NewNode, 0));
2610  return;
2611  }
2612 
2613  // For example, "testl %eax, $32776" to "testw %ax, $32776".
2614  if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2615  N0.getValueType() != MVT::i16 &&
2616  (!(C->getZExtValue() & 0x8000) ||
2617  hasNoSignedComparisonUses(Node))) {
2618  SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2619  MVT::i16);
2620  SDValue Reg = N0.getOperand(0);
2621 
2622  // Extract the 16-bit subregister.
2623  SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2624  MVT::i16, Reg);
2625 
2626  // Emit a testw.
2627  SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2628  Subreg, Imm);
2629  // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2630  // one, do not call ReplaceAllUsesWith.
2631  ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2632  SDValue(NewNode, 0));
2633  return;
2634  }
2635 
2636  // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2637  if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2638  N0.getValueType() == MVT::i64 &&
2639  (!(C->getZExtValue() & 0x80000000) ||
2640  hasNoSignedComparisonUses(Node))) {
2641  SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2642  MVT::i32);
2643  SDValue Reg = N0.getOperand(0);
2644 
2645  // Extract the 32-bit subregister.
2646  SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2647  MVT::i32, Reg);
2648 
2649  // Emit a testl.
2650  SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2651  Subreg, Imm);
2652  // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2653  // one, do not call ReplaceAllUsesWith.
2654  ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2655  SDValue(NewNode, 0));
2656  return;
2657  }
2658  }
2659  break;
2660  }
2661  case ISD::STORE: {
2662  // Change a chain of {load; incr or dec; store} of the same value into
2663  // a simple increment or decrement through memory of that value, if the
2664  // uses of the modified value and its address are suitable.
2665  // The DEC64m tablegen pattern is currently not able to match the case where
2666  // the EFLAGS on the original DEC are used. (This also applies to
2667  // {INC,DEC}X{64,32,16,8}.)
2668  // We'll need to improve tablegen to allow flags to be transferred from a
2669  // node in the pattern to the result node. probably with a new keyword
2670  // for example, we have this
2671  // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2672  // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2673  // (implicit EFLAGS)]>;
2674  // but maybe need something like this
2675  // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2676  // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2677  // (transferrable EFLAGS)]>;
2678 
2679  StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2680  SDValue StoredVal = StoreNode->getOperand(1);
2681  unsigned Opc = StoredVal->getOpcode();
2682 
2683  LoadSDNode *LoadNode = nullptr;
2684  SDValue InputChain;
2685  if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2686  LoadNode, InputChain))
2687  break;
2688 
2689  SDValue Base, Scale, Index, Disp, Segment;
2690  if (!selectAddr(LoadNode, LoadNode->getBasePtr(),
2691  Base, Scale, Index, Disp, Segment))
2692  break;
2693 
2694  MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2695  MemOp[0] = StoreNode->getMemOperand();
2696  MemOp[1] = LoadNode->getMemOperand();
2697  const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2698  EVT LdVT = LoadNode->getMemoryVT();
2699  unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2700  MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2701  SDLoc(Node),
2702  MVT::i32, MVT::Other, Ops);
2703  Result->setMemRefs(MemOp, MemOp + 2);
2704 
2705  ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2706  ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2707  CurDAG->RemoveDeadNode(Node);
2708  return;
2709  }
2710  }
2711 
2712  SelectCode(Node);
2713 }
2714 
2715 bool X86DAGToDAGISel::
2716 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2717  std::vector<SDValue> &OutOps) {
2718  SDValue Op0, Op1, Op2, Op3, Op4;
2719  switch (ConstraintID) {
2720  default:
2721  llvm_unreachable("Unexpected asm memory constraint");
2723  // FIXME: It seems strange that 'i' is needed here since it's supposed to
2724  // be an immediate and not a memory constraint.
2726  case InlineAsm::Constraint_o: // offsetable ??
2727  case InlineAsm::Constraint_v: // not offsetable ??
2728  case InlineAsm::Constraint_m: // memory
2730  if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2731  return true;
2732  break;
2733  }
2734 
2735  OutOps.push_back(Op0);
2736  OutOps.push_back(Op1);
2737  OutOps.push_back(Op2);
2738  OutOps.push_back(Op3);
2739  OutOps.push_back(Op4);
2740  return false;
2741 }
2742 
2743 /// This pass converts a legalized DAG into a X86-specific DAG,
2744 /// ready for instruction scheduling.
2746  CodeGenOpt::Level OptLevel) {
2747  return new X86DAGToDAGISel(TM, OptLevel);
2748 }
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition: ISDOpcodes.h:511
static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq)
Return true if call address is a load and it can be moved below CALLSEQ_START and the chains leading ...
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
SDValue getValue(unsigned R) const
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition: ISDOpcodes.h:42
STATISTIC(NumFunctions,"Total number of functions")
static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N)
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1164
void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd)
Assign this MachineSDNodes's memory reference descriptor list.
bool hasOneUse() const
Return true if there is exactly one use of this node.
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
Tail call return.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node.
unsigned getReg() const
DataLayout DL
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getID() const
Return the register class ID number.
constexpr bool isInt< 8 >(int64_t x)
Definition: MathExtras.h:295
unsigned getSizeInBits() const
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition: ISDOpcodes.h:131
APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getNumOperands() const
const SDValue & getOperand(unsigned Num) const
void setNodeId(int Id)
Set unique node id.
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
const SDValue & getBasePtr() const
std::size_t countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1...
Definition: MathExtras.h:181
unsigned getResNo() const
get the index which selects a specific result in the SDNode
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition: ISDOpcodes.h:159
GlobalBaseReg - On Darwin, this node represents the result of the mflr at function entry...
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition: ISDOpcodes.h:209
X86 compare and logical compare instructions.
The address of a basic block.
Definition: Constants.h:813
A description of a memory reference used in the backend.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Shift and rotation operations.
Definition: ISDOpcodes.h:378
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
std::size_t countTrailingOnes(T Value, ZeroBehavior ZB=ZB_Width)
Count the number of ones from the least significant bit to the first zero bit.
Definition: MathExtras.h:470
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
CopyToReg - This node has three operands: a chain, a register number to set to this value...
Definition: ISDOpcodes.h:170
Reg
All possible values of the reg field in the ModR/M byte.
SimpleValueType SimpleTy
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence, and carry arbitrary information that target might want to know.
Definition: ISDOpcodes.h:673
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc, SDValue StoredVal, SelectionDAG *CurDAG, LoadSDNode *&LoadNode, SDValue &InputChain)
Check whether or not the chain ending in StoreNode is suitable for doing the {load; increment or decr...
#define T
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition: ISDOpcodes.h:397
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
const SDValue & getBasePtr() const
EVT getMemoryVT() const
Return the type of the in-memory value.
This class is used to represent ISD::STORE nodes.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
Definition: APInt.h:629
SDNode * getNode() const
get the SDNode which holds the desired result
Function Alias Analysis false
#define P(N)
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition: ISDOpcodes.h:166
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:112
LOCAL_RECOVER - Represents the llvm.localrecover intrinsic.
Definition: ISDOpcodes.h:81
Machine Value Type.
const SDValue & getOperand(unsigned i) const
static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM)
bool isNonTemporal() const
bool sge(const APInt &RHS) const
Signed greather or equal comparison.
Definition: APInt.h:1288
This is an important base class in LLVM.
Definition: Constant.h:42
bool isVector() const
Return true if this is a vector value type.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
This class provides iterator support for SDUse operands that use a specific SDNode.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
void RepositionNode(allnodes_iterator Position, SDNode *N)
Move node N in the AllNodes list to be immediately before the given iterator Position.
unsigned getOpcode() const
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
On Darwin, this node represents the result of the popl at function entry, used for PIC code...
self_iterator getIterator()
Definition: ilist_node.h:82
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
bool isVolatile() const
static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM)
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition: ISDOpcodes.h:529
std::vector< ArgListEntry > ArgListTy
Extended Value Type.
Definition: ValueTypes.h:34
This structure contains all information that is necessary for lowering calls.
ISD::MemIndexedMode getAddressingMode() const
Return the addressing mode for this load or store: unindexed, pre-inc, pre-dec, post-inc, or post-dec.
This class contains a discriminated union of information about pointers in memory operands...
const MachinePointerInfo & getPointerInfo() const
const SDValue & getOffset() const
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
These operations represent an abstract X86 call instruction, which includes a bunch of information...
TokenFactor - This node takes multiple tokens as input and produces a single token result...
Definition: ISDOpcodes.h:50
Iterator for intrusive lists based on ilist_node.
#define E
Definition: LargeTest.cpp:27
constexpr bool isInt< 32 >(int64_t x)
Definition: MathExtras.h:301
void dump() const
Dump this node, for debugging.
void computeKnownBits(SDValue Op, KnownBits &Known, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:209
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
An SDNode that represents everything that will be needed to construct a MachineInstr.
const SDValue & getChain() const
const size_t N
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
Represents one node in the SelectionDAG.
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:35
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM)
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
Definition: APInt.h:69
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
int64_t getSExtValue() const
op_iterator op_begin() const
static use_iterator use_end()
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:444
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:447
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:395
llvm_unreachable("Unknown RegBank!")
static bool isDispSafeForFrameIndex(int64_t Val)
uint64_t getConstantOperandVal(unsigned i) const
static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc)
Get the appropriate X86 opcode for an in-memory increment or decrement.
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:361
bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition: ISDOpcodes.h:205
A wrapper node for TargetConstantPool, TargetJumpTable, TargetExternalSymbol, TargetGlobalAddress, TargetGlobalTLSAddress, MCSymbol and TargetBlockAddress.
#define C
Definition: LargeTest.cpp:25
FunctionPass * createX86ISelDag(X86TargetMachine &TM, CodeGenOpt::Level OptLevel)
This pass converts a legalized DAG into a X86-specific DAG, ready for instruction scheduling...
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
Definition: ISDOpcodes.h:580
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:292
void ReplaceAllUsesWith(SDValue From, SDValue Op)
Modify anything using 'From' to use 'To' instead.
#define I(x, y, z)
Definition: MD5.cpp:58
bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
op_iterator op_end() const
const SDValue & getOffset() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
static volatile int Zero
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
int getNodeId() const
Return the unique node id.
static bool hasNoSignedComparisonUses(SDNode *N)
Test whether the given X86ISD::CMP node has any uses which require the SF or OF bits to be accurate...
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition: ISDOpcodes.h:175
EVT getValueType() const
Return the ValueType of the referenced return value.
SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
This class is used to form a handle around another node that is persistent and is updated across invo...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
Dynamic (non-constant condition) vector blend where only the sign bits of the condition elements are ...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:81
#define DEBUG(X)
Definition: Debug.h:118
IRTranslator LLVM IR MI
bool isZeroNode(SDValue Elt)
Returns true if Elt is a constant zero or floating point constant +0.0.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, bool hasSymbolicDisplacement=true)
Returns true of the given offset can be fit into displacement field of the instruction.
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
TRUNCATE - Completely drop the high bits.
Definition: ISDOpcodes.h:450
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
bool isScalarFPTypeInSSEReg(EVT VT) const
Return true if the specified scalar FP type is computed in an SSE register, not on the X87 floating p...
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition: ISDOpcodes.h:349
static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load, SDValue Call, SDValue OrigChain)
Replace the original chain operand of the call with load's chain operand and move load below the call...
Carry-using nodes for multiple precision addition and subtraction.
Definition: ISDOpcodes.h:241
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode...
Special wrapper used under X86-64 PIC mode for RIP relative displacements.
uint64_t getZExtValue() const
BRIND - Indirect branch.
Definition: ISDOpcodes.h:600
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1183
This class is used to represent ISD::LOAD nodes.