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