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