LLVM  14.0.0git
TargetLowering.h
Go to the documentation of this file.
1 //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file describes how to lower LLVM code to machine code. This has two
11 /// main components:
12 ///
13 /// 1. Which ValueTypes are natively supported by the target.
14 /// 2. Which operations are supported for supported ValueTypes.
15 /// 3. Cost thresholds for alternative implementations of certain operations.
16 ///
17 /// In addition it has a few other components, like information about FP
18 /// immediates.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #ifndef LLVM_CODEGEN_TARGETLOWERING_H
23 #define LLVM_CODEGEN_TARGETLOWERING_H
24 
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/Support/Alignment.h"
50 #include "llvm/Support/Casting.h"
54 #include <algorithm>
55 #include <cassert>
56 #include <climits>
57 #include <cstdint>
58 #include <iterator>
59 #include <map>
60 #include <string>
61 #include <utility>
62 #include <vector>
63 
64 namespace llvm {
65 
66 class BranchProbability;
67 class CCState;
68 class CCValAssign;
69 class Constant;
70 class FastISel;
71 class FunctionLoweringInfo;
72 class GlobalValue;
73 class GISelKnownBits;
74 class IntrinsicInst;
75 class IRBuilderBase;
76 struct KnownBits;
77 class LegacyDivergenceAnalysis;
78 class LLVMContext;
79 class MachineBasicBlock;
80 class MachineFunction;
81 class MachineInstr;
82 class MachineJumpTableInfo;
83 class MachineLoop;
84 class MachineRegisterInfo;
85 class MCContext;
86 class MCExpr;
87 class Module;
88 class ProfileSummaryInfo;
89 class TargetLibraryInfo;
90 class TargetMachine;
91 class TargetRegisterClass;
92 class TargetRegisterInfo;
93 class TargetTransformInfo;
94 class Value;
95 
96 namespace Sched {
97 
98 enum Preference {
99  None, // No preference
100  Source, // Follow source order.
101  RegPressure, // Scheduling for lowest register pressure.
102  Hybrid, // Scheduling for both latency and register pressure.
103  ILP, // Scheduling for ILP in low register pressure mode.
104  VLIW, // Scheduling for VLIW targets.
105  Fast, // Fast suboptimal list scheduling
106  Linearize // Linearize DAG, no scheduling
107 };
108 
109 } // end namespace Sched
110 
111 // MemOp models a memory operation, either memset or memcpy/memmove.
112 struct MemOp {
113 private:
114  // Shared
115  uint64_t Size;
116  bool DstAlignCanChange; // true if destination alignment can satisfy any
117  // constraint.
118  Align DstAlign; // Specified alignment of the memory operation.
119 
120  bool AllowOverlap;
121  // memset only
122  bool IsMemset; // If setthis memory operation is a memset.
123  bool ZeroMemset; // If set clears out memory with zeros.
124  // memcpy only
125  bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
126  // constant so it does not need to be loaded.
127  Align SrcAlign; // Inferred alignment of the source or default value if the
128  // memory operation does not need to load the value.
129 public:
130  static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
131  Align SrcAlign, bool IsVolatile,
132  bool MemcpyStrSrc = false) {
133  MemOp Op;
134  Op.Size = Size;
135  Op.DstAlignCanChange = DstAlignCanChange;
136  Op.DstAlign = DstAlign;
137  Op.AllowOverlap = !IsVolatile;
138  Op.IsMemset = false;
139  Op.ZeroMemset = false;
140  Op.MemcpyStrSrc = MemcpyStrSrc;
141  Op.SrcAlign = SrcAlign;
142  return Op;
143  }
144 
145  static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
146  bool IsZeroMemset, bool IsVolatile) {
147  MemOp Op;
148  Op.Size = Size;
149  Op.DstAlignCanChange = DstAlignCanChange;
150  Op.DstAlign = DstAlign;
151  Op.AllowOverlap = !IsVolatile;
152  Op.IsMemset = true;
153  Op.ZeroMemset = IsZeroMemset;
154  Op.MemcpyStrSrc = false;
155  return Op;
156  }
157 
158  uint64_t size() const { return Size; }
159  Align getDstAlign() const {
160  assert(!DstAlignCanChange);
161  return DstAlign;
162  }
163  bool isFixedDstAlign() const { return !DstAlignCanChange; }
164  bool allowOverlap() const { return AllowOverlap; }
165  bool isMemset() const { return IsMemset; }
166  bool isMemcpy() const { return !IsMemset; }
168  return isMemcpy() && !DstAlignCanChange;
169  }
170  bool isZeroMemset() const { return isMemset() && ZeroMemset; }
171  bool isMemcpyStrSrc() const {
172  assert(isMemcpy() && "Must be a memcpy");
173  return MemcpyStrSrc;
174  }
175  Align getSrcAlign() const {
176  assert(isMemcpy() && "Must be a memcpy");
177  return SrcAlign;
178  }
179  bool isSrcAligned(Align AlignCheck) const {
180  return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
181  }
182  bool isDstAligned(Align AlignCheck) const {
183  return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
184  }
185  bool isAligned(Align AlignCheck) const {
186  return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
187  }
188 };
189 
190 /// This base class for TargetLowering contains the SelectionDAG-independent
191 /// parts that can be used from the rest of CodeGen.
193 public:
194  /// This enum indicates whether operations are valid for a target, and if not,
195  /// what action should be used to make them valid.
196  enum LegalizeAction : uint8_t {
197  Legal, // The target natively supports this operation.
198  Promote, // This operation should be executed in a larger type.
199  Expand, // Try to expand this to other ops, otherwise use a libcall.
200  LibCall, // Don't try to expand this to other ops, always use a libcall.
201  Custom // Use the LowerOperation hook to implement custom lowering.
202  };
203 
204  /// This enum indicates whether a types are legal for a target, and if not,
205  /// what action should be used to make them valid.
206  enum LegalizeTypeAction : uint8_t {
207  TypeLegal, // The target natively supports this type.
208  TypePromoteInteger, // Replace this integer with a larger one.
209  TypeExpandInteger, // Split this integer into two of half the size.
210  TypeSoftenFloat, // Convert this float to a same size integer type.
211  TypeExpandFloat, // Split this float into two of half the size.
212  TypeScalarizeVector, // Replace this one-element vector with its element.
213  TypeSplitVector, // Split this vector into two of half the size.
214  TypeWidenVector, // This vector should be widened into a larger vector.
215  TypePromoteFloat, // Replace this float with a larger one.
216  TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
217  TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
218  // While it is theoretically possible to
219  // legalize operations on scalable types with a
220  // loop that handles the vscale * #lanes of the
221  // vector, this is non-trivial at SelectionDAG
222  // level and these types are better to be
223  // widened or promoted.
224  };
225 
226  /// LegalizeKind holds the legalization kind that needs to happen to EVT
227  /// in order to type-legalize it.
228  using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
229 
230  /// Enum that describes how the target represents true/false values.
232  UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
233  ZeroOrOneBooleanContent, // All bits zero except for bit 0.
234  ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
235  };
236 
237  /// Enum that describes what type of support for selects the target has.
239  ScalarValSelect, // The target supports scalar selects (ex: cmov).
240  ScalarCondVectorVal, // The target supports selects with a scalar condition
241  // and vector values (ex: cmov).
242  VectorMaskSelect // The target supports vector selects with a vector
243  // mask (ex: x86 blends).
244  };
245 
246  /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
247  /// to, if at all. Exists because different targets have different levels of
248  /// support for these atomic instructions, and also have different options
249  /// w.r.t. what they should expand to.
250  enum class AtomicExpansionKind {
251  None, // Don't expand the instruction.
252  LLSC, // Expand the instruction into loadlinked/storeconditional; used
253  // by ARM/AArch64.
254  LLOnly, // Expand the (load) instruction into just a load-linked, which has
255  // greater atomic guarantees than a normal load.
256  CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
257  MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
258  };
259 
260  /// Enum that specifies when a multiplication should be expanded.
261  enum class MulExpansionKind {
262  Always, // Always expand the instruction.
263  OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
264  // or custom.
265  };
266 
267  /// Enum that specifies when a float negation is beneficial.
268  enum class NegatibleCost {
269  Cheaper = 0, // Negated expression is cheaper.
270  Neutral = 1, // Negated expression has the same cost.
271  Expensive = 2 // Negated expression is more expensive.
272  };
273 
274  class ArgListEntry {
275  public:
276  Value *Val = nullptr;
278  Type *Ty = nullptr;
279  bool IsSExt : 1;
280  bool IsZExt : 1;
281  bool IsInReg : 1;
282  bool IsSRet : 1;
283  bool IsNest : 1;
284  bool IsByVal : 1;
285  bool IsByRef : 1;
286  bool IsInAlloca : 1;
287  bool IsPreallocated : 1;
288  bool IsReturned : 1;
289  bool IsSwiftSelf : 1;
290  bool IsSwiftAsync : 1;
291  bool IsSwiftError : 1;
292  bool IsCFGuardTarget : 1;
294  Type *IndirectType = nullptr;
295 
301 
302  void setAttributes(const CallBase *Call, unsigned ArgIdx);
303  };
304  using ArgListTy = std::vector<ArgListEntry>;
305 
306  virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
307  ArgListTy &Args) const {};
308 
310  switch (Content) {
312  // Extend by adding rubbish bits.
313  return ISD::ANY_EXTEND;
315  // Extend by adding zero bits.
316  return ISD::ZERO_EXTEND;
318  // Extend by copying the sign bit.
319  return ISD::SIGN_EXTEND;
320  }
321  llvm_unreachable("Invalid content kind");
322  }
323 
324  explicit TargetLoweringBase(const TargetMachine &TM);
325  TargetLoweringBase(const TargetLoweringBase &) = delete;
327  virtual ~TargetLoweringBase() = default;
328 
329  /// Return true if the target support strict float operation
330  bool isStrictFPEnabled() const {
331  return IsStrictFPEnabled;
332  }
333 
334 protected:
335  /// Initialize all of the actions to default values.
336  void initActions();
337 
338 public:
339  const TargetMachine &getTargetMachine() const { return TM; }
340 
341  virtual bool useSoftFloat() const { return false; }
342 
343  /// Return the pointer type for the given address space, defaults to
344  /// the pointer type from the data layout.
345  /// FIXME: The default needs to be removed once all the code is updated.
346  virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
347  return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
348  }
349 
350  /// Return the in-memory pointer type for the given address space, defaults to
351  /// the pointer type from the data layout. FIXME: The default needs to be
352  /// removed once all the code is updated.
353  virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
354  return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
355  }
356 
357  /// Return the type for frame index, which is determined by
358  /// the alloca address space specified through the data layout.
360  return getPointerTy(DL, DL.getAllocaAddrSpace());
361  }
362 
363  /// Return the type for code pointers, which is determined by the program
364  /// address space specified through the data layout.
366  return getPointerTy(DL, DL.getProgramAddressSpace());
367  }
368 
369  /// Return the type for operands of fence.
370  /// TODO: Let fence operands be of i32 type and remove this.
371  virtual MVT getFenceOperandTy(const DataLayout &DL) const {
372  return getPointerTy(DL);
373  }
374 
375  /// EVT is not used in-tree, but is used by out-of-tree target.
376  /// A documentation for this function would be nice...
377  virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
378 
379  EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
380  bool LegalTypes = true) const;
381 
382  /// Return the preferred type to use for a shift opcode, given the shifted
383  /// amount type is \p ShiftValueTy.
385  virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
386  return ShiftValueTy;
387  }
388 
389  /// Returns the type to be used for the index operand of:
390  /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
391  /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
392  virtual MVT getVectorIdxTy(const DataLayout &DL) const {
393  return getPointerTy(DL);
394  }
395 
396  /// Returns the type to be used for the EVL/AVL operand of VP nodes:
397  /// ISD::VP_ADD, ISD::VP_SUB, etc. It must be a legal scalar integer type,
398  /// and must be at least as large as i32. The EVL is implicitly zero-extended
399  /// to any larger type.
400  virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
401 
402  /// This callback is used to inspect load/store instructions and add
403  /// target-specific MachineMemOperand flags to them. The default
404  /// implementation does nothing.
407  }
408 
410  const DataLayout &DL) const;
412  const DataLayout &DL) const;
414  const DataLayout &DL) const;
415 
416  virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
417  return true;
418  }
419 
420  /// Return true if it is profitable to convert a select of FP constants into
421  /// a constant pool load whose address depends on the select condition. The
422  /// parameter may be used to differentiate a select with FP compare from
423  /// integer compare.
424  virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
425  return true;
426  }
427 
428  /// Return true if multiple condition registers are available.
430  return HasMultipleConditionRegisters;
431  }
432 
433  /// Return true if the target has BitExtract instructions.
434  bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
435 
436  /// Return the preferred vector type legalization action.
439  // The default action for one element vectors is to scalarize
440  if (VT.getVectorElementCount().isScalar())
441  return TypeScalarizeVector;
442  // The default action for an odd-width vector is to widen.
443  if (!VT.isPow2VectorType())
444  return TypeWidenVector;
445  // The default action for other vectors is to promote
446  return TypePromoteInteger;
447  }
448 
449  // Return true if the half type should be passed around as i16, but promoted
450  // to float around arithmetic. The default behavior is to pass around as
451  // float and convert around loads/stores/bitcasts and other places where
452  // the size matters.
453  virtual bool softPromoteHalfType() const { return false; }
454 
455  // There are two general methods for expanding a BUILD_VECTOR node:
456  // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
457  // them together.
458  // 2. Build the vector on the stack and then load it.
459  // If this function returns true, then method (1) will be used, subject to
460  // the constraint that all of the necessary shuffles are legal (as determined
461  // by isShuffleMaskLegal). If this function returns false, then method (2) is
462  // always used. The vector type, and the number of defined values, are
463  // provided.
464  virtual bool
466  unsigned DefinedValues) const {
467  return DefinedValues < 3;
468  }
469 
470  /// Return true if integer divide is usually cheaper than a sequence of
471  /// several shifts, adds, and multiplies for this target.
472  /// The definition of "cheaper" may depend on whether we're optimizing
473  /// for speed or for size.
474  virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
475 
476  /// Return true if the target can handle a standalone remainder operation.
477  virtual bool hasStandaloneRem(EVT VT) const {
478  return true;
479  }
480 
481  /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
482  virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
483  // Default behavior is to replace SQRT(X) with X*RSQRT(X).
484  return false;
485  }
486 
487  /// Reciprocal estimate status values used by the functions below.
488  enum ReciprocalEstimate : int {
490  Disabled = 0,
492  };
493 
494  /// Return a ReciprocalEstimate enum value for a square root of the given type
495  /// based on the function's attributes. If the operation is not overridden by
496  /// the function's attributes, "Unspecified" is returned and target defaults
497  /// are expected to be used for instruction selection.
499 
500  /// Return a ReciprocalEstimate enum value for a division of the given type
501  /// based on the function's attributes. If the operation is not overridden by
502  /// the function's attributes, "Unspecified" is returned and target defaults
503  /// are expected to be used for instruction selection.
505 
506  /// Return the refinement step count for a square root of the given type based
507  /// on the function's attributes. If the operation is not overridden by
508  /// the function's attributes, "Unspecified" is returned and target defaults
509  /// are expected to be used for instruction selection.
510  int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
511 
512  /// Return the refinement step count for a division of the given type based
513  /// on the function's attributes. If the operation is not overridden by
514  /// the function's attributes, "Unspecified" is returned and target defaults
515  /// are expected to be used for instruction selection.
516  int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
517 
518  /// Returns true if target has indicated at least one type should be bypassed.
519  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
520 
521  /// Returns map of slow types for division or remainder with corresponding
522  /// fast types
524  return BypassSlowDivWidths;
525  }
526 
527  /// Return true if Flow Control is an expensive operation that should be
528  /// avoided.
529  bool isJumpExpensive() const { return JumpIsExpensive; }
530 
531  /// Return true if selects are only cheaper than branches if the branch is
532  /// unlikely to be predicted right.
535  }
536 
537  virtual bool fallBackToDAGISel(const Instruction &Inst) const {
538  return false;
539  }
540 
541  /// Return true if the following transform is beneficial:
542  /// fold (conv (load x)) -> (load (conv*)x)
543  /// On architectures that don't natively support some vector loads
544  /// efficiently, casting the load to a smaller vector of larger types and
545  /// loading is more efficient, however, this can be undone by optimizations in
546  /// dag combiner.
547  virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
548  const SelectionDAG &DAG,
549  const MachineMemOperand &MMO) const {
550  // Don't do if we could do an indexed load on the original type, but not on
551  // the new one.
552  if (!LoadVT.isSimple() || !BitcastVT.isSimple())
553  return true;
554 
555  MVT LoadMVT = LoadVT.getSimpleVT();
556 
557  // Don't bother doing this if it's just going to be promoted again later, as
558  // doing so might interfere with other combines.
559  if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
560  getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
561  return false;
562 
563  bool Fast = false;
564  return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
565  MMO, &Fast) && Fast;
566  }
567 
568  /// Return true if the following transform is beneficial:
569  /// (store (y (conv x)), y*)) -> (store x, (x*))
570  virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
571  const SelectionDAG &DAG,
572  const MachineMemOperand &MMO) const {
573  // Default to the same logic as loads.
574  return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
575  }
576 
577  /// Return true if it is expected to be cheaper to do a store of a non-zero
578  /// vector constant with the given size and type for the address space than to
579  /// store the individual scalar element constants.
580  virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
581  unsigned NumElem,
582  unsigned AddrSpace) const {
583  return false;
584  }
585 
586  /// Allow store merging for the specified type after legalization in addition
587  /// to before legalization. This may transform stores that do not exist
588  /// earlier (for example, stores created from intrinsics).
589  virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
590  return true;
591  }
592 
593  /// Returns if it's reasonable to merge stores to MemVT size.
594  virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
595  const MachineFunction &MF) const {
596  return true;
597  }
598 
599  /// Return true if it is cheap to speculate a call to intrinsic cttz.
600  virtual bool isCheapToSpeculateCttz() const {
601  return false;
602  }
603 
604  /// Return true if it is cheap to speculate a call to intrinsic ctlz.
605  virtual bool isCheapToSpeculateCtlz() const {
606  return false;
607  }
608 
609  /// Return true if ctlz instruction is fast.
610  virtual bool isCtlzFast() const {
611  return false;
612  }
613 
614  /// Return the maximum number of "x & (x - 1)" operations that can be done
615  /// instead of deferring to a custom CTPOP.
616  virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
617  return 1;
618  }
619 
620  /// Return true if instruction generated for equality comparison is folded
621  /// with instruction generated for signed comparison.
622  virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
623 
624  /// Return true if the heuristic to prefer icmp eq zero should be used in code
625  /// gen prepare.
626  virtual bool preferZeroCompareBranch() const { return false; }
627 
628  /// Return true if it is safe to transform an integer-domain bitwise operation
629  /// into the equivalent floating-point operation. This should be set to true
630  /// if the target has IEEE-754-compliant fabs/fneg operations for the input
631  /// type.
632  virtual bool hasBitPreservingFPLogic(EVT VT) const {
633  return false;
634  }
635 
636  /// Return true if it is cheaper to split the store of a merged int val
637  /// from a pair of smaller values into multiple stores.
638  virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
639  return false;
640  }
641 
642  /// Return if the target supports combining a
643  /// chain like:
644  /// \code
645  /// %andResult = and %val1, #mask
646  /// %icmpResult = icmp %andResult, 0
647  /// \endcode
648  /// into a single machine instruction of a form like:
649  /// \code
650  /// cc = test %register, #mask
651  /// \endcode
652  virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
653  return false;
654  }
655 
656  /// Use bitwise logic to make pairs of compares more efficient. For example:
657  /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
658  /// This should be true when it takes more than one instruction to lower
659  /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
660  /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
661  virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
662  return false;
663  }
664 
665  /// Return the preferred operand type if the target has a quick way to compare
666  /// integer values of the given size. Assume that any legal integer type can
667  /// be compared efficiently. Targets may override this to allow illegal wide
668  /// types to return a vector type if there is support to compare that type.
669  virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
670  MVT VT = MVT::getIntegerVT(NumBits);
672  }
673 
674  /// Return true if the target should transform:
675  /// (X & Y) == Y ---> (~X & Y) == 0
676  /// (X & Y) != Y ---> (~X & Y) != 0
677  ///
678  /// This may be profitable if the target has a bitwise and-not operation that
679  /// sets comparison flags. A target may want to limit the transformation based
680  /// on the type of Y or if Y is a constant.
681  ///
682  /// Note that the transform will not occur if Y is known to be a power-of-2
683  /// because a mask and compare of a single bit can be handled by inverting the
684  /// predicate, for example:
685  /// (X & 8) == 8 ---> (X & 8) != 0
686  virtual bool hasAndNotCompare(SDValue Y) const {
687  return false;
688  }
689 
690  /// Return true if the target has a bitwise and-not operation:
691  /// X = ~A & B
692  /// This can be used to simplify select or other instructions.
693  virtual bool hasAndNot(SDValue X) const {
694  // If the target has the more complex version of this operation, assume that
695  // it has this operation too.
696  return hasAndNotCompare(X);
697  }
698 
699  /// Return true if the target has a bit-test instruction:
700  /// (X & (1 << Y)) ==/!= 0
701  /// This knowledge can be used to prevent breaking the pattern,
702  /// or creating it if it could be recognized.
703  virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
704 
705  /// There are two ways to clear extreme bits (either low or high):
706  /// Mask: x & (-1 << y) (the instcombine canonical form)
707  /// Shifts: x >> y << y
708  /// Return true if the variant with 2 variable shifts is preferred.
709  /// Return false if there is no preference.
711  // By default, let's assume that no one prefers shifts.
712  return false;
713  }
714 
715  /// Return true if it is profitable to fold a pair of shifts into a mask.
716  /// This is usually true on most targets. But some targets, like Thumb1,
717  /// have immediate shift instructions, but no immediate "and" instruction;
718  /// this makes the fold unprofitable.
720  CombineLevel Level) const {
721  return true;
722  }
723 
724  /// Should we tranform the IR-optimal check for whether given truncation
725  /// down into KeptBits would be truncating or not:
726  /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
727  /// Into it's more traditional form:
728  /// ((%x << C) a>> C) dstcond %x
729  /// Return true if we should transform.
730  /// Return false if there is no preference.
732  unsigned KeptBits) const {
733  // By default, let's assume that no one prefers shifts.
734  return false;
735  }
736 
737  /// Given the pattern
738  /// (X & (C l>>/<< Y)) ==/!= 0
739  /// return true if it should be transformed into:
740  /// ((X <</l>> Y) & C) ==/!= 0
741  /// WARNING: if 'X' is a constant, the fold may deadlock!
742  /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
743  /// here because it can end up being not linked in.
746  unsigned OldShiftOpcode, unsigned NewShiftOpcode,
747  SelectionDAG &DAG) const {
748  if (hasBitTest(X, Y)) {
749  // One interesting pattern that we'd want to form is 'bit test':
750  // ((1 << Y) & C) ==/!= 0
751  // But we also need to be careful not to try to reverse that fold.
752 
753  // Is this '1 << Y' ?
754  if (OldShiftOpcode == ISD::SHL && CC->isOne())
755  return false; // Keep the 'bit test' pattern.
756 
757  // Will it be '1 << Y' after the transform ?
758  if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
759  return true; // Do form the 'bit test' pattern.
760  }
761 
762  // If 'X' is a constant, and we transform, then we will immediately
763  // try to undo the fold, thus causing endless combine loop.
764  // So by default, let's assume everyone prefers the fold
765  // iff 'X' is not a constant.
766  return !XC;
767  }
768 
769  /// These two forms are equivalent:
770  /// sub %y, (xor %x, -1)
771  /// add (add %x, 1), %y
772  /// The variant with two add's is IR-canonical.
773  /// Some targets may prefer one to the other.
774  virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
775  // By default, let's assume that everyone prefers the form with two add's.
776  return true;
777  }
778 
779  /// Return true if the target wants to use the optimization that
780  /// turns ext(promotableInst1(...(promotableInstN(load)))) into
781  /// promotedInst1(...(promotedInstN(ext(load)))).
783 
784  /// Return true if the target can combine store(extractelement VectorTy,
785  /// Idx).
786  /// \p Cost[out] gives the cost of that transformation when this is true.
787  virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
788  unsigned &Cost) const {
789  return false;
790  }
791 
792  /// Return true if inserting a scalar into a variable element of an undef
793  /// vector is more efficiently handled by splatting the scalar instead.
794  virtual bool shouldSplatInsEltVarIndex(EVT) const {
795  return false;
796  }
797 
798  /// Return true if target always benefits from combining into FMA for a
799  /// given value type. This must typically return false on targets where FMA
800  /// takes more cycles to execute than FADD.
801  virtual bool enableAggressiveFMAFusion(EVT VT) const {
802  return false;
803  }
804 
805  /// Return the ValueType of the result of SETCC operations.
807  EVT VT) const;
808 
809  /// Return the ValueType for comparison libcalls. Comparions libcalls include
810  /// floating point comparion calls, and Ordered/Unordered check calls on
811  /// floating point numbers.
812  virtual
814 
815  /// For targets without i1 registers, this gives the nature of the high-bits
816  /// of boolean values held in types wider than i1.
817  ///
818  /// "Boolean values" are special true/false values produced by nodes like
819  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
820  /// Not to be confused with general values promoted from i1. Some cpus
821  /// distinguish between vectors of boolean and scalars; the isVec parameter
822  /// selects between the two kinds. For example on X86 a scalar boolean should
823  /// be zero extended from i1, while the elements of a vector of booleans
824  /// should be sign extended from i1.
825  ///
826  /// Some cpus also treat floating point types the same way as they treat
827  /// vectors instead of the way they treat scalars.
828  BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
829  if (isVec)
830  return BooleanVectorContents;
831  return isFloat ? BooleanFloatContents : BooleanContents;
832  }
833 
835  return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
836  }
837 
838  /// Return target scheduling preference.
840  return SchedPreferenceInfo;
841  }
842 
843  /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
844  /// for different nodes. This function returns the preference (or none) for
845  /// the given node.
847  return Sched::None;
848  }
849 
850  /// Return the register class that should be used for the specified value
851  /// type.
852  virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
853  (void)isDivergent;
854  const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
855  assert(RC && "This value type is not natively supported!");
856  return RC;
857  }
858 
859  /// Allows target to decide about the register class of the
860  /// specific value that is live outside the defining block.
861  /// Returns true if the value needs uniform register class.
863  const Value *) const {
864  return false;
865  }
866 
867  /// Return the 'representative' register class for the specified value
868  /// type.
869  ///
870  /// The 'representative' register class is the largest legal super-reg
871  /// register class for the register class of the value type. For example, on
872  /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
873  /// register class is GR64 on x86_64.
874  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
875  const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
876  return RC;
877  }
878 
879  /// Return the cost of the 'representative' register class for the specified
880  /// value type.
881  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
882  return RepRegClassCostForVT[VT.SimpleTy];
883  }
884 
885  /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
886  /// instructions, and false if a library call is preferred (e.g for code-size
887  /// reasons).
888  virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
889  return true;
890  }
891 
892  /// Return true if the target has native support for the specified value type.
893  /// This means that it has a register that directly holds it without
894  /// promotions or expansions.
895  bool isTypeLegal(EVT VT) const {
896  assert(!VT.isSimple() ||
897  (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
898  return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
899  }
900 
902  /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
903  /// that indicates how instruction selection should deal with the type.
904  LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
905 
906  public:
908  std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
909  TypeLegal);
910  }
911 
913  return ValueTypeActions[VT.SimpleTy];
914  }
915 
917  ValueTypeActions[VT.SimpleTy] = Action;
918  }
919  };
920 
922  return ValueTypeActions;
923  }
924 
925  /// Return how we should legalize values of this type, either it is already
926  /// legal (return 'Legal') or we need to promote it to a larger type (return
927  /// 'Promote'), or we need to expand it into multiple registers of smaller
928  /// integer type (return 'Expand'). 'Custom' is not an option.
930  return getTypeConversion(Context, VT).first;
931  }
933  return ValueTypeActions.getTypeAction(VT);
934  }
935 
936  /// For types supported by the target, this is an identity function. For
937  /// types that must be promoted to larger types, this returns the larger type
938  /// to promote to. For integer types that are larger than the largest integer
939  /// register, this contains one step in the expansion to get to the smaller
940  /// register. For illegal floating point types, this returns the integer type
941  /// to transform to.
943  return getTypeConversion(Context, VT).second;
944  }
945 
946  /// For types supported by the target, this is an identity function. For
947  /// types that must be expanded (i.e. integer types that are larger than the
948  /// largest integer register or illegal floating point types), this returns
949  /// the largest legal type it will be expanded to.
951  assert(!VT.isVector());
952  while (true) {
953  switch (getTypeAction(Context, VT)) {
954  case TypeLegal:
955  return VT;
956  case TypeExpandInteger:
957  VT = getTypeToTransformTo(Context, VT);
958  break;
959  default:
960  llvm_unreachable("Type is not legal nor is it to be expanded!");
961  }
962  }
963  }
964 
965  /// Vector types are broken down into some number of legal first class types.
966  /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
967  /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
968  /// turns into 4 EVT::i32 values with both PPC and X86.
969  ///
970  /// This method returns the number of registers needed, and the VT for each
971  /// register. It also returns the VT and quantity of the intermediate values
972  /// before they are promoted/expanded.
974  EVT &IntermediateVT,
975  unsigned &NumIntermediates,
976  MVT &RegisterVT) const;
977 
978  /// Certain targets such as MIPS require that some types such as vectors are
979  /// always broken down into scalars in some contexts. This occurs even if the
980  /// vector type is legal.
982  LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
983  unsigned &NumIntermediates, MVT &RegisterVT) const {
984  return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
985  RegisterVT);
986  }
987 
988  struct IntrinsicInfo {
989  unsigned opc = 0; // target opcode
990  EVT memVT; // memory VT
991 
992  // value representing memory location
994 
995  int offset = 0; // offset off of ptrVal
996  uint64_t size = 0; // the size of the memory location
997  // (taken from memVT if zero)
998  MaybeAlign align = Align(1); // alignment
999 
1001  IntrinsicInfo() = default;
1002  };
1003 
1004  /// Given an intrinsic, checks if on the target the intrinsic will need to map
1005  /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
1006  /// true and store the intrinsic information into the IntrinsicInfo that was
1007  /// passed to the function.
1008  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
1009  MachineFunction &,
1010  unsigned /*Intrinsic*/) const {
1011  return false;
1012  }
1013 
1014  /// Returns true if the target can instruction select the specified FP
1015  /// immediate natively. If false, the legalizer will materialize the FP
1016  /// immediate as a load from a constant pool.
1017  virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1018  bool ForCodeSize = false) const {
1019  return false;
1020  }
1021 
1022  /// Targets can use this to indicate that they only support *some*
1023  /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1024  /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1025  /// legal.
1026  virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1027  return true;
1028  }
1029 
1030  /// Returns true if the operation can trap for the value type.
1031  ///
1032  /// VT must be a legal type. By default, we optimistically assume most
1033  /// operations don't trap except for integer divide and remainder.
1034  virtual bool canOpTrap(unsigned Op, EVT VT) const;
1035 
1036  /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1037  /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1038  /// constant pool entry.
1039  virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
1040  EVT /*VT*/) const {
1041  return false;
1042  }
1043 
1044  /// Return how this operation should be treated: either it is legal, needs to
1045  /// be promoted to a larger size, needs to be expanded to some other code
1046  /// sequence, or the target has a custom expander for it.
1047  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
1048  if (VT.isExtended()) return Expand;
1049  // If a target-specific SDNode requires legalization, require the target
1050  // to provide custom legalization for it.
1051  if (Op >= array_lengthof(OpActions[0])) return Custom;
1052  return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1053  }
1054 
1055  /// Custom method defined by each target to indicate if an operation which
1056  /// may require a scale is supported natively by the target.
1057  /// If not, the operation is illegal.
1058  virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1059  unsigned Scale) const {
1060  return false;
1061  }
1062 
1063  /// Some fixed point operations may be natively supported by the target but
1064  /// only for specific scales. This method allows for checking
1065  /// if the width is supported by the target for a given operation that may
1066  /// depend on scale.
1068  unsigned Scale) const {
1069  auto Action = getOperationAction(Op, VT);
1070  if (Action != Legal)
1071  return Action;
1072 
1073  // This operation is supported in this type but may only work on specific
1074  // scales.
1075  bool Supported;
1076  switch (Op) {
1077  default:
1078  llvm_unreachable("Unexpected fixed point operation.");
1079  case ISD::SMULFIX:
1080  case ISD::SMULFIXSAT:
1081  case ISD::UMULFIX:
1082  case ISD::UMULFIXSAT:
1083  case ISD::SDIVFIX:
1084  case ISD::SDIVFIXSAT:
1085  case ISD::UDIVFIX:
1086  case ISD::UDIVFIXSAT:
1087  Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1088  break;
1089  }
1090 
1091  return Supported ? Action : Expand;
1092  }
1093 
1094  // If Op is a strict floating-point operation, return the result
1095  // of getOperationAction for the equivalent non-strict operation.
1097  unsigned EqOpc;
1098  switch (Op) {
1099  default: llvm_unreachable("Unexpected FP pseudo-opcode");
1100 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1101  case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1102 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1103  case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1104 #include "llvm/IR/ConstrainedOps.def"
1105  }
1106 
1107  return getOperationAction(EqOpc, VT);
1108  }
1109 
1110  /// Return true if the specified operation is legal on this target or can be
1111  /// made legal with custom lowering. This is used to help guide high-level
1112  /// lowering decisions. LegalOnly is an optional convenience for code paths
1113  /// traversed pre and post legalisation.
1114  bool isOperationLegalOrCustom(unsigned Op, EVT VT,
1115  bool LegalOnly = false) const {
1116  if (LegalOnly)
1117  return isOperationLegal(Op, VT);
1118 
1119  return (VT == MVT::Other || isTypeLegal(VT)) &&
1120  (getOperationAction(Op, VT) == Legal ||
1121  getOperationAction(Op, VT) == Custom);
1122  }
1123 
1124  /// Return true if the specified operation is legal on this target or can be
1125  /// made legal using promotion. This is used to help guide high-level lowering
1126  /// decisions. LegalOnly is an optional convenience for code paths traversed
1127  /// pre and post legalisation.
1128  bool isOperationLegalOrPromote(unsigned Op, EVT VT,
1129  bool LegalOnly = false) const {
1130  if (LegalOnly)
1131  return isOperationLegal(Op, VT);
1132 
1133  return (VT == MVT::Other || isTypeLegal(VT)) &&
1134  (getOperationAction(Op, VT) == Legal ||
1135  getOperationAction(Op, VT) == Promote);
1136  }
1137 
1138  /// Return true if the specified operation is legal on this target or can be
1139  /// made legal with custom lowering or using promotion. This is used to help
1140  /// guide high-level lowering decisions. LegalOnly is an optional convenience
1141  /// for code paths traversed pre and post legalisation.
1143  bool LegalOnly = false) const {
1144  if (LegalOnly)
1145  return isOperationLegal(Op, VT);
1146 
1147  return (VT == MVT::Other || isTypeLegal(VT)) &&
1148  (getOperationAction(Op, VT) == Legal ||
1149  getOperationAction(Op, VT) == Custom ||
1150  getOperationAction(Op, VT) == Promote);
1151  }
1152 
1153  /// Return true if the operation uses custom lowering, regardless of whether
1154  /// the type is legal or not.
1155  bool isOperationCustom(unsigned Op, EVT VT) const {
1156  return getOperationAction(Op, VT) == Custom;
1157  }
1158 
1159  /// Return true if lowering to a jump table is allowed.
1160  virtual bool areJTsAllowed(const Function *Fn) const {
1161  if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1162  return false;
1163 
1166  }
1167 
1168  /// Check whether the range [Low,High] fits in a machine word.
1169  bool rangeFitsInWord(const APInt &Low, const APInt &High,
1170  const DataLayout &DL) const {
1171  // FIXME: Using the pointer type doesn't seem ideal.
1172  uint64_t BW = DL.getIndexSizeInBits(0u);
1173  uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1174  return Range <= BW;
1175  }
1176 
1177  /// Return true if lowering to a jump table is suitable for a set of case
1178  /// clusters which may contain \p NumCases cases, \p Range range of values.
1179  virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1180  uint64_t Range, ProfileSummaryInfo *PSI,
1181  BlockFrequencyInfo *BFI) const;
1182 
1183  /// Return true if lowering to a bit test is suitable for a set of case
1184  /// clusters which contains \p NumDests unique destinations, \p Low and
1185  /// \p High as its lowest and highest case values, and expects \p NumCmps
1186  /// case value comparisons. Check if the number of destinations, comparison
1187  /// metric, and range are all suitable.
1188  bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1189  const APInt &Low, const APInt &High,
1190  const DataLayout &DL) const {
1191  // FIXME: I don't think NumCmps is the correct metric: a single case and a
1192  // range of cases both require only one branch to lower. Just looking at the
1193  // number of clusters and destinations should be enough to decide whether to
1194  // build bit tests.
1195 
1196  // To lower a range with bit tests, the range must fit the bitwidth of a
1197  // machine word.
1198  if (!rangeFitsInWord(Low, High, DL))
1199  return false;
1200 
1201  // Decide whether it's profitable to lower this range with bit tests. Each
1202  // destination requires a bit test and branch, and there is an overall range
1203  // check branch. For a small number of clusters, separate comparisons might
1204  // be cheaper, and for many destinations, splitting the range might be
1205  // better.
1206  return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1207  (NumDests == 3 && NumCmps >= 6);
1208  }
1209 
1210  /// Return true if the specified operation is illegal on this target or
1211  /// unlikely to be made legal with custom lowering. This is used to help guide
1212  /// high-level lowering decisions.
1213  bool isOperationExpand(unsigned Op, EVT VT) const {
1214  return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1215  }
1216 
1217  /// Return true if the specified operation is legal on this target.
1218  bool isOperationLegal(unsigned Op, EVT VT) const {
1219  return (VT == MVT::Other || isTypeLegal(VT)) &&
1220  getOperationAction(Op, VT) == Legal;
1221  }
1222 
1223  /// Return how this load with extension should be treated: either it is legal,
1224  /// needs to be promoted to a larger size, needs to be expanded to some other
1225  /// code sequence, or the target has a custom expander for it.
1226  LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1227  EVT MemVT) const {
1228  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1229  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1230  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1231  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::VALUETYPE_SIZE &&
1232  MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
1233  unsigned Shift = 4 * ExtType;
1234  return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1235  }
1236 
1237  /// Return true if the specified load with extension is legal on this target.
1238  bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1239  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1240  }
1241 
1242  /// Return true if the specified load with extension is legal or custom
1243  /// on this target.
1244  bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1245  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1246  getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1247  }
1248 
1249  /// Return how this store with truncation should be treated: either it is
1250  /// legal, needs to be promoted to a larger size, needs to be expanded to some
1251  /// other code sequence, or the target has a custom expander for it.
1253  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1254  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1255  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1256  assert(ValI < MVT::VALUETYPE_SIZE && MemI < MVT::VALUETYPE_SIZE &&
1257  "Table isn't big enough!");
1258  return TruncStoreActions[ValI][MemI];
1259  }
1260 
1261  /// Return true if the specified store with truncation is legal on this
1262  /// target.
1263  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1264  return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1265  }
1266 
1267  /// Return true if the specified store with truncation has solution on this
1268  /// target.
1269  bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1270  return isTypeLegal(ValVT) &&
1271  (getTruncStoreAction(ValVT, MemVT) == Legal ||
1272  getTruncStoreAction(ValVT, MemVT) == Custom);
1273  }
1274 
1275  virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT,
1276  bool LegalOnly) const {
1277  if (LegalOnly)
1278  return isTruncStoreLegal(ValVT, MemVT);
1279 
1280  return isTruncStoreLegalOrCustom(ValVT, MemVT);
1281  }
1282 
1283  /// Return how the indexed load should be treated: either it is legal, needs
1284  /// to be promoted to a larger size, needs to be expanded to some other code
1285  /// sequence, or the target has a custom expander for it.
1286  LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1287  return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1288  }
1289 
1290  /// Return true if the specified indexed load is legal on this target.
1291  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1292  return VT.isSimple() &&
1293  (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1294  getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1295  }
1296 
1297  /// Return how the indexed store should be treated: either it is legal, needs
1298  /// to be promoted to a larger size, needs to be expanded to some other code
1299  /// sequence, or the target has a custom expander for it.
1300  LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1301  return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1302  }
1303 
1304  /// Return true if the specified indexed load is legal on this target.
1305  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1306  return VT.isSimple() &&
1307  (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1308  getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1309  }
1310 
1311  /// Return how the indexed load should be treated: either it is legal, needs
1312  /// to be promoted to a larger size, needs to be expanded to some other code
1313  /// sequence, or the target has a custom expander for it.
1314  LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1315  return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1316  }
1317 
1318  /// Return true if the specified indexed load is legal on this target.
1319  bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1320  return VT.isSimple() &&
1321  (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1322  getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1323  }
1324 
1325  /// Return how the indexed store should be treated: either it is legal, needs
1326  /// to be promoted to a larger size, needs to be expanded to some other code
1327  /// sequence, or the target has a custom expander for it.
1328  LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1329  return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1330  }
1331 
1332  /// Return true if the specified indexed load is legal on this target.
1333  bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1334  return VT.isSimple() &&
1335  (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1336  getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1337  }
1338 
1339  /// Returns true if the index type for a masked gather/scatter requires
1340  /// extending
1341  virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1342 
1343  // Returns true if VT is a legal index type for masked gathers/scatters
1344  // on this target
1345  virtual bool shouldRemoveExtendFromGSIndex(EVT VT) const { return false; }
1346 
1347  /// Return how the condition code should be treated: either it is legal, needs
1348  /// to be expanded to some other code sequence, or the target has a custom
1349  /// expander for it.
1352  assert((unsigned)CC < array_lengthof(CondCodeActions) &&
1353  ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
1354  "Table isn't big enough!");
1355  // See setCondCodeAction for how this is encoded.
1356  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1357  uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1358  LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1359  assert(Action != Promote && "Can't promote condition code!");
1360  return Action;
1361  }
1362 
1363  /// Return true if the specified condition code is legal on this target.
1364  bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1365  return getCondCodeAction(CC, VT) == Legal;
1366  }
1367 
1368  /// Return true if the specified condition code is legal or custom on this
1369  /// target.
1371  return getCondCodeAction(CC, VT) == Legal ||
1372  getCondCodeAction(CC, VT) == Custom;
1373  }
1374 
1375  /// If the action for this operation is to promote, this method returns the
1376  /// ValueType to promote to.
1377  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1378  assert(getOperationAction(Op, VT) == Promote &&
1379  "This operation isn't promoted!");
1380 
1381  // See if this has an explicit type specified.
1382  std::map<std::pair<unsigned, MVT::SimpleValueType>,
1384  PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1385  if (PTTI != PromoteToType.end()) return PTTI->second;
1386 
1387  assert((VT.isInteger() || VT.isFloatingPoint()) &&
1388  "Cannot autopromote this type, add it with AddPromotedToType.");
1389 
1390  MVT NVT = VT;
1391  do {
1392  NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1393  assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1394  "Didn't find type to promote to!");
1395  } while (!isTypeLegal(NVT) ||
1396  getOperationAction(Op, NVT) == Promote);
1397  return NVT;
1398  }
1399 
1401  bool AllowUnknown = false) const {
1402  return getValueType(DL, Ty, AllowUnknown);
1403  }
1404 
1405  /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1406  /// operations except for the pointer size. If AllowUnknown is true, this
1407  /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1408  /// otherwise it will assert.
1410  bool AllowUnknown = false) const {
1411  // Lower scalar pointers to native pointer types.
1412  if (auto *PTy = dyn_cast<PointerType>(Ty))
1413  return getPointerTy(DL, PTy->getAddressSpace());
1414 
1415  if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1416  Type *EltTy = VTy->getElementType();
1417  // Lower vectors of pointers to native pointer types.
1418  if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1419  EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1420  EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1421  }
1422  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1423  VTy->getElementCount());
1424  }
1425 
1426  return EVT::getEVT(Ty, AllowUnknown);
1427  }
1428 
1430  bool AllowUnknown = false) const {
1431  // Lower scalar pointers to native pointer types.
1432  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1433  return getPointerMemTy(DL, PTy->getAddressSpace());
1434  else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1435  Type *Elm = VTy->getElementType();
1436  if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1437  EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
1438  Elm = PointerTy.getTypeForEVT(Ty->getContext());
1439  }
1440  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1441  VTy->getElementCount());
1442  }
1443 
1444  return getValueType(DL, Ty, AllowUnknown);
1445  }
1446 
1447 
1448  /// Return the MVT corresponding to this LLVM type. See getValueType.
1450  bool AllowUnknown = false) const {
1451  return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1452  }
1453 
1454  /// Return the desired alignment for ByVal or InAlloca aggregate function
1455  /// arguments in the caller parameter area. This is the actual alignment, not
1456  /// its logarithm.
1457  virtual uint64_t getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1458 
1459  /// Return the type of registers that this ValueType will eventually require.
1461  assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1462  return RegisterTypeForVT[VT.SimpleTy];
1463  }
1464 
1465  /// Return the type of registers that this ValueType will eventually require.
1467  if (VT.isSimple()) {
1468  assert((unsigned)VT.getSimpleVT().SimpleTy <
1469  array_lengthof(RegisterTypeForVT));
1470  return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1471  }
1472  if (VT.isVector()) {
1473  EVT VT1;
1474  MVT RegisterVT;
1475  unsigned NumIntermediates;
1476  (void)getVectorTypeBreakdown(Context, VT, VT1,
1477  NumIntermediates, RegisterVT);
1478  return RegisterVT;
1479  }
1480  if (VT.isInteger()) {
1482  }
1483  llvm_unreachable("Unsupported extended type!");
1484  }
1485 
1486  /// Return the number of registers that this ValueType will eventually
1487  /// require.
1488  ///
1489  /// This is one for any types promoted to live in larger registers, but may be
1490  /// more than one for types (like i64) that are split into pieces. For types
1491  /// like i140, which are first promoted then expanded, it is the number of
1492  /// registers needed to hold all the bits of the original type. For an i140
1493  /// on a 32 bit machine this means 5 registers.
1494  ///
1495  /// RegisterVT may be passed as a way to override the default settings, for
1496  /// instance with i128 inline assembly operands on SystemZ.
1497  virtual unsigned
1499  Optional<MVT> RegisterVT = None) const {
1500  if (VT.isSimple()) {
1501  assert((unsigned)VT.getSimpleVT().SimpleTy <
1502  array_lengthof(NumRegistersForVT));
1503  return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1504  }
1505  if (VT.isVector()) {
1506  EVT VT1;
1507  MVT VT2;
1508  unsigned NumIntermediates;
1509  return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1510  }
1511  if (VT.isInteger()) {
1512  unsigned BitWidth = VT.getSizeInBits();
1513  unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1514  return (BitWidth + RegWidth - 1) / RegWidth;
1515  }
1516  llvm_unreachable("Unsupported extended type!");
1517  }
1518 
1519  /// Certain combinations of ABIs, Targets and features require that types
1520  /// are legal for some operations and not for other operations.
1521  /// For MIPS all vector types must be passed through the integer register set.
1523  CallingConv::ID CC, EVT VT) const {
1524  return getRegisterType(Context, VT);
1525  }
1526 
1527  /// Certain targets require unusual breakdowns of certain types. For MIPS,
1528  /// this occurs when a vector type is used, as vector are passed through the
1529  /// integer register set.
1531  CallingConv::ID CC,
1532  EVT VT) const {
1533  return getNumRegisters(Context, VT);
1534  }
1535 
1536  /// Certain targets have context sensitive alignment requirements, where one
1537  /// type has the alignment requirement of another type.
1539  const DataLayout &DL) const {
1540  return DL.getABITypeAlign(ArgTy);
1541  }
1542 
1543  /// If true, then instruction selection should seek to shrink the FP constant
1544  /// of the specified type to a smaller type in order to save space and / or
1545  /// reduce runtime.
1546  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1547 
1548  /// Return true if it is profitable to reduce a load to a smaller type.
1549  /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1551  EVT NewVT) const {
1552  // By default, assume that it is cheaper to extract a subvector from a wide
1553  // vector load rather than creating multiple narrow vector loads.
1554  if (NewVT.isVector() && !Load->hasOneUse())
1555  return false;
1556 
1557  return true;
1558  }
1559 
1560  /// When splitting a value of the specified type into parts, does the Lo
1561  /// or Hi part come first? This usually follows the endianness, except
1562  /// for ppcf128, where the Hi part always comes first.
1563  bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1564  return DL.isBigEndian() || VT == MVT::ppcf128;
1565  }
1566 
1567  /// If true, the target has custom DAG combine transformations that it can
1568  /// perform for the specified node.
1570  assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1571  return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1572  }
1573 
1574  unsigned getGatherAllAliasesMaxDepth() const {
1575  return GatherAllAliasesMaxDepth;
1576  }
1577 
1578  /// Returns the size of the platform's va_list object.
1579  virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1580  return getPointerTy(DL).getSizeInBits();
1581  }
1582 
1583  /// Get maximum # of store operations permitted for llvm.memset
1584  ///
1585  /// This function returns the maximum number of store operations permitted
1586  /// to replace a call to llvm.memset. The value is set by the target at the
1587  /// performance threshold for such a replacement. If OptSize is true,
1588  /// return the limit for functions that have OptSize attribute.
1589  unsigned getMaxStoresPerMemset(bool OptSize) const {
1590  return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1591  }
1592 
1593  /// Get maximum # of store operations permitted for llvm.memcpy
1594  ///
1595  /// This function returns the maximum number of store operations permitted
1596  /// to replace a call to llvm.memcpy. The value is set by the target at the
1597  /// performance threshold for such a replacement. If OptSize is true,
1598  /// return the limit for functions that have OptSize attribute.
1599  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1600  return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1601  }
1602 
1603  /// \brief Get maximum # of store operations to be glued together
1604  ///
1605  /// This function returns the maximum number of store operations permitted
1606  /// to glue together during lowering of llvm.memcpy. The value is set by
1607  // the target at the performance threshold for such a replacement.
1608  virtual unsigned getMaxGluedStoresPerMemcpy() const {
1609  return MaxGluedStoresPerMemcpy;
1610  }
1611 
1612  /// Get maximum # of load operations permitted for memcmp
1613  ///
1614  /// This function returns the maximum number of load operations permitted
1615  /// to replace a call to memcmp. The value is set by the target at the
1616  /// performance threshold for such a replacement. If OptSize is true,
1617  /// return the limit for functions that have OptSize attribute.
1618  unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1619  return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1620  }
1621 
1622  /// Get maximum # of store operations permitted for llvm.memmove
1623  ///
1624  /// This function returns the maximum number of store operations permitted
1625  /// to replace a call to llvm.memmove. The value is set by the target at the
1626  /// performance threshold for such a replacement. If OptSize is true,
1627  /// return the limit for functions that have OptSize attribute.
1628  unsigned getMaxStoresPerMemmove(bool OptSize) const {
1630  }
1631 
1632  /// Determine if the target supports unaligned memory accesses.
1633  ///
1634  /// This function returns true if the target allows unaligned memory accesses
1635  /// of the specified type in the given address space. If true, it also returns
1636  /// whether the unaligned memory access is "fast" in the last argument by
1637  /// reference. This is used, for example, in situations where an array
1638  /// copy/move/set is converted to a sequence of store operations. Its use
1639  /// helps to ensure that such replacements don't generate code that causes an
1640  /// alignment error (trap) on the target machine.
1642  EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1644  bool * /*Fast*/ = nullptr) const {
1645  return false;
1646  }
1647 
1648  /// LLT handling variant.
1650  LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1652  bool * /*Fast*/ = nullptr) const {
1653  return false;
1654  }
1655 
1656  /// This function returns true if the memory access is aligned or if the
1657  /// target allows this specific unaligned memory access. If the access is
1658  /// allowed, the optional final parameter returns if the access is also fast
1659  /// (as defined by the target).
1661  LLVMContext &Context, const DataLayout &DL, EVT VT,
1662  unsigned AddrSpace = 0, Align Alignment = Align(1),
1664  bool *Fast = nullptr) const;
1665 
1666  /// Return true if the memory access of this type is aligned or if the target
1667  /// allows this specific unaligned access for the given MachineMemOperand.
1668  /// If the access is allowed, the optional final parameter returns if the
1669  /// access is also fast (as defined by the target).
1671  const DataLayout &DL, EVT VT,
1672  const MachineMemOperand &MMO,
1673  bool *Fast = nullptr) const;
1674 
1675  /// Return true if the target supports a memory access of this type for the
1676  /// given address space and alignment. If the access is allowed, the optional
1677  /// final parameter returns if the access is also fast (as defined by the
1678  /// target).
1679  virtual bool
1681  unsigned AddrSpace = 0, Align Alignment = Align(1),
1683  bool *Fast = nullptr) const;
1684 
1685  /// Return true if the target supports a memory access of this type for the
1686  /// given MachineMemOperand. If the access is allowed, the optional
1687  /// final parameter returns if the access is also fast (as defined by the
1688  /// target).
1690  const MachineMemOperand &MMO,
1691  bool *Fast = nullptr) const;
1692 
1693  /// LLT handling variant.
1695  const MachineMemOperand &MMO,
1696  bool *Fast = nullptr) const;
1697 
1698  /// Returns the target specific optimal type for load and store operations as
1699  /// a result of memset, memcpy, and memmove lowering.
1700  /// It returns EVT::Other if the type should be determined using generic
1701  /// target-independent logic.
1702  virtual EVT
1704  const AttributeList & /*FuncAttributes*/) const {
1705  return MVT::Other;
1706  }
1707 
1708  /// LLT returning variant.
1709  virtual LLT
1711  const AttributeList & /*FuncAttributes*/) const {
1712  return LLT();
1713  }
1714 
1715  /// Returns true if it's safe to use load / store of the specified type to
1716  /// expand memcpy / memset inline.
1717  ///
1718  /// This is mostly true for all types except for some special cases. For
1719  /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1720  /// fstpl which also does type conversion. Note the specified type doesn't
1721  /// have to be legal as the hook is used before type legalization.
1722  virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1723 
1724  /// Return lower limit for number of blocks in a jump table.
1725  virtual unsigned getMinimumJumpTableEntries() const;
1726 
1727  /// Return lower limit of the density in a jump table.
1728  unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1729 
1730  /// Return upper limit for number of entries in a jump table.
1731  /// Zero if no limit.
1732  unsigned getMaximumJumpTableSize() const;
1733 
1734  virtual bool isJumpTableRelative() const;
1735 
1736  /// If a physical register, this specifies the register that
1737  /// llvm.savestack/llvm.restorestack should save and restore.
1739  return StackPointerRegisterToSaveRestore;
1740  }
1741 
1742  /// If a physical register, this returns the register that receives the
1743  /// exception address on entry to an EH pad.
1744  virtual Register
1745  getExceptionPointerRegister(const Constant *PersonalityFn) const {
1746  return Register();
1747  }
1748 
1749  /// If a physical register, this returns the register that receives the
1750  /// exception typeid on entry to a landing pad.
1751  virtual Register
1752  getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1753  return Register();
1754  }
1755 
1756  virtual bool needsFixedCatchObjects() const {
1757  report_fatal_error("Funclet EH is not implemented for this target");
1758  }
1759 
1760  /// Return the minimum stack alignment of an argument.
1762  return MinStackArgumentAlignment;
1763  }
1764 
1765  /// Return the minimum function alignment.
1766  Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
1767 
1768  /// Return the preferred function alignment.
1769  Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
1770 
1771  /// Return the preferred loop alignment.
1772  virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const;
1773 
1774  /// Should loops be aligned even when the function is marked OptSize (but not
1775  /// MinSize).
1776  virtual bool alignLoopsWithOptSize() const {
1777  return false;
1778  }
1779 
1780  /// If the target has a standard location for the stack protector guard,
1781  /// returns the address of that location. Otherwise, returns nullptr.
1782  /// DEPRECATED: please override useLoadStackGuardNode and customize
1783  /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1784  virtual Value *getIRStackGuard(IRBuilderBase &IRB) const;
1785 
1786  /// Inserts necessary declarations for SSP (stack protection) purpose.
1787  /// Should be used only when getIRStackGuard returns nullptr.
1788  virtual void insertSSPDeclarations(Module &M) const;
1789 
1790  /// Return the variable that's previously inserted by insertSSPDeclarations,
1791  /// if any, otherwise return nullptr. Should be used only when
1792  /// getIRStackGuard returns nullptr.
1793  virtual Value *getSDagStackGuard(const Module &M) const;
1794 
1795  /// If this function returns true, stack protection checks should XOR the
1796  /// frame pointer (or whichever pointer is used to address locals) into the
1797  /// stack guard value before checking it. getIRStackGuard must return nullptr
1798  /// if this returns true.
1799  virtual bool useStackGuardXorFP() const { return false; }
1800 
1801  /// If the target has a standard stack protection check function that
1802  /// performs validation and error handling, returns the function. Otherwise,
1803  /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1804  /// Should be used only when getIRStackGuard returns nullptr.
1805  virtual Function *getSSPStackGuardCheck(const Module &M) const;
1806 
1807  /// \returns true if a constant G_UBFX is legal on the target.
1808  virtual bool isConstantUnsignedBitfieldExtactLegal(unsigned Opc, LLT Ty1,
1809  LLT Ty2) const {
1810  return false;
1811  }
1812 
1813 protected:
1815  bool UseTLS) const;
1816 
1817 public:
1818  /// Returns the target-specific address of the unsafe stack pointer.
1819  virtual Value *getSafeStackPointerLocation(IRBuilderBase &IRB) const;
1820 
1821  /// Returns the name of the symbol used to emit stack probes or the empty
1822  /// string if not applicable.
1823  virtual bool hasStackProbeSymbol(MachineFunction &MF) const { return false; }
1824 
1825  virtual bool hasInlineStackProbe(MachineFunction &MF) const { return false; }
1826 
1828  return "";
1829  }
1830 
1831  /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1832  /// are happy to sink it into basic blocks. A cast may be free, but not
1833  /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
1834  virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
1835 
1836  /// Return true if the pointer arguments to CI should be aligned by aligning
1837  /// the object whose address is being passed. If so then MinSize is set to the
1838  /// minimum size the object must be to be aligned and PrefAlign is set to the
1839  /// preferred alignment.
1840  virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1841  unsigned & /*PrefAlign*/) const {
1842  return false;
1843  }
1844 
1845  //===--------------------------------------------------------------------===//
1846  /// \name Helpers for TargetTransformInfo implementations
1847  /// @{
1848 
1849  /// Get the ISD node that corresponds to the Instruction class opcode.
1850  int InstructionOpcodeToISD(unsigned Opcode) const;
1851 
1852  /// Estimate the cost of type-legalization and the legalized type.
1853  std::pair<InstructionCost, MVT> getTypeLegalizationCost(const DataLayout &DL,
1854  Type *Ty) const;
1855 
1856  /// @}
1857 
1858  //===--------------------------------------------------------------------===//
1859  /// \name Helpers for atomic expansion.
1860  /// @{
1861 
1862  /// Returns the maximum atomic operation size (in bits) supported by
1863  /// the backend. Atomic operations greater than this size (as well
1864  /// as ones that are not naturally aligned), will be expanded by
1865  /// AtomicExpandPass into an __atomic_* library call.
1867  return MaxAtomicSizeInBitsSupported;
1868  }
1869 
1870  /// Returns the size of the smallest cmpxchg or ll/sc instruction
1871  /// the backend supports. Any smaller operations are widened in
1872  /// AtomicExpandPass.
1873  ///
1874  /// Note that *unlike* operations above the maximum size, atomic ops
1875  /// are still natively supported below the minimum; they just
1876  /// require a more complex expansion.
1877  unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1878 
1879  /// Whether the target supports unaligned atomic operations.
1880  bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1881 
1882  /// Whether AtomicExpandPass should automatically insert fences and reduce
1883  /// ordering for this atomic. This should be true for most architectures with
1884  /// weak memory ordering. Defaults to false.
1885  virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1886  return false;
1887  }
1888 
1889  /// Perform a load-linked operation on Addr, returning a "Value *" with the
1890  /// corresponding pointee type. This may entail some non-trivial operations to
1891  /// truncate or reconstruct types that will be illegal in the backend. See
1892  /// ARMISelLowering for an example implementation.
1894  Value *Addr, AtomicOrdering Ord) const {
1895  llvm_unreachable("Load linked unimplemented on this target");
1896  }
1897 
1898  /// Perform a store-conditional operation to Addr. Return the status of the
1899  /// store. This should be 0 if the store succeeded, non-zero otherwise.
1901  Value *Addr, AtomicOrdering Ord) const {
1902  llvm_unreachable("Store conditional unimplemented on this target");
1903  }
1904 
1905  /// Perform a masked atomicrmw using a target-specific intrinsic. This
1906  /// represents the core LL/SC loop which will be lowered at a late stage by
1907  /// the backend.
1909  AtomicRMWInst *AI,
1910  Value *AlignedAddr, Value *Incr,
1911  Value *Mask, Value *ShiftAmt,
1912  AtomicOrdering Ord) const {
1913  llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
1914  }
1915 
1916  /// Perform a masked cmpxchg using a target-specific intrinsic. This
1917  /// represents the core LL/SC loop which will be lowered at a late stage by
1918  /// the backend.
1920  IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1921  Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1922  llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
1923  }
1924 
1925  /// Inserts in the IR a target-specific intrinsic specifying a fence.
1926  /// It is called by AtomicExpandPass before expanding an
1927  /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1928  /// if shouldInsertFencesForAtomic returns true.
1929  ///
1930  /// Inst is the original atomic instruction, prior to other expansions that
1931  /// may be performed.
1932  ///
1933  /// This function should either return a nullptr, or a pointer to an IR-level
1934  /// Instruction*. Even complex fence sequences can be represented by a
1935  /// single Instruction* through an intrinsic to be lowered later.
1936  /// Backends should override this method to produce target-specific intrinsic
1937  /// for their fences.
1938  /// FIXME: Please note that the default implementation here in terms of
1939  /// IR-level fences exists for historical/compatibility reasons and is
1940  /// *unsound* ! Fences cannot, in general, be used to restore sequential
1941  /// consistency. For example, consider the following example:
1942  /// atomic<int> x = y = 0;
1943  /// int r1, r2, r3, r4;
1944  /// Thread 0:
1945  /// x.store(1);
1946  /// Thread 1:
1947  /// y.store(1);
1948  /// Thread 2:
1949  /// r1 = x.load();
1950  /// r2 = y.load();
1951  /// Thread 3:
1952  /// r3 = y.load();
1953  /// r4 = x.load();
1954  /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1955  /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1956  /// IR-level fences can prevent it.
1957  /// @{
1959  Instruction *Inst,
1960  AtomicOrdering Ord) const;
1961 
1963  Instruction *Inst,
1964  AtomicOrdering Ord) const;
1965  /// @}
1966 
1967  // Emits code that executes when the comparison result in the ll/sc
1968  // expansion of a cmpxchg instruction is such that the store-conditional will
1969  // not execute. This makes it possible to balance out the load-linked with
1970  // a dedicated instruction, if desired.
1971  // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1972  // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1974 
1975  /// Returns true if the given (atomic) store should be expanded by the
1976  /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1978  return false;
1979  }
1980 
1981  /// Returns true if arguments should be sign-extended in lib calls.
1982  virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1983  return IsSigned;
1984  }
1985 
1986  /// Returns true if arguments should be extended in lib calls.
1987  virtual bool shouldExtendTypeInLibCall(EVT Type) const {
1988  return true;
1989  }
1990 
1991  /// Returns how the given (atomic) load should be expanded by the
1992  /// IR-level AtomicExpand pass.
1995  }
1996 
1997  /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1998  /// AtomicExpand pass.
1999  virtual AtomicExpansionKind
2002  }
2003 
2004  /// Returns how the IR-level AtomicExpand pass should expand the given
2005  /// AtomicRMW, if at all. Default is to never expand.
2007  return RMW->isFloatingPointOperation() ?
2009  }
2010 
2011  /// On some platforms, an AtomicRMW that never actually modifies the value
2012  /// (such as fetch_add of 0) can be turned into a fence followed by an
2013  /// atomic load. This may sound useless, but it makes it possible for the
2014  /// processor to keep the cacheline shared, dramatically improving
2015  /// performance. And such idempotent RMWs are useful for implementing some
2016  /// kinds of locks, see for example (justification + benchmarks):
2017  /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
2018  /// This method tries doing that transformation, returning the atomic load if
2019  /// it succeeds, and nullptr otherwise.
2020  /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
2021  /// another round of expansion.
2022  virtual LoadInst *
2024  return nullptr;
2025  }
2026 
2027  /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2028  /// SIGN_EXTEND, or ANY_EXTEND).
2030  return ISD::ZERO_EXTEND;
2031  }
2032 
2033  /// Returns how the platform's atomic compare and swap expects its comparison
2034  /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2035  /// separate from getExtendForAtomicOps, which is concerned with the
2036  /// sign-extension of the instruction's output, whereas here we are concerned
2037  /// with the sign-extension of the input. For targets with compare-and-swap
2038  /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2039  /// the input can be ANY_EXTEND, but the output will still have a specific
2040  /// extension.
2042  return ISD::ANY_EXTEND;
2043  }
2044 
2045  /// @}
2046 
2047  /// Returns true if we should normalize
2048  /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2049  /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2050  /// that it saves us from materializing N0 and N1 in an integer register.
2051  /// Targets that are able to perform and/or on flags should return false here.
2053  EVT VT) const {
2054  // If a target has multiple condition registers, then it likely has logical
2055  // operations on those registers.
2057  return false;
2058  // Only do the transform if the value won't be split into multiple
2059  // registers.
2061  return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2062  Action != TypeSplitVector;
2063  }
2064 
2065  virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2066 
2067  /// Return true if a select of constants (select Cond, C1, C2) should be
2068  /// transformed into simple math ops with the condition value. For example:
2069  /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2070  virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2071  return false;
2072  }
2073 
2074  /// Return true if it is profitable to transform an integer
2075  /// multiplication-by-constant into simpler operations like shifts and adds.
2076  /// This may be true if the target does not directly support the
2077  /// multiplication operation for the specified type or the sequence of simpler
2078  /// ops is faster than the multiply.
2080  EVT VT, SDValue C) const {
2081  return false;
2082  }
2083 
2084  /// Return true if it may be profitable to transform
2085  /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
2086  /// This may not be true if c1 and c2 can be represented as immediates but
2087  /// c1*c2 cannot, for example.
2088  /// The target should check if c1, c2 and c1*c2 can be represented as
2089  /// immediates, or have to be materialized into registers. If it is not sure
2090  /// about some cases, a default true can be returned to let the DAGCombiner
2091  /// decide.
2092  /// AddNode is (add x, c1), and ConstNode is c2.
2093  virtual bool isMulAddWithConstProfitable(const SDValue &AddNode,
2094  const SDValue &ConstNode) const {
2095  return true;
2096  }
2097 
2098  /// Return true if it is more correct/profitable to use strict FP_TO_INT
2099  /// conversion operations - canonicalizing the FP source value instead of
2100  /// converting all cases and then selecting based on value.
2101  /// This may be true if the target throws exceptions for out of bounds
2102  /// conversions or has fast FP CMOV.
2103  virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2104  bool IsSigned) const {
2105  return false;
2106  }
2107 
2108  //===--------------------------------------------------------------------===//
2109  // TargetLowering Configuration Methods - These methods should be invoked by
2110  // the derived class constructor to configure this object for the target.
2111  //
2112 protected:
2113  /// Specify how the target extends the result of integer and floating point
2114  /// boolean values from i1 to a wider type. See getBooleanContents.
2116  BooleanContents = Ty;
2117  BooleanFloatContents = Ty;
2118  }
2119 
2120  /// Specify how the target extends the result of integer and floating point
2121  /// boolean values from i1 to a wider type. See getBooleanContents.
2123  BooleanContents = IntTy;
2124  BooleanFloatContents = FloatTy;
2125  }
2126 
2127  /// Specify how the target extends the result of a vector boolean value from a
2128  /// vector of i1 to a wider type. See getBooleanContents.
2130  BooleanVectorContents = Ty;
2131  }
2132 
2133  /// Specify the target scheduling preference.
2135  SchedPreferenceInfo = Pref;
2136  }
2137 
2138  /// Indicate the minimum number of blocks to generate jump tables.
2139  void setMinimumJumpTableEntries(unsigned Val);
2140 
2141  /// Indicate the maximum number of entries in jump tables.
2142  /// Set to zero to generate unlimited jump tables.
2143  void setMaximumJumpTableSize(unsigned);
2144 
2145  /// If set to a physical register, this specifies the register that
2146  /// llvm.savestack/llvm.restorestack should save and restore.
2148  StackPointerRegisterToSaveRestore = R;
2149  }
2150 
2151  /// Tells the code generator that the target has multiple (allocatable)
2152  /// condition registers that can be used to store the results of comparisons
2153  /// for use by selects and conditional branches. With multiple condition
2154  /// registers, the code generator will not aggressively sink comparisons into
2155  /// the blocks of their users.
2156  void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
2157  HasMultipleConditionRegisters = hasManyRegs;
2158  }
2159 
2160  /// Tells the code generator that the target has BitExtract instructions.
2161  /// The code generator will aggressively sink "shift"s into the blocks of
2162  /// their users if the users will generate "and" instructions which can be
2163  /// combined with "shift" to BitExtract instructions.
2164  void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2165  HasExtractBitsInsn = hasExtractInsn;
2166  }
2167 
2168  /// Tells the code generator not to expand logic operations on comparison
2169  /// predicates into separate sequences that increase the amount of flow
2170  /// control.
2171  void setJumpIsExpensive(bool isExpensive = true);
2172 
2173  /// Tells the code generator which bitwidths to bypass.
2174  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2175  BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2176  }
2177 
2178  /// Add the specified register class as an available regclass for the
2179  /// specified value type. This indicates the selector can handle values of
2180  /// that class natively.
2182  assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
2183  RegClassForVT[VT.SimpleTy] = RC;
2184  }
2185 
2186  /// Return the largest legal super-reg register class of the register class
2187  /// for the specified type and its associated "cost".
2188  virtual std::pair<const TargetRegisterClass *, uint8_t>
2190 
2191  /// Once all of the register classes are added, this allows us to compute
2192  /// derived properties we expose.
2194 
2195  /// Indicate that the specified operation does not work with the specified
2196  /// type and indicate what to do about it. Note that VT may refer to either
2197  /// the type of a result or that of an operand of Op.
2198  void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
2199  assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
2200  OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2201  }
2202 
2203  /// Indicate that the specified load with extension does not work with the
2204  /// specified type and indicate what to do about it.
2205  void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2206  LegalizeAction Action) {
2207  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2208  MemVT.isValid() && "Table isn't big enough!");
2209  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2210  unsigned Shift = 4 * ExtType;
2211  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2212  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2213  }
2214 
2215  /// Indicate that the specified truncating store does not work with the
2216  /// specified type and indicate what to do about it.
2217  void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
2218  assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2219  TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2220  }
2221 
2222  /// Indicate that the specified indexed load does or does not work with the
2223  /// specified type and indicate what to do abort it.
2224  ///
2225  /// NOTE: All indexed mode loads are initialized to Expand in
2226  /// TargetLowering.cpp
2227  void setIndexedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
2228  setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2229  }
2230 
2231  /// Indicate that the specified indexed store does or does not work with the
2232  /// specified type and indicate what to do about it.
2233  ///
2234  /// NOTE: All indexed mode stores are initialized to Expand in
2235  /// TargetLowering.cpp
2236  void setIndexedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
2237  setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2238  }
2239 
2240  /// Indicate that the specified indexed masked load does or does not work with
2241  /// the specified type and indicate what to do about it.
2242  ///
2243  /// NOTE: All indexed mode masked loads are initialized to Expand in
2244  /// TargetLowering.cpp
2245  void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2246  LegalizeAction Action) {
2247  setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2248  }
2249 
2250  /// Indicate that the specified indexed masked store does or does not work
2251  /// with the specified type and indicate what to do about it.
2252  ///
2253  /// NOTE: All indexed mode masked stores are initialized to Expand in
2254  /// TargetLowering.cpp
2255  void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2256  LegalizeAction Action) {
2257  setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2258  }
2259 
2260  /// Indicate that the specified condition code is or isn't supported on the
2261  /// target and indicate what to do about it.
2263  LegalizeAction Action) {
2264  assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
2265  "Table isn't big enough!");
2266  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2267  /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
2268  /// value and the upper 29 bits index into the second dimension of the array
2269  /// to select what 32-bit value to use.
2270  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2271  CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2272  CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2273  }
2274 
2275  /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2276  /// to trying a larger integer/fp until it can find one that works. If that
2277  /// default is insufficient, this method can be used by the target to override
2278  /// the default.
2279  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2280  PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2281  }
2282 
2283  /// Convenience method to set an operation to Promote and specify the type
2284  /// in a single call.
2285  void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2286  setOperationAction(Opc, OrigVT, Promote);
2287  AddPromotedToType(Opc, OrigVT, DestVT);
2288  }
2289 
2290  /// Targets should invoke this method for each target independent node that
2291  /// they want to provide a custom DAG combiner for by implementing the
2292  /// PerformDAGCombine virtual method.
2294  assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
2295  TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
2296  }
2297 
2298  /// Set the target's minimum function alignment.
2299  void setMinFunctionAlignment(Align Alignment) {
2300  MinFunctionAlignment = Alignment;
2301  }
2302 
2303  /// Set the target's preferred function alignment. This should be set if
2304  /// there is a performance benefit to higher-than-minimum alignment
2306  PrefFunctionAlignment = Alignment;
2307  }
2308 
2309  /// Set the target's preferred loop alignment. Default alignment is one, it
2310  /// means the target does not care about loop alignment. The target may also
2311  /// override getPrefLoopAlignment to provide per-loop values.
2312  void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2313 
2314  /// Set the minimum stack alignment of an argument.
2316  MinStackArgumentAlignment = Alignment;
2317  }
2318 
2319  /// Set the maximum atomic operation size supported by the
2320  /// backend. Atomic operations greater than this size (as well as
2321  /// ones that are not naturally aligned), will be expanded by
2322  /// AtomicExpandPass into an __atomic_* library call.
2323  void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2324  MaxAtomicSizeInBitsSupported = SizeInBits;
2325  }
2326 
2327  /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2328  void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2329  MinCmpXchgSizeInBits = SizeInBits;
2330  }
2331 
2332  /// Sets whether unaligned atomic operations are supported.
2333  void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2334  SupportsUnalignedAtomics = UnalignedSupported;
2335  }
2336 
2337 public:
2338  //===--------------------------------------------------------------------===//
2339  // Addressing mode description hooks (used by LSR etc).
2340  //
2341 
2342  /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2343  /// instructions reading the address. This allows as much computation as
2344  /// possible to be done in the address mode for that operand. This hook lets
2345  /// targets also pass back when this should be done on intrinsics which
2346  /// load/store.
2347  virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2348  SmallVectorImpl<Value*> &/*Ops*/,
2349  Type *&/*AccessTy*/) const {
2350  return false;
2351  }
2352 
2353  /// This represents an addressing mode of:
2354  /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2355  /// If BaseGV is null, there is no BaseGV.
2356  /// If BaseOffs is zero, there is no base offset.
2357  /// If HasBaseReg is false, there is no base register.
2358  /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2359  /// no scale.
2360  struct AddrMode {
2361  GlobalValue *BaseGV = nullptr;
2362  int64_t BaseOffs = 0;
2363  bool HasBaseReg = false;
2364  int64_t Scale = 0;
2365  AddrMode() = default;
2366  };
2367 
2368  /// Return true if the addressing mode represented by AM is legal for this
2369  /// target, for a load/store of the specified type.
2370  ///
2371  /// The type may be VoidTy, in which case only return true if the addressing
2372  /// mode is legal for a load/store of any legal type. TODO: Handle
2373  /// pre/postinc as well.
2374  ///
2375  /// If the address space cannot be determined, it will be -1.
2376  ///
2377  /// TODO: Remove default argument
2378  virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2379  Type *Ty, unsigned AddrSpace,
2380  Instruction *I = nullptr) const;
2381 
2382  /// Return the cost of the scaling factor used in the addressing mode
2383  /// represented by AM for this target, for a load/store of the specified type.
2384  ///
2385  /// If the AM is supported, the return value must be >= 0.
2386  /// If the AM is not supported, it returns a negative value.
2387  /// TODO: Handle pre/postinc as well.
2388  /// TODO: Remove default argument
2390  const AddrMode &AM, Type *Ty,
2391  unsigned AS = 0) const {
2392  // Default: assume that any scaling factor used in a legal AM is free.
2393  if (isLegalAddressingMode(DL, AM, Ty, AS))
2394  return 0;
2395  return -1;
2396  }
2397 
2398  /// Return true if the specified immediate is legal icmp immediate, that is
2399  /// the target has icmp instructions which can compare a register against the
2400  /// immediate without having to materialize the immediate into a register.
2401  virtual bool isLegalICmpImmediate(int64_t) const {
2402  return true;
2403  }
2404 
2405  /// Return true if the specified immediate is legal add immediate, that is the
2406  /// target has add instructions which can add a register with the immediate
2407  /// without having to materialize the immediate into a register.
2408  virtual bool isLegalAddImmediate(int64_t) const {
2409  return true;
2410  }
2411 
2412  /// Return true if the specified immediate is legal for the value input of a
2413  /// store instruction.
2414  virtual bool isLegalStoreImmediate(int64_t Value) const {
2415  // Default implementation assumes that at least 0 works since it is likely
2416  // that a zero register exists or a zero immediate is allowed.
2417  return Value == 0;
2418  }
2419 
2420  /// Return true if it's significantly cheaper to shift a vector by a uniform
2421  /// scalar than by an amount which will vary across each lane. On x86 before
2422  /// AVX2 for example, there is a "psllw" instruction for the former case, but
2423  /// no simple instruction for a general "a << b" operation on vectors.
2424  /// This should also apply to lowering for vector funnel shifts (rotates).
2425  virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2426  return false;
2427  }
2428 
2429  /// Given a shuffle vector SVI representing a vector splat, return a new
2430  /// scalar type of size equal to SVI's scalar type if the new type is more
2431  /// profitable. Returns nullptr otherwise. For example under MVE float splats
2432  /// are converted to integer to prevent the need to move from SPR to GPR
2433  /// registers.
2435  return nullptr;
2436  }
2437 
2438  /// Given a set in interconnected phis of type 'From' that are loaded/stored
2439  /// or bitcast to type 'To', return true if the set should be converted to
2440  /// 'To'.
2441  virtual bool shouldConvertPhiType(Type *From, Type *To) const {
2442  return (From->isIntegerTy() || From->isFloatingPointTy()) &&
2443  (To->isIntegerTy() || To->isFloatingPointTy());
2444  }
2445 
2446  /// Returns true if the opcode is a commutative binary operation.
2447  virtual bool isCommutativeBinOp(unsigned Opcode) const {
2448  // FIXME: This should get its info from the td file.
2449  switch (Opcode) {
2450  case ISD::ADD:
2451  case ISD::SMIN:
2452  case ISD::SMAX:
2453  case ISD::UMIN:
2454  case ISD::UMAX:
2455  case ISD::MUL:
2456  case ISD::MULHU:
2457  case ISD::MULHS:
2458  case ISD::SMUL_LOHI:
2459  case ISD::UMUL_LOHI:
2460  case ISD::FADD:
2461  case ISD::FMUL:
2462  case ISD::AND:
2463  case ISD::OR:
2464  case ISD::XOR:
2465  case ISD::SADDO:
2466  case ISD::UADDO:
2467  case ISD::ADDC:
2468  case ISD::ADDE:
2469  case ISD::SADDSAT:
2470  case ISD::UADDSAT:
2471  case ISD::FMINNUM:
2472  case ISD::FMAXNUM:
2473  case ISD::FMINNUM_IEEE:
2474  case ISD::FMAXNUM_IEEE:
2475  case ISD::FMINIMUM:
2476  case ISD::FMAXIMUM:
2477  return true;
2478  default: return false;
2479  }
2480  }
2481 
2482  /// Return true if the node is a math/logic binary operator.
2483  virtual bool isBinOp(unsigned Opcode) const {
2484  // A commutative binop must be a binop.
2485  if (isCommutativeBinOp(Opcode))
2486  return true;
2487  // These are non-commutative binops.
2488  switch (Opcode) {
2489  case ISD::SUB:
2490  case ISD::SHL:
2491  case ISD::SRL:
2492  case ISD::SRA:
2493  case ISD::SDIV:
2494  case ISD::UDIV:
2495  case ISD::SREM:
2496  case ISD::UREM:
2497  case ISD::SSUBSAT:
2498  case ISD::USUBSAT:
2499  case ISD::FSUB:
2500  case ISD::FDIV:
2501  case ISD::FREM:
2502  return true;
2503  default:
2504  return false;
2505  }
2506  }
2507 
2508  /// Return true if it's free to truncate a value of type FromTy to type
2509  /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2510  /// by referencing its sub-register AX.
2511  /// Targets must return false when FromTy <= ToTy.
2512  virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2513  return false;
2514  }
2515 
2516  /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2517  /// whether a call is in tail position. Typically this means that both results
2518  /// would be assigned to the same register or stack slot, but it could mean
2519  /// the target performs adequate checks of its own before proceeding with the
2520  /// tail call. Targets must return false when FromTy <= ToTy.
2521  virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2522  return false;
2523  }
2524 
2525  virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
2526  virtual bool isTruncateFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2527  LLVMContext &Ctx) const {
2528  return isTruncateFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2529  getApproximateEVTForLLT(ToTy, DL, Ctx));
2530  }
2531 
2532  virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2533 
2534  /// Return true if the extension represented by \p I is free.
2535  /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2536  /// this method can use the context provided by \p I to decide
2537  /// whether or not \p I is free.
2538  /// This method extends the behavior of the is[Z|FP]ExtFree family.
2539  /// In other words, if is[Z|FP]Free returns true, then this method
2540  /// returns true as well. The converse is not true.
2541  /// The target can perform the adequate checks by overriding isExtFreeImpl.
2542  /// \pre \p I must be a sign, zero, or fp extension.
2543  bool isExtFree(const Instruction *I) const {
2544  switch (I->getOpcode()) {
2545  case Instruction::FPExt:
2546  if (isFPExtFree(EVT::getEVT(I->getType()),
2547  EVT::getEVT(I->getOperand(0)->getType())))
2548  return true;
2549  break;
2550  case Instruction::ZExt:
2551  if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2552  return true;
2553  break;
2554  case Instruction::SExt:
2555  break;
2556  default:
2557  llvm_unreachable("Instruction is not an extension");
2558  }
2559  return isExtFreeImpl(I);
2560  }
2561 
2562  /// Return true if \p Load and \p Ext can form an ExtLoad.
2563  /// For example, in AArch64
2564  /// %L = load i8, i8* %ptr
2565  /// %E = zext i8 %L to i32
2566  /// can be lowered into one load instruction
2567  /// ldrb w0, [x0]
2568  bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2569  const DataLayout &DL) const {
2570  EVT VT = getValueType(DL, Ext->getType());
2571  EVT LoadVT = getValueType(DL, Load->getType());
2572 
2573  // If the load has other users and the truncate is not free, the ext
2574  // probably isn't free.
2575  if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2576  !isTruncateFree(Ext->getType(), Load->getType()))
2577  return false;
2578 
2579  // Check whether the target supports casts folded into loads.
2580  unsigned LType;
2581  if (isa<ZExtInst>(Ext))
2582  LType = ISD::ZEXTLOAD;
2583  else {
2584  assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2585  LType = ISD::SEXTLOAD;
2586  }
2587 
2588  return isLoadExtLegal(LType, VT, LoadVT);
2589  }
2590 
2591  /// Return true if any actual instruction that defines a value of type FromTy
2592  /// implicitly zero-extends the value to ToTy in the result register.
2593  ///
2594  /// The function should return true when it is likely that the truncate can
2595  /// be freely folded with an instruction defining a value of FromTy. If
2596  /// the defining instruction is unknown (because you're looking at a
2597  /// function argument, PHI, etc.) then the target may require an
2598  /// explicit truncate, which is not necessarily free, but this function
2599  /// does not deal with those cases.
2600  /// Targets must return false when FromTy >= ToTy.
2601  virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2602  return false;
2603  }
2604 
2605  virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
2606  virtual bool isZExtFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2607  LLVMContext &Ctx) const {
2608  return isZExtFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2609  getApproximateEVTForLLT(ToTy, DL, Ctx));
2610  }
2611 
2612  /// Return true if sign-extension from FromTy to ToTy is cheaper than
2613  /// zero-extension.
2614  virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2615  return false;
2616  }
2617 
2618  /// Return true if sinking I's operands to the same basic block as I is
2619  /// profitable, e.g. because the operands can be folded into a target
2620  /// instruction during instruction selection. After calling the function
2621  /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2622  /// come first).
2624  SmallVectorImpl<Use *> &Ops) const {
2625  return false;
2626  }
2627 
2628  /// Return true if the target supplies and combines to a paired load
2629  /// two loaded values of type LoadedType next to each other in memory.
2630  /// RequiredAlignment gives the minimal alignment constraints that must be met
2631  /// to be able to select this paired load.
2632  ///
2633  /// This information is *not* used to generate actual paired loads, but it is
2634  /// used to generate a sequence of loads that is easier to combine into a
2635  /// paired load.
2636  /// For instance, something like this:
2637  /// a = load i64* addr
2638  /// b = trunc i64 a to i32
2639  /// c = lshr i64 a, 32
2640  /// d = trunc i64 c to i32
2641  /// will be optimized into:
2642  /// b = load i32* addr1
2643  /// d = load i32* addr2
2644  /// Where addr1 = addr2 +/- sizeof(i32).
2645  ///
2646  /// In other words, unless the target performs a post-isel load combining,
2647  /// this information should not be provided because it will generate more
2648  /// loads.
2649  virtual bool hasPairedLoad(EVT /*LoadedType*/,
2650  Align & /*RequiredAlignment*/) const {
2651  return false;
2652  }
2653 
2654  /// Return true if the target has a vector blend instruction.
2655  virtual bool hasVectorBlend() const { return false; }
2656 
2657  /// Get the maximum supported factor for interleaved memory accesses.
2658  /// Default to be the minimum interleave factor: 2.
2659  virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2660 
2661  /// Lower an interleaved load to target specific intrinsics. Return
2662  /// true on success.
2663  ///
2664  /// \p LI is the vector load instruction.
2665  /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2666  /// \p Indices is the corresponding indices for each shufflevector.
2667  /// \p Factor is the interleave factor.
2668  virtual bool lowerInterleavedLoad(LoadInst *LI,
2670  ArrayRef<unsigned> Indices,
2671  unsigned Factor) const {
2672  return false;
2673  }
2674 
2675  /// Lower an interleaved store to target specific intrinsics. Return
2676  /// true on success.
2677  ///
2678  /// \p SI is the vector store instruction.
2679  /// \p SVI is the shufflevector to RE-interleave the stored vector.
2680  /// \p Factor is the interleave factor.
2682  unsigned Factor) const {
2683  return false;
2684  }
2685 
2686  /// Return true if zero-extending the specific node Val to type VT2 is free
2687  /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2688  /// because it's folded such as X86 zero-extending loads).
2689  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2690  return isZExtFree(Val.getValueType(), VT2);
2691  }
2692 
2693  /// Return true if an fpext operation is free (for instance, because
2694  /// single-precision floating-point numbers are implicitly extended to
2695  /// double-precision).
2696  virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2697  assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2698  "invalid fpext types");
2699  return false;
2700  }
2701 
2702  /// Return true if an fpext operation input to an \p Opcode operation is free
2703  /// (for instance, because half-precision floating-point numbers are
2704  /// implicitly extended to float-precision) for an FMA instruction.
2705  virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
2706  EVT DestVT, EVT SrcVT) const {
2707  assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2708  "invalid fpext types");
2709  return isFPExtFree(DestVT, SrcVT);
2710  }
2711 
2712  /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2713  /// extend node) is profitable.
2714  virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2715 
2716  /// Return true if an fneg operation is free to the point where it is never
2717  /// worthwhile to replace it with a bitwise operation.
2718  virtual bool isFNegFree(EVT VT) const {
2719  assert(VT.isFloatingPoint());
2720  return false;
2721  }
2722 
2723  /// Return true if an fabs operation is free to the point where it is never
2724  /// worthwhile to replace it with a bitwise operation.
2725  virtual bool isFAbsFree(EVT VT) const {
2726  assert(VT.isFloatingPoint());
2727  return false;
2728  }
2729 
2730  /// Return true if an FMA operation is faster than a pair of fmul and fadd
2731  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2732  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2733  ///
2734  /// NOTE: This may be called before legalization on types for which FMAs are
2735  /// not legal, but should return true if those types will eventually legalize
2736  /// to types that support FMAs. After legalization, it will only be called on
2737  /// types that support FMAs (via Legal or Custom actions)
2739  EVT) const {
2740  return false;
2741  }
2742 
2743  /// IR version
2744  virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
2745  return false;
2746  }
2747 
2748  /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
2749  /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
2750  /// fadd/fsub.
2751  virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
2752  assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
2753  N->getOpcode() == ISD::FMUL) &&
2754  "unexpected node in FMAD forming combine");
2755  return isOperationLegal(ISD::FMAD, N->getValueType(0));
2756  }
2757 
2758  // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
2759  // than FMUL and ADD is delegated to the machine combiner.
2761  CodeGenOpt::Level OptLevel) const {
2762  return false;
2763  }
2764 
2765  /// Return true if it's profitable to narrow operations of type VT1 to
2766  /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2767  /// i32 to i16.
2768  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2769  return false;
2770  }
2771 
2772  /// Return true if it is beneficial to convert a load of a constant to
2773  /// just the constant itself.
2774  /// On some targets it might be more efficient to use a combination of
2775  /// arithmetic instructions to materialize the constant instead of loading it
2776  /// from a constant pool.
2777  virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2778  Type *Ty) const {
2779  return false;
2780  }
2781 
2782  /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2783  /// from this source type with this index. This is needed because
2784  /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2785  /// the first element, and only the target knows which lowering is cheap.
2786  virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2787  unsigned Index) const {
2788  return false;
2789  }
2790 
2791  /// Try to convert an extract element of a vector binary operation into an
2792  /// extract element followed by a scalar operation.
2793  virtual bool shouldScalarizeBinop(SDValue VecOp) const {
2794  return false;
2795  }
2796 
2797  /// Return true if extraction of a scalar element from the given vector type
2798  /// at the given index is cheap. For example, if scalar operations occur on
2799  /// the same register file as vector operations, then an extract element may
2800  /// be a sub-register rename rather than an actual instruction.
2801  virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
2802  return false;
2803  }
2804 
2805  /// Try to convert math with an overflow comparison into the corresponding DAG
2806  /// node operation. Targets may want to override this independently of whether
2807  /// the operation is legal/custom for the given type because it may obscure
2808  /// matching of other patterns.
2809  virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
2810  bool MathUsed) const {
2811  // TODO: The default logic is inherited from code in CodeGenPrepare.
2812  // The opcode should not make a difference by default?
2813  if (Opcode != ISD::UADDO)
2814  return false;
2815 
2816  // Allow the transform as long as we have an integer type that is not
2817  // obviously illegal and unsupported and if the math result is used
2818  // besides the overflow check. On some targets (e.g. SPARC), it is
2819  // not profitable to form on overflow op if the math result has no
2820  // concrete users.
2821  if (VT.isVector())
2822  return false;
2823  return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
2824  }
2825 
2826  // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2827  // even if the vector itself has multiple uses.
2828  virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2829  return false;
2830  }
2831 
2832  // Return true if CodeGenPrepare should consider splitting large offset of a
2833  // GEP to make the GEP fit into the addressing mode and can be sunk into the
2834  // same blocks of its users.
2835  virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2836 
2837  /// Return true if creating a shift of the type by the given
2838  /// amount is not profitable.
2839  virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
2840  return false;
2841  }
2842 
2843  /// Does this target require the clearing of high-order bits in a register
2844  /// passed to the fp16 to fp conversion library function.
2845  virtual bool shouldKeepZExtForFP16Conv() const { return false; }
2846 
2847  //===--------------------------------------------------------------------===//
2848  // Runtime Library hooks
2849  //
2850 
2851  /// Rename the default libcall routine name for the specified libcall.
2852  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2853  LibcallRoutineNames[Call] = Name;
2854  }
2855 
2856  /// Get the libcall routine name for the specified libcall.
2857  const char *getLibcallName(RTLIB::Libcall Call) const {
2858  return LibcallRoutineNames[Call];
2859  }
2860 
2861  /// Override the default CondCode to be used to test the result of the
2862  /// comparison libcall against zero.
2864  CmpLibcallCCs[Call] = CC;
2865  }
2866 
2867  /// Get the CondCode that's to be used to test the result of the comparison
2868  /// libcall against zero.
2870  return CmpLibcallCCs[Call];
2871  }
2872 
2873  /// Set the CallingConv that should be used for the specified libcall.
2875  LibcallCallingConvs[Call] = CC;
2876  }
2877 
2878  /// Get the CallingConv that should be used for the specified libcall.
2880  return LibcallCallingConvs[Call];
2881  }
2882 
2883  /// Execute target specific actions to finalize target lowering.
2884  /// This is used to set extra flags in MachineFrameInformation and freezing
2885  /// the set of reserved registers.
2886  /// The default implementation just freezes the set of reserved registers.
2887  virtual void finalizeLowering(MachineFunction &MF) const;
2888 
2889  //===----------------------------------------------------------------------===//
2890  // GlobalISel Hooks
2891  //===----------------------------------------------------------------------===//
2892  /// Check whether or not \p MI needs to be moved close to its uses.
2893  virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
2894 
2895 
2896 private:
2897  const TargetMachine &TM;
2898 
2899  /// Tells the code generator that the target has multiple (allocatable)
2900  /// condition registers that can be used to store the results of comparisons
2901  /// for use by selects and conditional branches. With multiple condition
2902  /// registers, the code generator will not aggressively sink comparisons into
2903  /// the blocks of their users.
2904  bool HasMultipleConditionRegisters;
2905 
2906  /// Tells the code generator that the target has BitExtract instructions.
2907  /// The code generator will aggressively sink "shift"s into the blocks of
2908  /// their users if the users will generate "and" instructions which can be
2909  /// combined with "shift" to BitExtract instructions.
2910  bool HasExtractBitsInsn;
2911 
2912  /// Tells the code generator to bypass slow divide or remainder
2913  /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2914  /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2915  /// div/rem when the operands are positive and less than 256.
2916  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2917 
2918  /// Tells the code generator that it shouldn't generate extra flow control
2919  /// instructions and should attempt to combine flow control instructions via
2920  /// predication.
2921  bool JumpIsExpensive;
2922 
2923  /// Information about the contents of the high-bits in boolean values held in
2924  /// a type wider than i1. See getBooleanContents.
2925  BooleanContent BooleanContents;
2926 
2927  /// Information about the contents of the high-bits in boolean values held in
2928  /// a type wider than i1. See getBooleanContents.
2929  BooleanContent BooleanFloatContents;
2930 
2931  /// Information about the contents of the high-bits in boolean vector values
2932  /// when the element type is wider than i1. See getBooleanContents.
2933  BooleanContent BooleanVectorContents;
2934 
2935  /// The target scheduling preference: shortest possible total cycles or lowest
2936  /// register usage.
2937  Sched::Preference SchedPreferenceInfo;
2938 
2939  /// The minimum alignment that any argument on the stack needs to have.
2940  Align MinStackArgumentAlignment;
2941 
2942  /// The minimum function alignment (used when optimizing for size, and to
2943  /// prevent explicitly provided alignment from leading to incorrect code).
2944  Align MinFunctionAlignment;
2945 
2946  /// The preferred function alignment (used when alignment unspecified and
2947  /// optimizing for speed).
2948  Align PrefFunctionAlignment;
2949 
2950  /// The preferred loop alignment (in log2 bot in bytes).
2951  Align PrefLoopAlignment;
2952 
2953  /// Size in bits of the maximum atomics size the backend supports.
2954  /// Accesses larger than this will be expanded by AtomicExpandPass.
2955  unsigned MaxAtomicSizeInBitsSupported;
2956 
2957  /// Size in bits of the minimum cmpxchg or ll/sc operation the
2958  /// backend supports.
2959  unsigned MinCmpXchgSizeInBits;
2960 
2961  /// This indicates if the target supports unaligned atomic operations.
2962  bool SupportsUnalignedAtomics;
2963 
2964  /// If set to a physical register, this specifies the register that
2965  /// llvm.savestack/llvm.restorestack should save and restore.
2966  Register StackPointerRegisterToSaveRestore;
2967 
2968  /// This indicates the default register class to use for each ValueType the
2969  /// target supports natively.
2970  const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
2971  uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
2972  MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
2973 
2974  /// This indicates the "representative" register class to use for each
2975  /// ValueType the target supports natively. This information is used by the
2976  /// scheduler to track register pressure. By default, the representative
2977  /// register class is the largest legal super-reg register class of the
2978  /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2979  /// representative class would be GR32.
2980  const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE];
2981 
2982  /// This indicates the "cost" of the "representative" register class for each
2983  /// ValueType. The cost is used by the scheduler to approximate register
2984  /// pressure.
2985  uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
2986 
2987  /// For any value types we are promoting or expanding, this contains the value
2988  /// type that we are changing to. For Expanded types, this contains one step
2989  /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2990  /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2991  /// the same type (e.g. i32 -> i32).
2992  MVT TransformToType[MVT::VALUETYPE_SIZE];
2993 
2994  /// For each operation and each value type, keep a LegalizeAction that
2995  /// indicates how instruction selection should deal with the operation. Most
2996  /// operations are Legal (aka, supported natively by the target), but
2997  /// operations that are not should be described. Note that operations on
2998  /// non-legal value types are not described here.
3000 
3001  /// For each load extension type and each value type, keep a LegalizeAction
3002  /// that indicates how instruction selection should deal with a load of a
3003  /// specific value type and extension type. Uses 4-bits to store the action
3004  /// for each of the 4 load ext types.
3006 
3007  /// For each value type pair keep a LegalizeAction that indicates whether a
3008  /// truncating store of a specific value type and truncating type is legal.
3010 
3011  /// For each indexed mode and each value type, keep a quad of LegalizeAction
3012  /// that indicates how instruction selection should deal with the load /
3013  /// store / maskedload / maskedstore.
3014  ///
3015  /// The first dimension is the value_type for the reference. The second
3016  /// dimension represents the various modes for load store.
3018 
3019  /// For each condition code (ISD::CondCode) keep a LegalizeAction that
3020  /// indicates how instruction selection should deal with the condition code.
3021  ///
3022  /// Because each CC action takes up 4 bits, we need to have the array size be
3023  /// large enough to fit all of the value types. This can be done by rounding
3024  /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
3025  uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
3026 
3027  ValueTypeActionImpl ValueTypeActions;
3028 
3029 private:
3030  LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
3031 
3032  /// Targets can specify ISD nodes that they would like PerformDAGCombine
3033  /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
3034  /// array.
3035  unsigned char
3036  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
3037 
3038  /// For operations that must be promoted to a specific type, this holds the
3039  /// destination type. This map should be sparse, so don't hold it as an
3040  /// array.
3041  ///
3042  /// Targets add entries to this map with AddPromotedToType(..), clients access
3043  /// this with getTypeToPromoteTo(..).
3044  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3045  PromoteToType;
3046 
3047  /// Stores the name each libcall.
3048  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
3049 
3050  /// The ISD::CondCode that should be used to test the result of each of the
3051  /// comparison libcall against zero.
3052  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
3053 
3054  /// Stores the CallingConv that should be used for each libcall.
3055  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
3056 
3057  /// Set default libcall names and calling conventions.
3058  void InitLibcalls(const Triple &TT);
3059 
3060  /// The bits of IndexedModeActions used to store the legalisation actions
3061  /// We store the data as | ML | MS | L | S | each taking 4 bits.
3062  enum IndexedModeActionsBits {
3063  IMAB_Store = 0,
3064  IMAB_Load = 4,
3065  IMAB_MaskedStore = 8,
3066  IMAB_MaskedLoad = 12
3067  };
3068 
3069  void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
3070  LegalizeAction Action) {
3071  assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
3072  (unsigned)Action < 0xf && "Table isn't big enough!");
3073  unsigned Ty = (unsigned)VT.SimpleTy;
3074  IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
3075  IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
3076  }
3077 
3078  LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
3079  unsigned Shift) const {
3080  assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
3081  "Table isn't big enough!");
3082  unsigned Ty = (unsigned)VT.SimpleTy;
3083  return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
3084  }
3085 
3086 protected:
3087  /// Return true if the extension represented by \p I is free.
3088  /// \pre \p I is a sign, zero, or fp extension and
3089  /// is[Z|FP]ExtFree of the related types is not true.
3090  virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
3091 
3092  /// Depth that GatherAllAliases should should continue looking for chain
3093  /// dependencies when trying to find a more preferable chain. As an
3094  /// approximation, this should be more than the number of consecutive stores
3095  /// expected to be merged.
3097 
3098  /// \brief Specify maximum number of store instructions per memset call.
3099  ///
3100  /// When lowering \@llvm.memset this field specifies the maximum number of
3101  /// store operations that may be substituted for the call to memset. Targets
3102  /// must set this value based on the cost threshold for that target. Targets
3103  /// should assume that the memset will be done using as many of the largest
3104  /// store operations first, followed by smaller ones, if necessary, per
3105  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
3106  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
3107  /// store. This only applies to setting a constant array of a constant size.
3109  /// Likewise for functions with the OptSize attribute.
3111 
3112  /// \brief Specify maximum number of store instructions per memcpy call.
3113  ///
3114  /// When lowering \@llvm.memcpy this field specifies the maximum number of
3115  /// store operations that may be substituted for a call to memcpy. Targets
3116  /// must set this value based on the cost threshold for that target. Targets
3117  /// should assume that the memcpy will be done using as many of the largest
3118  /// store operations first, followed by smaller ones, if necessary, per
3119  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
3120  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
3121  /// and one 1-byte store. This only applies to copying a constant array of
3122  /// constant size.
3124  /// Likewise for functions with the OptSize attribute.
3126  /// \brief Specify max number of store instructions to glue in inlined memcpy.
3127  ///
3128  /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
3129  /// of store instructions to keep together. This helps in pairing and
3130  // vectorization later on.
3132 
3133  /// \brief Specify maximum number of load instructions per memcmp call.
3134  ///
3135  /// When lowering \@llvm.memcmp this field specifies the maximum number of
3136  /// pairs of load operations that may be substituted for a call to memcmp.
3137  /// Targets must set this value based on the cost threshold for that target.
3138  /// Targets should assume that the memcmp will be done using as many of the
3139  /// largest load operations first, followed by smaller ones, if necessary, per
3140  /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
3141  /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
3142  /// and one 1-byte load. This only applies to copying a constant array of
3143  /// constant size.
3145  /// Likewise for functions with the OptSize attribute.
3147 
3148  /// \brief Specify maximum number of store instructions per memmove call.
3149  ///
3150  /// When lowering \@llvm.memmove this field specifies the maximum number of
3151  /// store instructions that may be substituted for a call to memmove. Targets
3152  /// must set this value based on the cost threshold for that target. Targets
3153  /// should assume that the memmove will be done using as many of the largest
3154  /// store operations first, followed by smaller ones, if necessary, per
3155  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
3156  /// with 8-bit alignment would result in nine 1-byte stores. This only
3157  /// applies to copying a constant array of constant size.
3159  /// Likewise for functions with the OptSize attribute.
3161 
3162  /// Tells the code generator that select is more expensive than a branch if
3163  /// the branch is usually predicted right.
3165 
3166  /// \see enableExtLdPromotion.
3168 
3169  /// Return true if the value types that can be represented by the specified
3170  /// register class are all legal.
3171  bool isLegalRC(const TargetRegisterInfo &TRI,
3172  const TargetRegisterClass &RC) const;
3173 
3174  /// Replace/modify any TargetFrameIndex operands with a targte-dependent
3175  /// sequence of memory operands that is recognized by PrologEpilogInserter.
3177  MachineBasicBlock *MBB) const;
3178 
3180 };
3181 
3182 /// This class defines information used to lower LLVM code to legal SelectionDAG
3183 /// operators that the target instruction selector can accept natively.
3184 ///
3185 /// This class also defines callbacks that targets must implement to lower
3186 /// target-specific constructs to SelectionDAG operators.
3188 public:
3189  struct DAGCombinerInfo;
3190  struct MakeLibCallOptions;
3191 
3192  TargetLowering(const TargetLowering &) = delete;
3193  TargetLowering &operator=(const TargetLowering &) = delete;
3194 
3195  explicit TargetLowering(const TargetMachine &TM);
3196 
3197  bool isPositionIndependent() const;
3198 
3199  virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
3200  FunctionLoweringInfo *FLI,
3201  LegacyDivergenceAnalysis *DA) const {
3202  return false;
3203  }
3204 
3205  virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
3206  return false;
3207  }
3208 
3209  /// Returns true by value, base pointer and offset pointer and addressing mode
3210  /// by reference if the node's address can be legally represented as
3211  /// pre-indexed load / store address.
3212  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
3213  SDValue &/*Offset*/,
3214  ISD::MemIndexedMode &/*AM*/,
3215  SelectionDAG &/*DAG*/) const {
3216  return false;
3217  }
3218 
3219  /// Returns true by value, base pointer and offset pointer and addressing mode
3220  /// by reference if this node can be combined with a load / store to form a
3221  /// post-indexed load / store.
3222  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
3223  SDValue &/*Base*/,
3224  SDValue &/*Offset*/,
3225  ISD::MemIndexedMode &/*AM*/,
3226  SelectionDAG &/*DAG*/) const {
3227  return false;
3228  }
3229 
3230  /// Returns true if the specified base+offset is a legal indexed addressing
3231  /// mode for this target. \p MI is the load or store instruction that is being
3232  /// considered for transformation.
3234  bool IsPre, MachineRegisterInfo &MRI) const {
3235  return false;
3236  }
3237 
3238  /// Return the entry encoding for a jump table in the current function. The
3239  /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
3240  virtual unsigned getJumpTableEncoding() const;
3241 
3242  virtual const MCExpr *
3244  const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
3245  MCContext &/*Ctx*/) const {
3246  llvm_unreachable("Need to implement this hook if target has custom JTIs");
3247  }
3248 
3249  /// Returns relocation base for the given PIC jumptable.
3251  SelectionDAG &DAG) const;
3252 
3253  /// This returns the relocation base for the given PIC jumptable, the same as
3254  /// getPICJumpTableRelocBase, but as an MCExpr.
3255  virtual const MCExpr *
3257  unsigned JTI, MCContext &Ctx) const;
3258 
3259  /// Return true if folding a constant offset with the given GlobalAddress is
3260  /// legal. It is frequently not legal in PIC relocation models.
3261  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
3262 
3264  SDValue &Chain) const;
3265 
3266  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3267  SDValue &NewRHS, ISD::CondCode &CCCode,
3268  const SDLoc &DL, const SDValue OldLHS,
3269  const SDValue OldRHS) const;
3270 
3271  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3272  SDValue &NewRHS, ISD::CondCode &CCCode,
3273  const SDLoc &DL, const SDValue OldLHS,
3274  const SDValue OldRHS, SDValue &Chain,
3275  bool IsSignaling = false) const;
3276 
3277  /// Returns a pair of (return value, chain).
3278  /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
3279  std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
3280  EVT RetVT, ArrayRef<SDValue> Ops,
3281  MakeLibCallOptions CallOptions,
3282  const SDLoc &dl,
3283  SDValue Chain = SDValue()) const;
3284 
3285  /// Check whether parameters to a call that are passed in callee saved
3286  /// registers are the same as from the calling function. This needs to be
3287  /// checked for tail call eligibility.
3289  const uint32_t *CallerPreservedMask,
3290  const SmallVectorImpl<CCValAssign> &ArgLocs,
3291  const SmallVectorImpl<SDValue> &OutVals) const;
3292 
3293  //===--------------------------------------------------------------------===//
3294  // TargetLowering Optimization Methods
3295  //
3296 
3297  /// A convenience struct that encapsulates a DAG, and two SDValues for
3298  /// returning information from TargetLowering to its clients that want to
3299  /// combine.
3302  bool LegalTys;
3303  bool LegalOps;
3306 
3308  bool LT, bool LO) :
3309  DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
3310 
3311  bool LegalTypes() const { return LegalTys; }
3312  bool LegalOperations() const { return LegalOps; }
3313 
3315  Old = O;
3316  New = N;
3317  return true;
3318  }
3319  };
3320 
3321  /// Determines the optimal series of memory ops to replace the memset / memcpy.
3322  /// Return true if the number of memory ops is below the threshold (Limit).
3323  /// It returns the types of the sequence of memory ops to perform
3324  /// memset / memcpy by reference.
3325  bool findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
3326  const MemOp &Op, unsigned DstAS, unsigned SrcAS,
3327  const AttributeList &FuncAttributes) const;
3328 
3329  /// Check to see if the specified operand of the specified instruction is a
3330  /// constant integer. If so, check to see if there are any bits set in the
3331  /// constant that are not demanded. If so, shrink the constant and return
3332  /// true.
3334  const APInt &DemandedElts,
3335  TargetLoweringOpt &TLO) const;
3336 
3337  /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
3339  TargetLoweringOpt &TLO) const;
3340 
3341  // Target hook to do target-specific const optimization, which is called by
3342  // ShrinkDemandedConstant. This function should return true if the target
3343  // doesn't want ShrinkDemandedConstant to further optimize the constant.
3345  const APInt &DemandedBits,
3346  const APInt &DemandedElts,
3347  TargetLoweringOpt &TLO) const {
3348  return false;
3349  }
3350 
3351  /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
3352  /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3353  /// generalized for targets with other types of implicit widening casts.
3354  bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
3355  TargetLoweringOpt &TLO) const;
3356 
3357  /// Look at Op. At this point, we know that only the DemandedBits bits of the
3358  /// result of Op are ever used downstream. If we can use this information to
3359  /// simplify Op, create a new simplified DAG node and return true, returning
3360  /// the original and new nodes in Old and New. Otherwise, analyze the
3361  /// expression and return a mask of KnownOne and KnownZero bits for the
3362  /// expression (used to simplify the caller). The KnownZero/One bits may only
3363  /// be accurate for those bits in the Demanded masks.
3364  /// \p AssumeSingleUse When this parameter is true, this function will
3365  /// attempt to simplify \p Op even if there are multiple uses.
3366  /// Callers are responsible for correctly updating the DAG based on the
3367  /// results of this function, because simply replacing replacing TLO.Old
3368  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3369  /// has multiple uses.
3371  const APInt &DemandedElts, KnownBits &Known,
3372  TargetLoweringOpt &TLO, unsigned Depth = 0,
3373  bool AssumeSingleUse = false) const;
3374 
3375  /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3376  /// Adds Op back to the worklist upon success.
3378  KnownBits &Known, TargetLoweringOpt &TLO,
3379  unsigned Depth = 0,
3380  bool AssumeSingleUse = false) const;
3381 
3382  /// Helper wrapper around SimplifyDemandedBits.
3383  /// Adds Op back to the worklist upon success.
3385  DAGCombinerInfo &DCI) const;
3386 
3387  /// More limited version of SimplifyDemandedBits that can be used to "look
3388  /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3389  /// bitwise ops etc.
3391  const APInt &DemandedElts,
3392  SelectionDAG &DAG,
3393  unsigned Depth) const;
3394 
3395  /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3396  /// elements.
3398  SelectionDAG &DAG,
3399  unsigned Depth = 0) const;
3400 
3401  /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3402  /// bits from only some vector elements.
3404  const APInt &DemandedElts,
3405  SelectionDAG &DAG,
3406  unsigned Depth = 0) const;
3407 
3408  /// Look at Vector Op. At this point, we know that only the DemandedElts
3409  /// elements of the result of Op are ever used downstream. If we can use
3410  /// this information to simplify Op, create a new simplified DAG node and
3411  /// return true, storing the original and new nodes in TLO.
3412  /// Otherwise, analyze the expression and return a mask of KnownUndef and
3413  /// KnownZero elements for the expression (used to simplify the caller).
3414  /// The KnownUndef/Zero elements may only be accurate for those bits
3415  /// in the DemandedMask.
3416  /// \p AssumeSingleUse When this parameter is true, this function will
3417  /// attempt to simplify \p Op even if there are multiple uses.
3418  /// Callers are responsible for correctly updating the DAG based on the
3419  /// results of this function, because simply replacing replacing TLO.Old
3420  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3421  /// has multiple uses.
3422  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3423  APInt &KnownUndef, APInt &KnownZero,
3424  TargetLoweringOpt &TLO, unsigned Depth = 0,
3425  bool AssumeSingleUse = false) const;
3426 
3427  /// Helper wrapper around SimplifyDemandedVectorElts.
3428  /// Adds Op back to the worklist upon success.
3429  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3430  APInt &KnownUndef, APInt &KnownZero,
3431  DAGCombinerInfo &DCI) const;
3432 
3433  /// Determine which of the bits specified in Mask are known to be either zero
3434  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3435  /// argument allows us to only collect the known bits that are shared by the
3436  /// requested vector elements.
3437  virtual void computeKnownBitsForTargetNode(const SDValue Op,
3438  KnownBits &Known,
3439  const APInt &DemandedElts,
3440  const SelectionDAG &DAG,
3441  unsigned Depth = 0) const;
3442 
3443  /// Determine which of the bits specified in Mask are known to be either zero
3444  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3445  /// argument allows us to only collect the known bits that are shared by the
3446  /// requested vector elements. This is for GISel.
3447  virtual void computeKnownBitsForTargetInstr(GISelKnownBits &Analysis,
3448  Register R, KnownBits &Known,
3449  const APInt &DemandedElts,
3450  const MachineRegisterInfo &MRI,
3451  unsigned Depth = 0) const;
3452 
3453  /// Determine the known alignment for the pointer value \p R. This is can
3454  /// typically be inferred from the number of low known 0 bits. However, for a
3455  /// pointer with a non-integral address space, the alignment value may be
3456  /// independent from the known low bits.
3458  Register R,
3459  const MachineRegisterInfo &MRI,
3460  unsigned Depth = 0) const;
3461 
3462  /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3463  /// Default implementation computes low bits based on alignment
3464  /// information. This should preserve known bits passed into it.
3465  virtual void computeKnownBitsForFrameIndex(int FIOp,
3466  KnownBits &Known,
3467  const MachineFunction &MF) const;
3468 
3469  /// This method can be implemented by targets that want to expose additional
3470  /// information about sign bits to the DAG Combiner. The DemandedElts
3471  /// argument allows us to only collect the minimum sign bits that are shared
3472  /// by the requested vector elements.
3473  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
3474  const APInt &DemandedElts,
3475  const SelectionDAG &DAG,
3476  unsigned Depth = 0) const;
3477 
3478  /// This method can be implemented by targets that want to expose additional
3479  /// information about sign bits to GlobalISel combiners. The DemandedElts
3480  /// argument allows us to only collect the minimum sign bits that are shared
3481  /// by the requested vector elements.
3482  virtual unsigned computeNumSignBitsForTargetInstr(GISelKnownBits &Analysis,
3483  Register R,
3484  const APInt &DemandedElts,
3485  const MachineRegisterInfo &MRI,
3486  unsigned Depth = 0) const;
3487 
3488  /// Attempt to simplify any target nodes based on the demanded vector
3489  /// elements, returning true on success. Otherwise, analyze the expression and
3490  /// return a mask of KnownUndef and KnownZero elements for the expression
3491  /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3492  /// accurate for those bits in the DemandedMask.
3494  SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3495  APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3496 
3497  /// Attempt to simplify any target nodes based on the demanded bits/elts,
3498  /// returning true on success. Otherwise, analyze the
3499  /// expression and return a mask of KnownOne and KnownZero bits for the
3500  /// expression (used to simplify the caller). The KnownZero/One bits may only
3501  /// be accurate for those bits in the Demanded masks.
3503  const APInt &DemandedBits,
3504  const APInt &DemandedElts,
3505  KnownBits &Known,
3506  TargetLoweringOpt &TLO,
3507  unsigned Depth = 0) const;
3508 
3509  /// More limited version of SimplifyDemandedBits that can be used to "look
3510  /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3511  /// bitwise ops etc.
3513  SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3514  SelectionDAG &DAG, unsigned Depth) const;
3515 
3516  /// Return true if this function can prove that \p Op is never poison
3517  /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
3518  /// argument limits the check to the requested vector elements.
3520  SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3521  bool PoisonOnly, unsigned Depth) const;
3522 
3523  /// Tries to build a legal vector shuffle using the provided parameters
3524  /// or equivalent variations. The Mask argument maybe be modified as the
3525  /// function tries different variations.
3526  /// Returns an empty SDValue if the operation fails.
3529  SelectionDAG &DAG) const;
3530 
3531  /// This method returns the constant pool value that will be loaded by LD.
3532  /// NOTE: You must check for implicit extensions of the constant by LD.
3533  virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
3534 
3535  /// If \p SNaN is false, \returns true if \p Op is known to never be any
3536  /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3537  /// NaN.
3539  const SelectionDAG &DAG,
3540  bool SNaN = false,
3541  unsigned Depth = 0) const;
3543  void *DC; // The DAG Combiner object.
3546 
3547  public:
3549 
3550  DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
3551  : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
3552 
3553  bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
3555  bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
3557  bool isCalledByLegalizer() const { return CalledByLegalizer; }
3558 
3559  void AddToWorklist(SDNode *N);
3560  SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
3561  SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
3562  SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
3563 
3565 
3566  void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
3567  };
3568 
3569  /// Return if the N is a constant or constant vector equal to the true value
3570  /// from getBooleanContents().
3571  bool isConstTrueVal(const SDNode *N) const;
3572 
3573  /// Return if the N is a constant or constant vector equal to the false value
3574  /// from getBooleanContents().
3575  bool isConstFalseVal(const SDNode *N) const;
3576 
3577  /// Return if \p N is a True value when extended to \p VT.
3578  bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
3579 
3580  /// Try to simplify a setcc built with the specified operands and cc. If it is
3581  /// unable to simplify it, return a null SDValue.
3583  bool foldBooleans, DAGCombinerInfo &DCI,
3584  const SDLoc &dl) const;
3585 
3586  // For targets which wrap address, unwrap for analysis.
3587  virtual SDValue unwrapAddress(SDValue N) const { return N; }
3588 
3589  /// Returns true (and the GlobalValue and the offset) if the node is a
3590  /// GlobalAddress + offset.
3591  virtual bool
3592  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
3593 
3594  /// This method will be invoked for all target nodes and for any
3595  /// target-independent nodes that the target has registered with invoke it
3596  /// for.
3597  ///
3598  /// The semantics are as follows:
3599  /// Return Value:
3600  /// SDValue.Val == 0 - No change was made
3601  /// SDValue.Val == N - N was replaced, is dead, and is already handled.
3602  /// otherwise - N should be replaced by the returned Operand.
3603  ///
3604  /// In addition, methods provided by DAGCombinerInfo may be used to perform
3605  /// more complex transformations.
3606  ///
3607  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
3608 
3609  /// Return true if it is profitable to move this shift by a constant amount
3610  /// though its operand, adjusting any immediate operands as necessary to
3611  /// preserve semantics. This transformation may not be desirable if it
3612  /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3613  /// extraction in AArch64). By default, it returns true.
3614  ///
3615  /// @param N the shift node
3616  /// @param Level the current DAGCombine legalization level.
3618  CombineLevel Level) const {
3619  return true;
3620  }
3621 
3622  /// Return true if the target has native support for the specified value type
3623  /// and it is 'desirable' to use the type for the given node type. e.g. On x86
3624  /// i16 is legal, but undesirable since i16 instruction encodings are longer
3625  /// and some i16 instructions are slow.
3626  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
3627  // By default, assume all legal types are desirable.
3628  return isTypeLegal(VT);
3629  }
3630 
3631  /// Return true if it is profitable for dag combiner to transform a floating
3632  /// point op of specified opcode to a equivalent op of an integer
3633  /// type. e.g. f32 load -> i32 load can be profitable on ARM.
3634  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
3635  EVT /*VT*/) const {
3636  return false;
3637  }
3638 
3639  /// This method query the target whether it is beneficial for dag combiner to
3640  /// promote the specified node. If true, it should return the desired
3641  /// promotion type by reference.
3642  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
3643  return false;
3644  }
3645 
3646  /// Return true if the target supports swifterror attribute. It optimizes
3647  /// loads and stores to reading and writing a specific register.
3648  virtual bool supportSwiftError() const {
3649  return false;
3650  }
3651 
3652  /// Return true if the target supports that a subset of CSRs for the given
3653  /// machine function is handled explicitly via copies.
3654  virtual bool supportSplitCSR(MachineFunction *MF) const {
3655  return false;
3656  }
3657 
3658  /// Perform necessary initialization to handle a subset of CSRs explicitly
3659  /// via copies. This function is called at the beginning of instruction
3660  /// selection.
3661  virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
3662  llvm_unreachable("Not Implemented");
3663  }
3664 
3665  /// Insert explicit copies in entry and exit blocks. We copy a subset of
3666  /// CSRs to virtual registers in the entry block, and copy them back to
3667  /// physical registers in the exit blocks. This function is called at the end
3668  /// of instruction selection.
3669  virtual void insertCopiesSplitCSR(
3670  MachineBasicBlock *Entry,
3671  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3672  llvm_unreachable("Not Implemented");
3673  }
3674 
3675  /// Return the newly negated expression if the cost is not expensive and
3676  /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
3677  /// do the negation.
3679  bool LegalOps, bool OptForSize,
3680  NegatibleCost &Cost,
3681  unsigned Depth = 0) const;
3682 
3683  /// This is the helper function to return the newly negated expression only
3684  /// when the cost is cheaper.
3686  bool LegalOps, bool OptForSize,
3687  unsigned Depth = 0) const {
3689  SDValue Neg =
3690  getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
3691  if (Neg && Cost == NegatibleCost::Cheaper)
3692  return Neg;
3693  // Remove the new created node to avoid the side effect to the DAG.
3694  if (Neg && Neg.getNode()->use_empty())
3695  DAG.RemoveDeadNode(Neg.getNode());
3696  return SDValue();
3697  }
3698 
3699  /// This is the helper function to return the newly negated expression if
3700  /// the cost is not expensive.
3702  bool OptForSize, unsigned Depth = 0) const {
3704  return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
3705  }
3706 
3707  //===--------------------------------------------------------------------===//
3708  // Lowering methods - These methods must be implemented by targets so that
3709  // the SelectionDAGBuilder code knows how to lower these.
3710  //
3711 
3712  /// Target-specific splitting of values into parts that fit a register
3713  /// storing a legal type
3715  SDValue Val, SDValue *Parts,
3716  unsigned NumParts, MVT PartVT,
3717  Optional<CallingConv::ID> CC) const {
3718  return false;
3719  }
3720 
3721  /// Target-specific combining of register parts into its original value
3722  virtual SDValue
3724  const SDValue *Parts, unsigned NumParts,
3725  MVT PartVT, EVT ValueVT,
3726  Optional<CallingConv::ID> CC) const {
3727  return SDValue();
3728  }
3729 
3730  /// This hook must be implemented to lower the incoming (formal) arguments,
3731  /// described by the Ins array, into the specified DAG. The implementation
3732  /// should fill in the InVals array with legal-type argument values, and
3733  /// return the resulting token chain value.
3735  SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
3736  const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
3737  SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
3738  llvm_unreachable("Not Implemented");
3739  }
3740 
3741  /// This structure contains all information that is necessary for lowering
3742  /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
3743  /// needs to lower a call, and targets will see this struct in their LowerCall
3744  /// implementation.
3747  Type *RetTy = nullptr;
3748  bool RetSExt : 1;
3749  bool RetZExt : 1;
3750  bool IsVarArg : 1;
3751  bool IsInReg : 1;
3752  bool DoesNotReturn : 1;
3754  bool IsConvergent : 1;
3755  bool IsPatchPoint : 1;
3756  bool IsPreallocated : 1;
3757  bool NoMerge : 1;
3758 
3759  // IsTailCall should be modified by implementations of
3760  // TargetLowering::LowerCall that perform tail call conversions.
3761  bool IsTailCall = false;
3762 
3763  // Is Call lowering done post SelectionDAG type legalization.
3765 
3766  unsigned NumFixedArgs = -1;
3772  const CallBase *CB = nullptr;
3777 
3782  DAG(DAG) {}
3783 
3785  DL = dl;
3786  return *this;
3787  }
3788 
3790  Chain = InChain;
3791  return *this;
3792  }
3793 
3794  // setCallee with target/module-specific attributes
3796  SDValue Target, ArgListTy &&ArgsList) {
3797  RetTy = ResultType;
3798  Callee = Target;
3799  CallConv = CC;
3800  NumFixedArgs = ArgsList.size();
3801  Args = std::move(ArgsList);
3802 
3804  &(DAG.getMachineFunction()), CC, Args);
3805  return *this;
3806  }
3807 
3809  SDValue Target, ArgListTy &&ArgsList) {
3810  RetTy = ResultType;
3811  Callee = Target;
3812  CallConv = CC;
3813  NumFixedArgs = ArgsList.size();
3814  Args = std::move(ArgsList);
3815  return *this;
3816  }
3817 
3819  SDValue Target, ArgListTy &&ArgsList,
3820  const CallBase &Call) {
3821  RetTy = ResultType;
3822 
3823  IsInReg = Call.hasRetAttr(Attribute::InReg);
3824  DoesNotReturn =
3825  Call.doesNotReturn() ||
3826  (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
3827  IsVarArg = FTy->isVarArg();
3828  IsReturnValueUsed = !Call.use_empty();
3829  RetSExt = Call.hasRetAttr(Attribute::SExt);
3830  RetZExt = Call.hasRetAttr(Attribute::ZExt);
3831  NoMerge = Call.hasFnAttr(Attribute::NoMerge);
3832 
3833  Callee = Target;
3834 
3835  CallConv = Call.getCallingConv();
3836  NumFixedArgs = FTy->getNumParams();
3837  Args = std::move(ArgsList);
3838 
3839  CB = &Call;
3840 
3841  return *this;
3842  }
3843 
3845  IsInReg = Value;
3846  return *this;
3847  }
3848 
3850  DoesNotReturn = Value;
3851  return *this;
3852  }
3853 
3855  IsVarArg = Value;
3856  return *this;
3857  }
3858 
3860  IsTailCall = Value;
3861  return *this;
3862  }
3863 
3866  return *this;
3867  }
3868 
3870  IsConvergent = Value;
3871  return *this;
3872  }
3873 
3875  RetSExt = Value;
3876  return *this;
3877  }
3878 
3880  RetZExt = Value;
3881  return *this;
3882  }
3883 
3885  IsPatchPoint = Value;
3886  return *this;
3887  }
3888 
3891  return *this;
3892  }
3893 
3896  return *this;
3897  }
3898 
3900  return Args;
3901  }
3902  };
3903 
3904  /// This structure is used to pass arguments to makeLibCall function.
3906  // By passing type list before soften to makeLibCall, the target hook
3907  // shouldExtendTypeInLibCall can get the original type before soften.
3910  bool IsSExt : 1;
3911  bool DoesNotReturn : 1;
3914  bool IsSoften : 1;
3915 
3919 
3921  IsSExt = Value;
3922  return *this;
3923  }
3924 
3926  DoesNotReturn = Value;
3927  return *this;
3928  }
3929 
3932  return *this;
3933  }
3934 
3937  return *this;
3938  }
3939 
3941  bool Value = true) {
3942  OpsVTBeforeSoften = OpsVT;
3943  RetVTBeforeSoften = RetVT;
3944  IsSoften = Value;
3945  return *this;
3946  }
3947  };
3948 
3949  /// This function lowers an abstract call to a function into an actual call.
3950  /// This returns a pair of operands. The first element is the return value
3951  /// for the function (if RetTy is not VoidTy). The second element is the
3952  /// outgoing token chain. It calls LowerCall to do the actual lowering.
3953  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3954 
3955  /// This hook must be implemented to lower calls into the specified
3956  /// DAG. The outgoing arguments to the call are described by the Outs array,
3957  /// and the values to be returned by the call are described by the Ins
3958  /// array. The implementation should fill in the InVals array with legal-type
3959  /// return values from the call, and return the resulting token chain value.
3960  virtual SDValue
3962  SmallVectorImpl<SDValue> &/*InVals*/) const {
3963  llvm_unreachable("Not Implemented");
3964  }
3965 
3966  /// Target-specific cleanup for formal ByVal parameters.
3967  virtual void HandleByVal(CCState *, unsigned &, Align) const {}
3968 
3969  /// This hook should be implemented to check whether the return values
3970  /// described by the Outs array can fit into the return registers. If false
3971  /// is returned, an sret-demotion is performed.
3972  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3973  MachineFunction &/*MF*/, bool /*isVarArg*/,
3974  const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3975  LLVMContext &/*Context*/) const
3976  {
3977  // Return true by default to get preexisting behavior.
3978  return true;
3979  }
3980 
3981  /// This hook must be implemented to lower outgoing return values, described
3982  /// by the Outs array, into the specified DAG. The implementation should
3983  /// return the resulting token chain value.
3984  virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3985  bool /*isVarArg*/,
3986  const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3987  const SmallVectorImpl<SDValue> & /*OutVals*/,
3988  const SDLoc & /*dl*/,
3989  SelectionDAG & /*DAG*/) const {
3990  llvm_unreachable("Not Implemented");
3991  }
3992 
3993  /// Return true if result of the specified node is used by a return node
3994  /// only. It also compute and return the input chain for the tail call.
3995  ///
3996  /// This is used to determine whether it is possible to codegen a libcall as
3997  /// tail call at legalization time.
3998  virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3999  return false;
4000  }
4001 
4002  /// Return true if the target may be able emit the call instruction as a tail
4003  /// call. This is used by optimization passes to determine if it's profitable
4004  /// to duplicate return instructions to enable tailcall optimization.
4005  virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
4006  return false;
4007  }
4008 
4009  /// Return the builtin name for the __builtin___clear_cache intrinsic
4010  /// Default is to invoke the clear cache library call
4011  virtual const char * getClearCacheBuiltinName() const {
4012  return "__clear_cache";
4013  }
4014 
4015  /// Return the register ID of the name passed in. Used by named register
4016  /// global variables extension. There is no target-independent behaviour
4017  /// so the default action is to bail.
4018  virtual Register getRegisterByName(const char* RegName, LLT Ty,
4019  const MachineFunction &MF) const {
4020  report_fatal_error("Named registers not implemented for this target");
4021  }
4022 
4023  /// Return the type that should be used to zero or sign extend a
4024  /// zeroext/signext integer return value. FIXME: Some C calling conventions
4025  /// require the return type to be promoted, but this is not true all the time,
4026  /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
4027  /// conventions. The frontend should handle this and include all of the
4028  /// necessary information.
4030  ISD::NodeType /*ExtendKind*/) const {
4031  EVT MinVT = getRegisterType(Context, MVT::i32);
4032  return VT.bitsLT(MinVT) ? MinVT : VT;
4033  }
4034 
4035  /// For some targets, an LLVM struct type must be broken down into multiple
4036  /// simple types, but the calling convention specifies that the entire struct
4037  /// must be passed in a block of consecutive registers.
4038  virtual bool
4040  bool isVarArg,
4041  const DataLayout &DL) const {
4042  return false;
4043  }
4044 
4045  /// For most targets, an LLVM type must be broken down into multiple
4046  /// smaller types. Usually the halves are ordered according to the endianness
4047  /// but for some platform that would break. So this method will default to
4048  /// matching the endianness but can be overridden.
4049  virtual bool
4051  return DL.isLittleEndian();
4052  }
4053 
4054  /// Returns a 0 terminated array of registers that can be safely used as
4055  /// scratch registers.
4056  virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
4057  return nullptr;
4058  }
4059 
4060  /// This callback is used to prepare for a volatile or atomic load.
4061  /// It takes a chain node as input and returns the chain for the load itself.
4062  ///
4063  /// Having a callback like this is necessary for targets like SystemZ,
4064  /// which allows a CPU to reuse the result of a previous load indefinitely,
4065  /// even if a cache-coherent store is performed by another CPU. The default
4066  /// implementation does nothing.
4068  SelectionDAG &DAG) const {
4069  return Chain;
4070  }
4071 
4072  /// Should SelectionDAG lower an atomic store of the given kind as a normal
4073  /// StoreSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
4074  /// eventually migrate all targets to the using StoreSDNodes, but porting is
4075  /// being done target at a time.
4076  virtual bool lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
4077  assert(SI.isAtomic() && "violated precondition");
4078  return false;
4079  }
4080 
4081  /// Should SelectionDAG lower an atomic load of the given kind as a normal
4082  /// LoadSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
4083  /// eventually migrate all targets to the using LoadSDNodes, but porting is
4084  /// being done target at a time.
4085  virtual bool lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
4086  assert(LI.isAtomic() && "violated precondition");
4087  return false;
4088  }
4089 
4090 
4091  /// This callback is invoked by the type legalizer to legalize nodes with an
4092  /// illegal operand type but legal result types. It replaces the
4093  /// LowerOperation callback in the type Legalizer. The reason we can not do
4094  /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
4095  /// use this callback.
4096  ///
4097  /// TODO: Consider merging with ReplaceNodeResults.
4098  ///
4099  /// The target places new result values for the node in Results (their number
4100  /// and types must exactly match those of the original return values of
4101  /// the node), or leaves Results empty, which indicates that the node is not
4102  /// to be custom lowered after all.
4103  /// The default implementation calls LowerOperation.
4104  virtual void LowerOperationWrapper(SDNode *N,
4106  SelectionDAG &DAG) const;
4107 
4108  /// This callback is invoked for operations that are unsupported by the
4109  /// target, which are registered to use 'custom' lowering, and whose defined
4110  /// values are all legal. If the target has no operations that require custom
4111  /// lowering, it need not implement this. The default implementation of this
4112  /// aborts.
4113  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
4114 
4115  /// This callback is invoked when a node result type is illegal for the
4116  /// target, and the operation was registered to use 'custom' lowering for that
4117  /// result type. The target places new result values for the node in Results
4118  /// (their number and types must exactly match those of the original return
4119  /// values of the node), or leaves Results empty, which indicates that the
4120  /// node is not to be custom lowered after all.
4121  ///
4122  /// If the target has no operations that require custom lowering, it need not
4123  /// implement this. The default implementation aborts.
4124  virtual void ReplaceNodeResults(SDNode * /*N*/,
4125  SmallVectorImpl<SDValue> &/*Results*/,
4126  SelectionDAG &/*DAG*/) const {
4127  llvm_unreachable("ReplaceNodeResults not implemented for this target!");
4128  }
4129 
4130  /// This method returns the name of a target specific DAG node.
4131  virtual const char *getTargetNodeName(unsigned Opcode) const;
4132 
4133  /// This method returns a target specific FastISel object, or null if the
4134  /// target does not support "fast" ISel.
4136  const TargetLibraryInfo *) const {
4137  return nullptr;
4138  }
4139 
4141  SelectionDAG &DAG) const;
4142 
4143  //===--------------------------------------------------------------------===//
4144  // Inline Asm Support hooks
4145  //
4146 
4147  /// This hook allows the target to expand an inline asm call to be explicit
4148  /// llvm code if it wants to. This is useful for turning simple inline asms
4149  /// into LLVM intrinsics, which gives the compiler more information about the
4150  /// behavior of the code.
4151  virtual bool ExpandInlineAsm(CallInst *) const {
4152  return false;
4153  }
4154 
4156  C_Register, // Constraint represents specific register(s).
4157  C_RegisterClass, // Constraint represents any of register(s) in class.
4158  C_Memory, // Memory constraint.
4159  C_Immediate, // Requires an immediate.
4160  C_Other, // Something else.
4161  C_Unknown // Unsupported constraint.
4162  };
4163 
4165  // Generic weights.
4166  CW_Invalid = -1, // No match.
4167  CW_Okay = 0, // Acceptable.
4168  CW_Good = 1, // Good weight.
4169  CW_Better = 2, // Better weight.
4170  CW_Best = 3, // Best weight.
4171 
4172  // Well-known weights.
4173  CW_SpecificReg = CW_Okay, // Specific register operands.
4174  CW_Register = CW_Good, // Register operands.
4175  CW_Memory = CW_Better, // Memory operands.
4176  CW_Constant = CW_Best, // Constant operand.
4177  CW_Default = CW_Okay // Default or don't know type.
4178  };
4179 
4180  /// This contains information for each constraint that we are lowering.
4182  /// This contains the actual string for the code, like "m". TargetLowering
4183  /// picks the 'best' code from ConstraintInfo::Codes that most closely
4184  /// matches the operand.
4185  std::string ConstraintCode;
4186 
4187  /// Information about the constraint code, e.g. Register, RegisterClass,
4188  /// Memory, Other, Unknown.
4190 
4191  /// If this is the result output operand or a clobber, this is null,
4192  /// otherwise it is the incoming operand to the CallInst. This gets
4193  /// modified as the asm is processed.
4194  Value *CallOperandVal = nullptr;
4195 
4196  /// The ValueType for the operand value.
4198 
4199  /// Copy constructor for copying from a ConstraintInfo.
4202 
4203  /// Return true of this is an input operand that is a matching constraint
4204  /// like "4".
4205  bool isMatchingInputConstraint() const;
4206 
4207  /// If this is an input matching constraint, this method returns the output
4208  /// operand it matches.
4209  unsigned getMatchedOperand() const;
4210  };
4211 
4212  using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
4213 
4214  /// Split up the constraint string from the inline assembly value into the
4215  /// specific constraints and their prefixes, and also tie in the associated
4216  /// operand values. If this returns an empty vector, and if the constraint
4217  /// string itself isn't empty, there was an error parsing.
4219  const TargetRegisterInfo *TRI,
4220  const CallBase &Call) const;
4221 
4222  /// Examine constraint type and operand type and determine a weight value.
4223  /// The operand object must already have been set up with the operand type.
4225  AsmOperandInfo &info, int maIndex) const;
4226 
4227  /// Examine constraint string and operand type and determine a weight value.
4228  /// The operand object must already have been set up with the operand type.
4230  AsmOperandInfo &info, const char *constraint) const;
4231 
4232  /// Determines the constraint code and constraint type to use for the specific
4233  /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4234  /// If the actual operand being passed in is available, it can be passed in as
4235  /// Op, otherwise an empty SDValue can be passed.
4236  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
4237  SDValue Op,
4238  SelectionDAG *DAG = nullptr) const;
4239 
4240  /// Given a constraint, return the type of constraint it is for this target.
4241  virtual ConstraintType getConstraintType(StringRef Constraint) const;
4242 
4243  /// Given a physical register constraint (e.g. {edx}), return the register
4244  /// number and the register class for the register.
4245  ///
4246  /// Given a register class constraint, like 'r', if this corresponds directly
4247  /// to an LLVM register class, return a register of 0 and the register class
4248  /// pointer.
4249  ///
4250  /// This should only be used for C_Register constraints. On error, this
4251  /// returns a register number of 0 and a null register class pointer.
4252  virtual std::pair<unsigned, const TargetRegisterClass *>
4254  StringRef Constraint, MVT VT) const;
4255 
4256  virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
4257  if (ConstraintCode == "m")
4258  return InlineAsm::Constraint_m;
4259  if (ConstraintCode == "o")
4260  return InlineAsm::Constraint_o;
4261  if (ConstraintCode == "X")
4262  return InlineAsm::Constraint_X;
4264  }
4265 
4266  /// Try to replace an X constraint, which matches anything, with another that
4267  /// has more specific requirements based on the type of the corresponding
4268  /// operand. This returns null if there is no replacement to make.
4269  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
4270 
4271  /// Lower the specified operand into the Ops vector. If it is invalid, don't
4272  /// add anything to Ops.
4273  virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
4274  std::vector<SDValue> &Ops,
4275  SelectionDAG &DAG) const;
4276 
4277  // Lower custom output constraints. If invalid, return SDValue().
4279  const SDLoc &DL,
4280  const AsmOperandInfo &OpInfo,
4281  SelectionDAG &DAG) const;
4282 
4283  //===--------------------------------------------------------------------===//
4284  // Div utility functions
4285  //
4286  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
4287  SmallVectorImpl<SDNode *> &Created) const;
4288  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
4289  SmallVectorImpl<SDNode *> &Created) const;
4290 
4291  /// Targets may override this function to provide custom SDIV lowering for
4292  /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
4293  /// assumes SDIV is expensive and replaces it with a series of other integer
4294  /// operations.
4295  virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
4296  SelectionDAG &DAG,
4297  SmallVectorImpl<SDNode *> &Created) const;
4298 
4299  /// Indicate whether this target prefers to combine FDIVs with the same
4300  /// divisor. If the transform should never be done, return zero. If the
4301  /// transform should be done, return the minimum number of divisor uses
4302  /// that must exist.
4303  virtual unsigned combineRepeatedFPDivisors() const {
4304  return 0;
4305  }
4306 
4307  /// Hooks for building estimates in place of slower divisions and square
4308  /// roots.
4309 
4310  /// Return either a square root or its reciprocal estimate value for the input
4311  /// operand.
4312  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
4313  /// 'Enabled' as set by a potential default override attribute.
4314  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
4315  /// refinement iterations required to generate a sufficient (though not
4316  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
4317  /// The boolean UseOneConstNR output is used to select a Newton-Raphson
4318  /// algorithm implementation that uses either one or two constants.
4319  /// The boolean Reciprocal is used to select whether the estimate is for the
4320  /// square root of the input operand or the reciprocal of its square root.
4321  /// A target may choose to implement its own refinement within this function.
4322  /// If that's true, then return '0' as the number of RefinementSteps to avoid
4323  /// any further refinement of the estimate.
4324  /// An empty SDValue return means no estimate sequence can be created.
4326  int Enabled, int &RefinementSteps,
4327  bool &UseOneConstNR, bool Reciprocal) const {
4328  return SDValue();
4329  }
4330 
4331  /// Return a reciprocal estimate value for the input operand.
4332  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
4333  /// 'Enabled' as set by a potential default override attribute.
4334  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
4335  /// refinement iterations required to generate a sufficient (though not
4336  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
4337  /// A target may choose to implement its own refinement within this function.
4338  /// If that's true, then return '0' as the number of RefinementSteps to avoid
4339  /// any further refinement of the estimate.
4340  /// An empty SDValue return means no estimate sequence can be created.
4342  int Enabled, int &RefinementSteps) const {
4343  return SDValue();
4344  }
4345 
4346  /// Return a target-dependent comparison result if the input operand is
4347  /// suitable for use with a square root estimate calculation. For example, the
4348  /// comparison may check if the operand is NAN, INF, zero, normal, etc. The
4349  /// result should be used as the condition operand for a select or branch.
4350  virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG,
4351  const DenormalMode &Mode) const;
4352 
4353  /// Return a target-dependent result if the input operand is not suitable for
4354  /// use with a square root estimate calculation.
4356  SelectionDAG &DAG) const {
4357  return DAG.getConstantFP(0.0, SDLoc(Operand), Operand.getValueType());
4358  }
4359 
4360  //===--------------------------------------------------------------------===//
4361  // Legalization utility functions
4362  //
4363 
4364  /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
4365  /// respectively, each computing an n/2-bit part of the result.
4366  /// \param Result A vector that will be filled with the parts of the result
4367  /// in little-endian order.
4368  /// \param LL Low bits of the LHS of the MUL. You can use this parameter
4369  /// if you want to control how low bits are extracted from the LHS.
4370  /// \param LH High bits of the LHS of the MUL. See LL for meaning.
4371  /// \param RL Low bits of the RHS of the MUL. See LL for meaning
4372  /// \param RH High bits of the RHS of the MUL. See LL for meaning.
4373  /// \returns true if the node has been expanded, false if it has not
4374  bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS,
4375  SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
4377  SDValue LL = SDValue(), SDValue LH = SDValue(),
4378  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
4379 
4380  /// Expand a MUL into two nodes. One that computes the high bits of
4381  /// the result and one that computes the low bits.
4382  /// \param HiLoVT The value type to use for the Lo and Hi nodes.
4383  /// \param LL Low bits of the LHS of the MUL. You can use this parameter
4384  /// if you want to control how low bits are extracted from the LHS.
4385  /// \param LH High bits of the LHS of the MUL. See LL for meaning.
4386  /// \param RL Low bits of the RHS of the MUL. See LL for meaning
4387  /// \param RH High bits of the RHS of the MUL. See LL for meaning.
4388  /// \returns true if the node has been expanded. false if it has not
4389  bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
4391  SDValue LL = SDValue(), SDValue LH = SDValue(),
4392  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
4393 
4394  /// Expand funnel shift.
4395  /// \param N Node to expand
4396  /// \param Result output after conversion
4397  /// \returns True, if the expansion was successful, false otherwise
4398  bool expandFunnelShift(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4399 
4400  /// Expand rotations.
4401  /// \param N Node to expand
4402  /// \param AllowVectorOps expand vector rotate, this should only be performed
4403  /// if the legalization is happening outside of LegalizeVectorOps
4404  /// \param Result output after conversion
4405  /// \returns True, if the expansion was successful, false otherwise
4406  bool expandROT(SDNode *N, bool AllowVectorOps, SDValue &Result,
4407  SelectionDAG &DAG) const;
4408 
4409  /// Expand shift-by-parts.
4410  /// \param N Node to expand
4411  /// \param Lo lower-output-part after conversion
4412  /// \param Hi upper-output-part after conversion
4414  SelectionDAG &DAG) const;
4415 
4416  /// Expand float(f32) to SINT(i64) conversion
4417  /// \param N Node to expand
4418  /// \param Result output after conversion
4419  /// \returns True, if the expansion was successful, false otherwise
4420  bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4421 
4422  /// Expand float to UINT conversion
4423  /// \param N Node to expand
4424  /// \param Result output after conversion
4425  /// \param Chain output chain after conversion
4426  /// \returns True, if the expansion was successful, false otherwise
4427  bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain,
4428  SelectionDAG &DAG) const;
4429 
4430  /// Expand UINT(i64) to double(f64) conversion
4431  /// \param N Node to expand
4432  /// \param Result output after conversion
4433  /// \param Chain output chain after conversion
4434  /// \returns True, if the expansion was successful, false otherwise
4435  bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain,
4436  SelectionDAG &DAG) const;
4437 
4438  /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
4440 
4441  /// Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
4442  /// \param N Node to expand
4443  /// \returns The expansion result
4445 
4446  /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
4447  /// vector nodes can only succeed if all operations are legal/custom.
4448  /// \param N Node to expand
4449  /// \returns The expansion result or SDValue() if it fails.
4450  SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const;
4451 
4452  /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
4453  /// vector nodes can only succeed if all operations are legal/custom.
4454  /// \param N Node to expand
4455  /// \returns The expansion result or SDValue() if it fails.
4456  SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const;
4457 
4458  /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
4459  /// vector nodes can only succeed if all operations are legal/custom.
4460  /// \param N Node to expand
4461  /// \returns The expansion result or SDValue() if it fails.
4462  SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const;
4463 
4464  /// Expand ABS nodes. Expands vector/scalar ABS nodes,
4465  /// vector nodes can only succeed if all operations are legal/custom.
4466  /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
4467  /// \param N Node to expand
4468  /// \param IsNegative indicate negated abs
4469  /// \returns The expansion result or SDValue() if it fails.
4471  bool IsNegative = false) const;
4472 
4473  /// Expand BSWAP nodes. Expands scalar/vector BSWAP nodes with i16/i32/i64
4474  /// scalar types. Returns SDValue() if expand fails.
4475  /// \param N Node to expand
4476  /// \returns The expansion result or SDValue() if it fails.
4477  SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const;
4478 
4479  /// Expand BITREVERSE nodes. Expands scalar/vector BITREVERSE nodes.
4480  /// Returns SDValue() if expand fails.
4481  /// \param N Node to expand
4482  /// \returns The expansion result or SDValue() if it fails.
4484 
4485  /// Turn load of vector type into a load of the individual elements.
4486  /// \param LD load to expand
4487  /// \returns BUILD_VECTOR and TokenFactor nodes.
4488  std::pair<SDValue, SDValue> scalarizeVectorLoad(LoadSDNode *LD,
4489  SelectionDAG &DAG) const;
4490 
4491  // Turn a store of a vector type into stores of the individual elements.
4492  /// \param ST Store with a vector value type
4493  /// \returns TokenFactor of the individual store chains.
4495 
4496  /// Expands an unaligned load to 2 half-size loads for an integer, and
4497  /// possibly more for vectors.
4498  std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
4499  SelectionDAG &DAG) const;
4500 
4501  /// Expands an unaligned store to 2 half-size stores for integer values, and
4502  /// possibly more for vectors.
4504 
4505  /// Increments memory address \p Addr according to the type of the value
4506  /// \p DataVT that should be stored. If the data is stored in compressed
4507  /// form, the memory address should be incremented according to the number of
4508  /// the stored elements. This number is equal to the number of '1's bits
4509  /// in the \p Mask.
4510  /// \p DataVT is a vector type. \p Mask is a vector value.
4511  /// \p DataVT and \p Mask have the same number of vector elements.
4513  EVT DataVT, SelectionDAG &DAG,
4514  bool IsCompressedMemory) const;
4515 
4516  /// Get a pointer to vector element \p Idx located in memory for a vector of
4517  /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
4518  /// bounds the returned pointer is unspecified, but will be within the vector
4519  /// bounds.
4521  SDValue Index) const;
4522 
4523  /// Get a pointer to a sub-vector of type \p SubVecVT at index \p Idx located
4524  /// in memory for a vector of type \p VecVT starting at a base address of
4525  /// \p VecPtr. If \p Idx plus the size of \p SubVecVT is out of bounds the
4526  /// returned pointer is unspecified, but the value returned will be such that
4527  /// the entire subvector would be within the vector bounds.
4529  EVT SubVecVT, SDValue Index) const;
4530 
4531  /// Method for building the DAG expansion of ISD::[US][MIN|MAX]. This
4532  /// method accepts integers as its arguments.
4534 
4535  /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
4536  /// method accepts integers as its arguments.
4538 
4539  /// Method for building the DAG expansion of ISD::[US]SHLSAT. This
4540  /// method accepts integers as its arguments.
4542 
4543  /// Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT]. This
4544  /// method accepts integers as its arguments.
4546 
4547  /// Method for building the DAG expansion of ISD::[US]DIVFIX[SAT]. This
4548  /// method accepts integers as its arguments.
4549  /// Note: This method may fail if the division could not be performed
4550  /// within the type. Clients must retry with a wider type if this happens.
4551  SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
4552  SDValue LHS, SDValue RHS,
4553  unsigned Scale,