Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:38

0001 //==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- C++ -*-==//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file describes an abstract interface used to get information about a
0010 // target machines register file.  This information is used for a variety of
0011 // purposed, especially register allocation.
0012 //
0013 //===----------------------------------------------------------------------===//
0014 
0015 #ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H
0016 #define LLVM_CODEGEN_TARGETREGISTERINFO_H
0017 
0018 #include "llvm/ADT/ArrayRef.h"
0019 #include "llvm/ADT/SmallVector.h"
0020 #include "llvm/ADT/StringRef.h"
0021 #include "llvm/ADT/iterator_range.h"
0022 #include "llvm/CodeGen/MachineBasicBlock.h"
0023 #include "llvm/CodeGen/RegisterBank.h"
0024 #include "llvm/IR/CallingConv.h"
0025 #include "llvm/MC/LaneBitmask.h"
0026 #include "llvm/MC/MCRegisterInfo.h"
0027 #include "llvm/Support/ErrorHandling.h"
0028 #include "llvm/Support/MathExtras.h"
0029 #include "llvm/Support/Printable.h"
0030 #include <cassert>
0031 #include <cstdint>
0032 
0033 namespace llvm {
0034 
0035 class BitVector;
0036 class DIExpression;
0037 class LiveRegMatrix;
0038 class MachineFunction;
0039 class MachineInstr;
0040 class RegScavenger;
0041 class VirtRegMap;
0042 class LiveIntervals;
0043 class LiveInterval;
0044 class TargetRegisterClass {
0045 public:
0046   using iterator = const MCPhysReg *;
0047   using const_iterator = const MCPhysReg *;
0048 
0049   // Instance variables filled by tablegen, do not use!
0050   const MCRegisterClass *MC;
0051   const uint32_t *SubClassMask;
0052   const uint16_t *SuperRegIndices;
0053   const LaneBitmask LaneMask;
0054   /// Classes with a higher priority value are assigned first by register
0055   /// allocators using a greedy heuristic. The value is in the range [0,31].
0056   const uint8_t AllocationPriority;
0057 
0058   // Change allocation priority heuristic used by greedy.
0059   const bool GlobalPriority;
0060 
0061   /// Configurable target specific flags.
0062   const uint8_t TSFlags;
0063   /// Whether the class supports two (or more) disjunct subregister indices.
0064   const bool HasDisjunctSubRegs;
0065   /// Whether a combination of subregisters can cover every register in the
0066   /// class. See also the CoveredBySubRegs description in Target.td.
0067   const bool CoveredBySubRegs;
0068   const unsigned *SuperClasses;
0069   const uint16_t SuperClassesSize;
0070   ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&);
0071 
0072   /// Return the register class ID number.
0073   unsigned getID() const { return MC->getID(); }
0074 
0075   /// begin/end - Return all of the registers in this class.
0076   ///
0077   iterator       begin() const { return MC->begin(); }
0078   iterator         end() const { return MC->end(); }
0079 
0080   /// Return the number of registers in this class.
0081   unsigned getNumRegs() const { return MC->getNumRegs(); }
0082 
0083   ArrayRef<MCPhysReg> getRegisters() const {
0084     return ArrayRef(begin(), getNumRegs());
0085   }
0086 
0087   /// Return the specified register in the class.
0088   MCRegister getRegister(unsigned i) const {
0089     return MC->getRegister(i);
0090   }
0091 
0092   /// Return true if the specified register is included in this register class.
0093   /// This does not include virtual registers.
0094   bool contains(Register Reg) const {
0095     /// FIXME: Historically this function has returned false when given vregs
0096     ///        but it should probably only receive physical registers
0097     if (!Reg.isPhysical())
0098       return false;
0099     return MC->contains(Reg.asMCReg());
0100   }
0101 
0102   /// Return true if both registers are in this class.
0103   bool contains(Register Reg1, Register Reg2) const {
0104     /// FIXME: Historically this function has returned false when given a vregs
0105     ///        but it should probably only receive physical registers
0106     if (!Reg1.isPhysical() || !Reg2.isPhysical())
0107       return false;
0108     return MC->contains(Reg1.asMCReg(), Reg2.asMCReg());
0109   }
0110 
0111   /// Return the cost of copying a value between two registers in this class.
0112   /// A negative number means the register class is very expensive
0113   /// to copy e.g. status flag register classes.
0114   int getCopyCost() const { return MC->getCopyCost(); }
0115 
0116   /// Return true if this register class may be used to create virtual
0117   /// registers.
0118   bool isAllocatable() const { return MC->isAllocatable(); }
0119 
0120   /// Return true if this register class has a defined BaseClassOrder.
0121   bool isBaseClass() const { return MC->isBaseClass(); }
0122 
0123   /// Return true if the specified TargetRegisterClass
0124   /// is a proper sub-class of this TargetRegisterClass.
0125   bool hasSubClass(const TargetRegisterClass *RC) const {
0126     return RC != this && hasSubClassEq(RC);
0127   }
0128 
0129   /// Returns true if RC is a sub-class of or equal to this class.
0130   bool hasSubClassEq(const TargetRegisterClass *RC) const {
0131     unsigned ID = RC->getID();
0132     return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
0133   }
0134 
0135   /// Return true if the specified TargetRegisterClass is a
0136   /// proper super-class of this TargetRegisterClass.
0137   bool hasSuperClass(const TargetRegisterClass *RC) const {
0138     return RC->hasSubClass(this);
0139   }
0140 
0141   /// Returns true if RC is a super-class of or equal to this class.
0142   bool hasSuperClassEq(const TargetRegisterClass *RC) const {
0143     return RC->hasSubClassEq(this);
0144   }
0145 
0146   /// Returns a bit vector of subclasses, including this one.
0147   /// The vector is indexed by class IDs.
0148   ///
0149   /// To use it, consider the returned array as a chunk of memory that
0150   /// contains an array of bits of size NumRegClasses. Each 32-bit chunk
0151   /// contains a bitset of the ID of the subclasses in big-endian style.
0152 
0153   /// I.e., the representation of the memory from left to right at the
0154   /// bit level looks like:
0155   /// [31 30 ... 1 0] [ 63 62 ... 33 32] ...
0156   ///                     [ XXX NumRegClasses NumRegClasses - 1 ... ]
0157   /// Where the number represents the class ID and XXX bits that
0158   /// should be ignored.
0159   ///
0160   /// See the implementation of hasSubClassEq for an example of how it
0161   /// can be used.
0162   const uint32_t *getSubClassMask() const {
0163     return SubClassMask;
0164   }
0165 
0166   /// Returns a 0-terminated list of sub-register indices that project some
0167   /// super-register class into this register class. The list has an entry for
0168   /// each Idx such that:
0169   ///
0170   ///   There exists SuperRC where:
0171   ///     For all Reg in SuperRC:
0172   ///       this->contains(Reg:Idx)
0173   const uint16_t *getSuperRegIndices() const {
0174     return SuperRegIndices;
0175   }
0176 
0177   /// Returns a list of super-classes.  The
0178   /// classes are ordered by ID which is also a topological ordering from large
0179   /// to small classes.  The list does NOT include the current class.
0180   ArrayRef<unsigned> superclasses() const {
0181     return ArrayRef(SuperClasses, SuperClassesSize);
0182   }
0183 
0184   /// Return true if this TargetRegisterClass is a subset
0185   /// class of at least one other TargetRegisterClass.
0186   bool isASubClass() const { return SuperClasses != nullptr; }
0187 
0188   /// Returns the preferred order for allocating registers from this register
0189   /// class in MF. The raw order comes directly from the .td file and may
0190   /// include reserved registers that are not allocatable.
0191   /// Register allocators should also make sure to allocate
0192   /// callee-saved registers only after all the volatiles are used. The
0193   /// RegisterClassInfo class provides filtered allocation orders with
0194   /// callee-saved registers moved to the end.
0195   ///
0196   /// The MachineFunction argument can be used to tune the allocatable
0197   /// registers based on the characteristics of the function, subtarget, or
0198   /// other criteria.
0199   ///
0200   /// By default, this method returns all registers in the class.
0201   ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const {
0202     return OrderFunc ? OrderFunc(MF) : getRegisters();
0203   }
0204 
0205   /// Returns the combination of all lane masks of register in this class.
0206   /// The lane masks of the registers are the combination of all lane masks
0207   /// of their subregisters. Returns 1 if there are no subregisters.
0208   LaneBitmask getLaneMask() const {
0209     return LaneMask;
0210   }
0211 };
0212 
0213 /// Extra information, not in MCRegisterDesc, about registers.
0214 /// These are used by codegen, not by MC.
0215 struct TargetRegisterInfoDesc {
0216   const uint8_t *CostPerUse; // Extra cost of instructions using register.
0217   unsigned NumCosts; // Number of cost values associated with each register.
0218   const bool
0219       *InAllocatableClass; // Register belongs to an allocatable regclass.
0220 };
0221 
0222 /// Each TargetRegisterClass has a per register weight, and weight
0223 /// limit which must be less than the limits of its pressure sets.
0224 struct RegClassWeight {
0225   unsigned RegWeight;
0226   unsigned WeightLimit;
0227 };
0228 
0229 /// TargetRegisterInfo base class - We assume that the target defines a static
0230 /// array of TargetRegisterDesc objects that represent all of the machine
0231 /// registers that the target has.  As such, we simply have to track a pointer
0232 /// to this array so that we can turn register number into a register
0233 /// descriptor.
0234 ///
0235 class TargetRegisterInfo : public MCRegisterInfo {
0236 public:
0237   using regclass_iterator = const TargetRegisterClass * const *;
0238   using vt_iterator = const MVT::SimpleValueType *;
0239   struct RegClassInfo {
0240     unsigned RegSize, SpillSize, SpillAlignment;
0241     unsigned VTListOffset;
0242   };
0243 
0244   /// SubRegCoveredBits - Emitted by tablegen: bit range covered by a subreg
0245   /// index, -1 in any being invalid.
0246   struct SubRegCoveredBits {
0247     uint16_t Offset;
0248     uint16_t Size;
0249   };
0250 
0251 private:
0252   const TargetRegisterInfoDesc *InfoDesc;     // Extra desc array for codegen
0253   const char *const *SubRegIndexNames;        // Names of subreg indexes.
0254   const SubRegCoveredBits *SubRegIdxRanges;   // Pointer to the subreg covered
0255                                               // bit ranges array.
0256 
0257   // Pointer to array of lane masks, one per sub-reg index.
0258   const LaneBitmask *SubRegIndexLaneMasks;
0259 
0260   regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
0261   LaneBitmask CoveringLanes;
0262   const RegClassInfo *const RCInfos;
0263   const MVT::SimpleValueType *const RCVTLists;
0264   unsigned HwMode;
0265 
0266 protected:
0267   TargetRegisterInfo(const TargetRegisterInfoDesc *ID, regclass_iterator RCB,
0268                      regclass_iterator RCE, const char *const *SRINames,
0269                      const SubRegCoveredBits *SubIdxRanges,
0270                      const LaneBitmask *SRILaneMasks, LaneBitmask CoveringLanes,
0271                      const RegClassInfo *const RCIs,
0272                      const MVT::SimpleValueType *const RCVTLists,
0273                      unsigned Mode = 0);
0274   virtual ~TargetRegisterInfo();
0275 
0276 public:
0277   /// Return the number of registers for the function. (may overestimate)
0278   virtual unsigned getNumSupportedRegs(const MachineFunction &) const {
0279     return getNumRegs();
0280   }
0281 
0282   // Register numbers can represent physical registers, virtual registers, and
0283   // sometimes stack slots. The unsigned values are divided into these ranges:
0284   //
0285   //   0           Not a register, can be used as a sentinel.
0286   //   [1;2^30)    Physical registers assigned by TableGen.
0287   //   [2^30;2^31) Stack slots. (Rarely used.)
0288   //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
0289   //
0290   // Further sentinels can be allocated from the small negative integers.
0291   // DenseMapInfo<unsigned> uses -1u and -2u.
0292 
0293   /// Return the size in bits of a register from class RC.
0294   TypeSize getRegSizeInBits(const TargetRegisterClass &RC) const {
0295     return TypeSize::getFixed(getRegClassInfo(RC).RegSize);
0296   }
0297 
0298   /// Return the size in bytes of the stack slot allocated to hold a spilled
0299   /// copy of a register from class RC.
0300   unsigned getSpillSize(const TargetRegisterClass &RC) const {
0301     return getRegClassInfo(RC).SpillSize / 8;
0302   }
0303 
0304   /// Return the minimum required alignment in bytes for a spill slot for
0305   /// a register of this class.
0306   Align getSpillAlign(const TargetRegisterClass &RC) const {
0307     return Align(getRegClassInfo(RC).SpillAlignment / 8);
0308   }
0309 
0310   /// Return true if the given TargetRegisterClass has the ValueType T.
0311   bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const {
0312     for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I)
0313       if (MVT(*I) == T)
0314         return true;
0315     return false;
0316   }
0317 
0318   /// Return true if the given TargetRegisterClass is compatible with LLT T.
0319   bool isTypeLegalForClass(const TargetRegisterClass &RC, LLT T) const {
0320     for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I) {
0321       MVT VT(*I);
0322       if (VT == MVT::Untyped)
0323         return true;
0324 
0325       if (LLT(VT) == T)
0326         return true;
0327     }
0328     return false;
0329   }
0330 
0331   /// Loop over all of the value types that can be represented by values
0332   /// in the given register class.
0333   vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const {
0334     return &RCVTLists[getRegClassInfo(RC).VTListOffset];
0335   }
0336 
0337   vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const {
0338     vt_iterator I = legalclasstypes_begin(RC);
0339     while (*I != MVT::Other)
0340       ++I;
0341     return I;
0342   }
0343 
0344   /// Returns the Register Class of a physical register of the given type,
0345   /// picking the most sub register class of the right type that contains this
0346   /// physreg.
0347   const TargetRegisterClass *getMinimalPhysRegClass(MCRegister Reg,
0348                                                     MVT VT = MVT::Other) const;
0349 
0350   /// Returns the common Register Class of two physical registers of the given
0351   /// type, picking the most sub register class of the right type that contains
0352   /// these two physregs.
0353   const TargetRegisterClass *
0354   getCommonMinimalPhysRegClass(MCRegister Reg1, MCRegister Reg2,
0355                                MVT VT = MVT::Other) const;
0356 
0357   /// Returns the Register Class of a physical register of the given type,
0358   /// picking the most sub register class of the right type that contains this
0359   /// physreg. If there is no register class compatible with the given type,
0360   /// returns nullptr.
0361   const TargetRegisterClass *getMinimalPhysRegClassLLT(MCRegister Reg,
0362                                                        LLT Ty = LLT()) const;
0363 
0364   /// Returns the common Register Class of two physical registers of the given
0365   /// type, picking the most sub register class of the right type that contains
0366   /// these two physregs. If there is no register class compatible with the
0367   /// given type, returns nullptr.
0368   const TargetRegisterClass *
0369   getCommonMinimalPhysRegClassLLT(MCRegister Reg1, MCRegister Reg2,
0370                                   LLT Ty = LLT()) const;
0371 
0372   /// Return the maximal subclass of the given register class that is
0373   /// allocatable or NULL.
0374   const TargetRegisterClass *
0375     getAllocatableClass(const TargetRegisterClass *RC) const;
0376 
0377   /// Returns a bitset indexed by register number indicating if a register is
0378   /// allocatable or not. If a register class is specified, returns the subset
0379   /// for the class.
0380   BitVector getAllocatableSet(const MachineFunction &MF,
0381                               const TargetRegisterClass *RC = nullptr) const;
0382 
0383   /// Get a list of cost values for all registers that correspond to the index
0384   /// returned by RegisterCostTableIndex.
0385   ArrayRef<uint8_t> getRegisterCosts(const MachineFunction &MF) const {
0386     unsigned Idx = getRegisterCostTableIndex(MF);
0387     unsigned NumRegs = getNumRegs();
0388     assert(Idx < InfoDesc->NumCosts && "CostPerUse index out of bounds");
0389 
0390     return ArrayRef(&InfoDesc->CostPerUse[Idx * NumRegs], NumRegs);
0391   }
0392 
0393   /// Return true if the register is in the allocation of any register class.
0394   bool isInAllocatableClass(MCRegister RegNo) const {
0395     return InfoDesc->InAllocatableClass[RegNo];
0396   }
0397 
0398   /// Return the human-readable symbolic target-specific
0399   /// name for the specified SubRegIndex.
0400   const char *getSubRegIndexName(unsigned SubIdx) const {
0401     assert(SubIdx && SubIdx < getNumSubRegIndices() &&
0402            "This is not a subregister index");
0403     return SubRegIndexNames[SubIdx-1];
0404   }
0405 
0406   /// Get the size of the bit range covered by a sub-register index.
0407   /// If the index isn't continuous, return the sum of the sizes of its parts.
0408   /// If the index is used to access subregisters of different sizes, return -1.
0409   unsigned getSubRegIdxSize(unsigned Idx) const;
0410 
0411   /// Get the offset of the bit range covered by a sub-register index.
0412   /// If an Offset doesn't make sense (the index isn't continuous, or is used to
0413   /// access sub-registers at different offsets), return -1.
0414   unsigned getSubRegIdxOffset(unsigned Idx) const;
0415 
0416   /// Return a bitmask representing the parts of a register that are covered by
0417   /// SubIdx \see LaneBitmask.
0418   ///
0419   /// SubIdx == 0 is allowed, it has the lane mask ~0u.
0420   LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const {
0421     assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
0422     return SubRegIndexLaneMasks[SubIdx];
0423   }
0424 
0425   /// Try to find one or more subregister indexes to cover \p LaneMask.
0426   ///
0427   /// If this is possible, returns true and appends the best matching set of
0428   /// indexes to \p Indexes. If this is not possible, returns false.
0429   bool getCoveringSubRegIndexes(const TargetRegisterClass *RC,
0430                                 LaneBitmask LaneMask,
0431                                 SmallVectorImpl<unsigned> &Indexes) const;
0432 
0433   /// The lane masks returned by getSubRegIndexLaneMask() above can only be
0434   /// used to determine if sub-registers overlap - they can't be used to
0435   /// determine if a set of sub-registers completely cover another
0436   /// sub-register.
0437   ///
0438   /// The X86 general purpose registers have two lanes corresponding to the
0439   /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
0440   /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
0441   /// sub_32bit sub-register.
0442   ///
0443   /// On the other hand, the ARM NEON lanes fully cover their registers: The
0444   /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
0445   /// This is related to the CoveredBySubRegs property on register definitions.
0446   ///
0447   /// This function returns a bit mask of lanes that completely cover their
0448   /// sub-registers. More precisely, given:
0449   ///
0450   ///   Covering = getCoveringLanes();
0451   ///   MaskA = getSubRegIndexLaneMask(SubA);
0452   ///   MaskB = getSubRegIndexLaneMask(SubB);
0453   ///
0454   /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
0455   /// SubB.
0456   LaneBitmask getCoveringLanes() const { return CoveringLanes; }
0457 
0458   /// Returns true if the two registers are equal or alias each other.
0459   /// The registers may be virtual registers.
0460   bool regsOverlap(Register RegA, Register RegB) const {
0461     if (RegA == RegB)
0462       return true;
0463     if (RegA.isPhysical() && RegB.isPhysical())
0464       return MCRegisterInfo::regsOverlap(RegA.asMCReg(), RegB.asMCReg());
0465     return false;
0466   }
0467 
0468   /// Returns true if Reg contains RegUnit.
0469   bool hasRegUnit(MCRegister Reg, MCRegUnit RegUnit) const {
0470     for (MCRegUnit Unit : regunits(Reg))
0471       if (Unit == RegUnit)
0472         return true;
0473     return false;
0474   }
0475 
0476   /// Returns the original SrcReg unless it is the target of a copy-like
0477   /// operation, in which case we chain backwards through all such operations
0478   /// to the ultimate source register.  If a physical register is encountered,
0479   /// we stop the search.
0480   virtual Register lookThruCopyLike(Register SrcReg,
0481                                     const MachineRegisterInfo *MRI) const;
0482 
0483   /// Find the original SrcReg unless it is the target of a copy-like operation,
0484   /// in which case we chain backwards through all such operations to the
0485   /// ultimate source register. If a physical register is encountered, we stop
0486   /// the search.
0487   /// Return the original SrcReg if all the definitions in the chain only have
0488   /// one user and not a physical register.
0489   virtual Register
0490   lookThruSingleUseCopyChain(Register SrcReg,
0491                              const MachineRegisterInfo *MRI) const;
0492 
0493   /// Return a null-terminated list of all of the callee-saved registers on
0494   /// this target. The register should be in the order of desired callee-save
0495   /// stack frame offset. The first register is closest to the incoming stack
0496   /// pointer if stack grows down, and vice versa.
0497   /// Notice: This function does not take into account disabled CSRs.
0498   ///         In most cases you will want to use instead the function
0499   ///         getCalleeSavedRegs that is implemented in MachineRegisterInfo.
0500   virtual const MCPhysReg*
0501   getCalleeSavedRegs(const MachineFunction *MF) const = 0;
0502 
0503   /// Return a null-terminated list of all of the callee-saved registers on
0504   /// this target when IPRA is on. The list should include any non-allocatable
0505   /// registers that the backend uses and assumes will be saved by all calling
0506   /// conventions. This is typically the ISA-standard frame pointer, but could
0507   /// include the thread pointer, TOC pointer, or base pointer for different
0508   /// targets.
0509   virtual const MCPhysReg *getIPRACSRegs(const MachineFunction *MF) const {
0510     return nullptr;
0511   }
0512 
0513   /// Return a mask of call-preserved registers for the given calling convention
0514   /// on the current function. The mask should include all call-preserved
0515   /// aliases. This is used by the register allocator to determine which
0516   /// registers can be live across a call.
0517   ///
0518   /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
0519   /// A set bit indicates that all bits of the corresponding register are
0520   /// preserved across the function call.  The bit mask is expected to be
0521   /// sub-register complete, i.e. if A is preserved, so are all its
0522   /// sub-registers.
0523   ///
0524   /// Bits are numbered from the LSB, so the bit for physical register Reg can
0525   /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
0526   ///
0527   /// A NULL pointer means that no register mask will be used, and call
0528   /// instructions should use implicit-def operands to indicate call clobbered
0529   /// registers.
0530   ///
0531   virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
0532                                                CallingConv::ID) const {
0533     // The default mask clobbers everything.  All targets should override.
0534     return nullptr;
0535   }
0536 
0537   /// Return a register mask for the registers preserved by the unwinder,
0538   /// or nullptr if no custom mask is needed.
0539   virtual const uint32_t *
0540   getCustomEHPadPreservedMask(const MachineFunction &MF) const {
0541     return nullptr;
0542   }
0543 
0544   /// Return a register mask that clobbers everything.
0545   virtual const uint32_t *getNoPreservedMask() const {
0546     llvm_unreachable("target does not provide no preserved mask");
0547   }
0548 
0549   /// Return a list of all of the registers which are clobbered "inside" a call
0550   /// to the given function. For example, these might be needed for PLT
0551   /// sequences of long-branch veneers.
0552   virtual ArrayRef<MCPhysReg>
0553   getIntraCallClobberedRegs(const MachineFunction *MF) const {
0554     return {};
0555   }
0556 
0557   /// Return true if all bits that are set in mask \p mask0 are also set in
0558   /// \p mask1.
0559   bool regmaskSubsetEqual(const uint32_t *mask0, const uint32_t *mask1) const;
0560 
0561   /// Return all the call-preserved register masks defined for this target.
0562   virtual ArrayRef<const uint32_t *> getRegMasks() const = 0;
0563   virtual ArrayRef<const char *> getRegMaskNames() const = 0;
0564 
0565   /// Returns a bitset indexed by physical register number indicating if a
0566   /// register is a special register that has particular uses and should be
0567   /// considered unavailable at all times, e.g. stack pointer, return address.
0568   /// A reserved register:
0569   /// - is not allocatable
0570   /// - is considered always live
0571   /// - is ignored by liveness tracking
0572   /// It is often necessary to reserve the super registers of a reserved
0573   /// register as well, to avoid them getting allocated indirectly. You may use
0574   /// markSuperRegs() and checkAllSuperRegsMarked() in this case.
0575   virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
0576 
0577   /// Returns either a string explaining why the given register is reserved for
0578   /// this function, or an empty optional if no explanation has been written.
0579   /// The absence of an explanation does not mean that the register is not
0580   /// reserved (meaning, you should check that PhysReg is in fact reserved
0581   /// before calling this).
0582   virtual std::optional<std::string>
0583   explainReservedReg(const MachineFunction &MF, MCRegister PhysReg) const {
0584     return {};
0585   }
0586 
0587   /// Returns false if we can't guarantee that Physreg, specified as an IR asm
0588   /// clobber constraint, will be preserved across the statement.
0589   virtual bool isAsmClobberable(const MachineFunction &MF,
0590                                 MCRegister PhysReg) const {
0591     return true;
0592   }
0593 
0594   /// Returns true if PhysReg cannot be written to in inline asm statements.
0595   virtual bool isInlineAsmReadOnlyReg(const MachineFunction &MF,
0596                                       unsigned PhysReg) const {
0597     return false;
0598   }
0599 
0600   /// Returns true if PhysReg is unallocatable and constant throughout the
0601   /// function.  Used by MachineRegisterInfo::isConstantPhysReg().
0602   virtual bool isConstantPhysReg(MCRegister PhysReg) const { return false; }
0603 
0604   /// Returns true if the register class is considered divergent.
0605   virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const {
0606     return false;
0607   }
0608 
0609   /// Returns true if the register is considered uniform.
0610   virtual bool isUniformReg(const MachineRegisterInfo &MRI,
0611                             const RegisterBankInfo &RBI, Register Reg) const {
0612     return false;
0613   }
0614 
0615   /// Returns true if MachineLoopInfo should analyze the given physreg
0616   /// for loop invariance.
0617   virtual bool shouldAnalyzePhysregInMachineLoopInfo(MCRegister R) const {
0618     return false;
0619   }
0620 
0621   /// Physical registers that may be modified within a function but are
0622   /// guaranteed to be restored before any uses. This is useful for targets that
0623   /// have call sequences where a GOT register may be updated by the caller
0624   /// prior to a call and is guaranteed to be restored (also by the caller)
0625   /// after the call.
0626   virtual bool isCallerPreservedPhysReg(MCRegister PhysReg,
0627                                         const MachineFunction &MF) const {
0628     return false;
0629   }
0630 
0631   /// This is a wrapper around getCallPreservedMask().
0632   /// Return true if the register is preserved after the call.
0633   virtual bool isCalleeSavedPhysReg(MCRegister PhysReg,
0634                                     const MachineFunction &MF) const;
0635 
0636   /// Returns true if PhysReg can be used as an argument to a function.
0637   virtual bool isArgumentRegister(const MachineFunction &MF,
0638                                   MCRegister PhysReg) const {
0639     return false;
0640   }
0641 
0642   /// Returns true if PhysReg is a fixed register.
0643   virtual bool isFixedRegister(const MachineFunction &MF,
0644                                MCRegister PhysReg) const {
0645     return false;
0646   }
0647 
0648   /// Returns true if PhysReg is a general purpose register.
0649   virtual bool isGeneralPurposeRegister(const MachineFunction &MF,
0650                                         MCRegister PhysReg) const {
0651     return false;
0652   }
0653 
0654   /// Returns true if RC is a class/subclass of general purpose register.
0655   virtual bool
0656   isGeneralPurposeRegisterClass(const TargetRegisterClass *RC) const {
0657     return false;
0658   }
0659 
0660   /// Prior to adding the live-out mask to a stackmap or patchpoint
0661   /// instruction, provide the target the opportunity to adjust it (mainly to
0662   /// remove pseudo-registers that should be ignored).
0663   virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const {}
0664 
0665   /// Return a super-register of the specified register
0666   /// Reg so its sub-register of index SubIdx is Reg.
0667   MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx,
0668                                  const TargetRegisterClass *RC) const {
0669     return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
0670   }
0671 
0672   /// Return a subclass of the specified register
0673   /// class A so that each register in it has a sub-register of the
0674   /// specified sub-register index which is in the specified register class B.
0675   ///
0676   /// TableGen will synthesize missing A sub-classes.
0677   virtual const TargetRegisterClass *
0678   getMatchingSuperRegClass(const TargetRegisterClass *A,
0679                            const TargetRegisterClass *B, unsigned Idx) const;
0680 
0681   // For a copy-like instruction that defines a register of class DefRC with
0682   // subreg index DefSubReg, reading from another source with class SrcRC and
0683   // subregister SrcSubReg return true if this is a preferable copy
0684   // instruction or an earlier use should be used.
0685   virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
0686                                     unsigned DefSubReg,
0687                                     const TargetRegisterClass *SrcRC,
0688                                     unsigned SrcSubReg) const;
0689 
0690   /// Returns the largest legal sub-class of RC that
0691   /// supports the sub-register index Idx.
0692   /// If no such sub-class exists, return NULL.
0693   /// If all registers in RC already have an Idx sub-register, return RC.
0694   ///
0695   /// TableGen generates a version of this function that is good enough in most
0696   /// cases.  Targets can override if they have constraints that TableGen
0697   /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
0698   /// supported by the full GR32 register class in 64-bit mode, but only by the
0699   /// GR32_ABCD regiister class in 32-bit mode.
0700   ///
0701   /// TableGen will synthesize missing RC sub-classes.
0702   virtual const TargetRegisterClass *
0703   getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
0704     assert(Idx == 0 && "Target has no sub-registers");
0705     return RC;
0706   }
0707 
0708   /// Return a register class that can be used for a subregister copy from/into
0709   /// \p SuperRC at \p SubRegIdx.
0710   virtual const TargetRegisterClass *
0711   getSubRegisterClass(const TargetRegisterClass *SuperRC,
0712                       unsigned SubRegIdx) const {
0713     return nullptr;
0714   }
0715 
0716   /// Return the subregister index you get from composing
0717   /// two subregister indices.
0718   ///
0719   /// The special null sub-register index composes as the identity.
0720   ///
0721   /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
0722   /// returns c. Note that composeSubRegIndices does not tell you about illegal
0723   /// compositions. If R does not have a subreg a, or R:a does not have a subreg
0724   /// b, composeSubRegIndices doesn't tell you.
0725   ///
0726   /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
0727   /// ssub_0:S0 - ssub_3:S3 subregs.
0728   /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
0729   unsigned composeSubRegIndices(unsigned a, unsigned b) const {
0730     if (!a) return b;
0731     if (!b) return a;
0732     return composeSubRegIndicesImpl(a, b);
0733   }
0734 
0735   /// Transforms a LaneMask computed for one subregister to the lanemask that
0736   /// would have been computed when composing the subsubregisters with IdxA
0737   /// first. @sa composeSubRegIndices()
0738   LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA,
0739                                          LaneBitmask Mask) const {
0740     if (!IdxA)
0741       return Mask;
0742     return composeSubRegIndexLaneMaskImpl(IdxA, Mask);
0743   }
0744 
0745   /// Transform a lanemask given for a virtual register to the corresponding
0746   /// lanemask before using subregister with index \p IdxA.
0747   /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a
0748   /// valie lane mask (no invalid bits set) the following holds:
0749   /// X0 = composeSubRegIndexLaneMask(Idx, Mask)
0750   /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0)
0751   /// => X1 == Mask
0752   LaneBitmask reverseComposeSubRegIndexLaneMask(unsigned IdxA,
0753                                                 LaneBitmask LaneMask) const {
0754     if (!IdxA)
0755       return LaneMask;
0756     return reverseComposeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
0757   }
0758 
0759   /// Debugging helper: dump register in human readable form to dbgs() stream.
0760   static void dumpReg(Register Reg, unsigned SubRegIndex = 0,
0761                       const TargetRegisterInfo *TRI = nullptr);
0762 
0763   /// Return target defined base register class for a physical register.
0764   /// This is the register class with the lowest BaseClassOrder containing the
0765   /// register.
0766   /// Will be nullptr if the register is not in any base register class.
0767   virtual const TargetRegisterClass *getPhysRegBaseClass(MCRegister Reg) const {
0768     return nullptr;
0769   }
0770 
0771 protected:
0772   /// Overridden by TableGen in targets that have sub-registers.
0773   virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
0774     llvm_unreachable("Target has no sub-registers");
0775   }
0776 
0777   /// Overridden by TableGen in targets that have sub-registers.
0778   virtual LaneBitmask
0779   composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const {
0780     llvm_unreachable("Target has no sub-registers");
0781   }
0782 
0783   virtual LaneBitmask reverseComposeSubRegIndexLaneMaskImpl(unsigned,
0784                                                             LaneBitmask) const {
0785     llvm_unreachable("Target has no sub-registers");
0786   }
0787 
0788   /// Return the register cost table index. This implementation is sufficient
0789   /// for most architectures and can be overriden by targets in case there are
0790   /// multiple cost values associated with each register.
0791   virtual unsigned getRegisterCostTableIndex(const MachineFunction &MF) const {
0792     return 0;
0793   }
0794 
0795 public:
0796   /// Find a common super-register class if it exists.
0797   ///
0798   /// Find a register class, SuperRC and two sub-register indices, PreA and
0799   /// PreB, such that:
0800   ///
0801   ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
0802   ///
0803   ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
0804   ///
0805   ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
0806   ///
0807   /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
0808   /// requirements, and there is no register class with a smaller spill size
0809   /// that satisfies the requirements.
0810   ///
0811   /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
0812   ///
0813   /// Either of the PreA and PreB sub-register indices may be returned as 0. In
0814   /// that case, the returned register class will be a sub-class of the
0815   /// corresponding argument register class.
0816   ///
0817   /// The function returns NULL if no register class can be found.
0818   const TargetRegisterClass*
0819   getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
0820                          const TargetRegisterClass *RCB, unsigned SubB,
0821                          unsigned &PreA, unsigned &PreB) const;
0822 
0823   //===--------------------------------------------------------------------===//
0824   // Register Class Information
0825   //
0826 protected:
0827   const RegClassInfo &getRegClassInfo(const TargetRegisterClass &RC) const {
0828     return RCInfos[getNumRegClasses() * HwMode + RC.getID()];
0829   }
0830 
0831 public:
0832   /// Register class iterators
0833   regclass_iterator regclass_begin() const { return RegClassBegin; }
0834   regclass_iterator regclass_end() const { return RegClassEnd; }
0835   iterator_range<regclass_iterator> regclasses() const {
0836     return make_range(regclass_begin(), regclass_end());
0837   }
0838 
0839   unsigned getNumRegClasses() const {
0840     return (unsigned)(regclass_end()-regclass_begin());
0841   }
0842 
0843   /// Returns the register class associated with the enumeration value.
0844   /// See class MCOperandInfo.
0845   const TargetRegisterClass *getRegClass(unsigned i) const {
0846     assert(i < getNumRegClasses() && "Register Class ID out of range");
0847     return RegClassBegin[i];
0848   }
0849 
0850   /// Returns the name of the register class.
0851   const char *getRegClassName(const TargetRegisterClass *Class) const {
0852     return MCRegisterInfo::getRegClassName(Class->MC);
0853   }
0854 
0855   /// Find the largest common subclass of A and B.
0856   /// Return NULL if there is no common subclass.
0857   const TargetRegisterClass *
0858   getCommonSubClass(const TargetRegisterClass *A,
0859                     const TargetRegisterClass *B) const;
0860 
0861   /// Returns a TargetRegisterClass used for pointer values.
0862   /// If a target supports multiple different pointer register classes,
0863   /// kind specifies which one is indicated.
0864   virtual const TargetRegisterClass *
0865   getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
0866     llvm_unreachable("Target didn't implement getPointerRegClass!");
0867   }
0868 
0869   /// Returns a legal register class to copy a register in the specified class
0870   /// to or from. If it is possible to copy the register directly without using
0871   /// a cross register class copy, return the specified RC. Returns NULL if it
0872   /// is not possible to copy between two registers of the specified class.
0873   virtual const TargetRegisterClass *
0874   getCrossCopyRegClass(const TargetRegisterClass *RC) const {
0875     return RC;
0876   }
0877 
0878   /// Returns the largest super class of RC that is legal to use in the current
0879   /// sub-target and has the same spill size.
0880   /// The returned register class can be used to create virtual registers which
0881   /// means that all its registers can be copied and spilled.
0882   virtual const TargetRegisterClass *
0883   getLargestLegalSuperClass(const TargetRegisterClass *RC,
0884                             const MachineFunction &) const {
0885     /// The default implementation is very conservative and doesn't allow the
0886     /// register allocator to inflate register classes.
0887     return RC;
0888   }
0889 
0890   /// Return the register pressure "high water mark" for the specific register
0891   /// class. The scheduler is in high register pressure mode (for the specific
0892   /// register class) if it goes over the limit.
0893   ///
0894   /// Note: this is the old register pressure model that relies on a manually
0895   /// specified representative register class per value type.
0896   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
0897                                        MachineFunction &MF) const {
0898     return 0;
0899   }
0900 
0901   /// Return a heuristic for the machine scheduler to compare the profitability
0902   /// of increasing one register pressure set versus another.  The scheduler
0903   /// will prefer increasing the register pressure of the set which returns
0904   /// the largest value for this function.
0905   virtual unsigned getRegPressureSetScore(const MachineFunction &MF,
0906                                           unsigned PSetID) const {
0907     return PSetID;
0908   }
0909 
0910   /// Get the weight in units of pressure for this register class.
0911   virtual const RegClassWeight &getRegClassWeight(
0912     const TargetRegisterClass *RC) const = 0;
0913 
0914   /// Returns size in bits of a phys/virtual/generic register.
0915   TypeSize getRegSizeInBits(Register Reg, const MachineRegisterInfo &MRI) const;
0916 
0917   /// Get the weight in units of pressure for this register unit.
0918   virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
0919 
0920   /// Get the number of dimensions of register pressure.
0921   virtual unsigned getNumRegPressureSets() const = 0;
0922 
0923   /// Get the name of this register unit pressure set.
0924   virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
0925 
0926   /// Get the register unit pressure limit for this dimension.
0927   /// This limit must be adjusted dynamically for reserved registers.
0928   virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
0929                                           unsigned Idx) const = 0;
0930 
0931   /// Get the dimensions of register pressure impacted by this register class.
0932   /// Returns a -1 terminated array of pressure set IDs.
0933   virtual const int *getRegClassPressureSets(
0934     const TargetRegisterClass *RC) const = 0;
0935 
0936   /// Get the dimensions of register pressure impacted by this register unit.
0937   /// Returns a -1 terminated array of pressure set IDs.
0938   virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
0939 
0940   /// Get a list of 'hint' registers that the register allocator should try
0941   /// first when allocating a physical register for the virtual register
0942   /// VirtReg. These registers are effectively moved to the front of the
0943   /// allocation order. If true is returned, regalloc will try to only use
0944   /// hints to the greatest extent possible even if it means spilling.
0945   ///
0946   /// The Order argument is the allocation order for VirtReg's register class
0947   /// as returned from RegisterClassInfo::getOrder(). The hint registers must
0948   /// come from Order, and they must not be reserved.
0949   ///
0950   /// The default implementation of this function will only add target
0951   /// independent register allocation hints. Targets that override this
0952   /// function should typically call this default implementation as well and
0953   /// expect to see generic copy hints added.
0954   virtual bool
0955   getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order,
0956                         SmallVectorImpl<MCPhysReg> &Hints,
0957                         const MachineFunction &MF,
0958                         const VirtRegMap *VRM = nullptr,
0959                         const LiveRegMatrix *Matrix = nullptr) const;
0960 
0961   /// A callback to allow target a chance to update register allocation hints
0962   /// when a register is "changed" (e.g. coalesced) to another register.
0963   /// e.g. On ARM, some virtual registers should target register pairs,
0964   /// if one of pair is coalesced to another register, the allocation hint of
0965   /// the other half of the pair should be changed to point to the new register.
0966   virtual void updateRegAllocHint(Register Reg, Register NewReg,
0967                                   MachineFunction &MF) const {
0968     // Do nothing.
0969   }
0970 
0971   /// Allow the target to reverse allocation order of local live ranges. This
0972   /// will generally allocate shorter local live ranges first. For targets with
0973   /// many registers, this could reduce regalloc compile time by a large
0974   /// factor. It is disabled by default for three reasons:
0975   /// (1) Top-down allocation is simpler and easier to debug for targets that
0976   /// don't benefit from reversing the order.
0977   /// (2) Bottom-up allocation could result in poor evicition decisions on some
0978   /// targets affecting the performance of compiled code.
0979   /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
0980   virtual bool reverseLocalAssignment() const { return false; }
0981 
0982   /// Allow the target to override the cost of using a callee-saved register for
0983   /// the first time. Default value of 0 means we will use a callee-saved
0984   /// register if it is available.
0985   virtual unsigned getCSRFirstUseCost() const { return 0; }
0986 
0987   /// Returns true if the target requires (and can make use of) the register
0988   /// scavenger.
0989   virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
0990     return false;
0991   }
0992 
0993   /// Returns true if the target wants to use frame pointer based accesses to
0994   /// spill to the scavenger emergency spill slot.
0995   virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
0996     return true;
0997   }
0998 
0999   /// Returns true if the target requires post PEI scavenging of registers for
1000   /// materializing frame index constants.
1001   virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
1002     return false;
1003   }
1004 
1005   /// Returns true if the target requires using the RegScavenger directly for
1006   /// frame elimination despite using requiresFrameIndexScavenging.
1007   virtual bool requiresFrameIndexReplacementScavenging(
1008       const MachineFunction &MF) const {
1009     return false;
1010   }
1011 
1012   /// Returns true if the target wants the LocalStackAllocation pass to be run
1013   /// and virtual base registers used for more efficient stack access.
1014   virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
1015     return false;
1016   }
1017 
1018   /// Return true if target has reserved a spill slot in the stack frame of
1019   /// the given function for the specified register. e.g. On x86, if the frame
1020   /// register is required, the first fixed stack object is reserved as its
1021   /// spill slot. This tells PEI not to create a new stack frame
1022   /// object for the given register. It should be called only after
1023   /// determineCalleeSaves().
1024   virtual bool hasReservedSpillSlot(const MachineFunction &MF, Register Reg,
1025                                     int &FrameIdx) const {
1026     return false;
1027   }
1028 
1029   /// Returns true if the live-ins should be tracked after register allocation.
1030   virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
1031     return true;
1032   }
1033 
1034   /// True if the stack can be realigned for the target.
1035   virtual bool canRealignStack(const MachineFunction &MF) const;
1036 
1037   /// True if storage within the function requires the stack pointer to be
1038   /// aligned more than the normal calling convention calls for.
1039   virtual bool shouldRealignStack(const MachineFunction &MF) const;
1040 
1041   /// True if stack realignment is required and still possible.
1042   bool hasStackRealignment(const MachineFunction &MF) const {
1043     return shouldRealignStack(MF) && canRealignStack(MF);
1044   }
1045 
1046   /// Get the offset from the referenced frame index in the instruction,
1047   /// if there is one.
1048   virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
1049                                            int Idx) const {
1050     return 0;
1051   }
1052 
1053   /// Returns true if the instruction's frame index reference would be better
1054   /// served by a base register other than FP or SP.
1055   /// Used by LocalStackFrameAllocation to determine which frame index
1056   /// references it should create new base registers for.
1057   virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1058     return false;
1059   }
1060 
1061   /// Insert defining instruction(s) for a pointer to FrameIdx before
1062   /// insertion point I. Return materialized frame pointer.
1063   virtual Register materializeFrameBaseRegister(MachineBasicBlock *MBB,
1064                                                 int FrameIdx,
1065                                                 int64_t Offset) const {
1066     llvm_unreachable("materializeFrameBaseRegister does not exist on this "
1067                      "target");
1068   }
1069 
1070   /// Resolve a frame index operand of an instruction
1071   /// to reference the indicated base register plus offset instead.
1072   virtual void resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1073                                  int64_t Offset) const {
1074     llvm_unreachable("resolveFrameIndex does not exist on this target");
1075   }
1076 
1077   /// Determine whether a given base register plus offset immediate is
1078   /// encodable to resolve a frame index.
1079   virtual bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg,
1080                                   int64_t Offset) const {
1081     llvm_unreachable("isFrameOffsetLegal does not exist on this target");
1082   }
1083 
1084   /// Gets the DWARF expression opcodes for \p Offset.
1085   virtual void getOffsetOpcodes(const StackOffset &Offset,
1086                                 SmallVectorImpl<uint64_t> &Ops) const;
1087 
1088   /// Prepends a DWARF expression for \p Offset to DIExpression \p Expr.
1089   DIExpression *
1090   prependOffsetExpression(const DIExpression *Expr, unsigned PrependFlags,
1091                           const StackOffset &Offset) const;
1092 
1093   /// Spill the register so it can be used by the register scavenger.
1094   /// Return true if the register was spilled, false otherwise.
1095   /// If this function does not spill the register, the scavenger
1096   /// will instead spill it to the emergency spill slot.
1097   virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
1098                                      MachineBasicBlock::iterator I,
1099                                      MachineBasicBlock::iterator &UseMI,
1100                                      const TargetRegisterClass *RC,
1101                                      Register Reg) const {
1102     return false;
1103   }
1104 
1105   /// Process frame indices in reverse block order. This changes the behavior of
1106   /// the RegScavenger passed to eliminateFrameIndex. If this is true targets
1107   /// should scavengeRegisterBackwards in eliminateFrameIndex. New targets
1108   /// should prefer reverse scavenging behavior.
1109   /// TODO: Remove this when all targets return true.
1110   virtual bool eliminateFrameIndicesBackwards() const { return true; }
1111 
1112   /// This method must be overriden to eliminate abstract frame indices from
1113   /// instructions which may use them. The instruction referenced by the
1114   /// iterator contains an MO_FrameIndex operand which must be eliminated by
1115   /// this method. This method may modify or replace the specified instruction,
1116   /// as long as it keeps the iterator pointing at the finished product.
1117   /// SPAdj is the SP adjustment due to call frame setup instruction.
1118   /// FIOperandNum is the FI operand number.
1119   /// Returns true if the current instruction was removed and the iterator
1120   /// is not longer valid
1121   virtual bool eliminateFrameIndex(MachineBasicBlock::iterator MI,
1122                                    int SPAdj, unsigned FIOperandNum,
1123                                    RegScavenger *RS = nullptr) const = 0;
1124 
1125   /// Return the assembly name for \p Reg.
1126   virtual StringRef getRegAsmName(MCRegister Reg) const {
1127     // FIXME: We are assuming that the assembly name is equal to the TableGen
1128     // name converted to lower case
1129     //
1130     // The TableGen name is the name of the definition for this register in the
1131     // target's tablegen files.  For example, the TableGen name of
1132     // def EAX : Register <...>; is "EAX"
1133     return StringRef(getName(Reg));
1134   }
1135 
1136   //===--------------------------------------------------------------------===//
1137   /// Subtarget Hooks
1138 
1139   /// SrcRC and DstRC will be morphed into NewRC if this returns true.
1140   virtual bool shouldCoalesce(MachineInstr *MI,
1141                               const TargetRegisterClass *SrcRC,
1142                               unsigned SubReg,
1143                               const TargetRegisterClass *DstRC,
1144                               unsigned DstSubReg,
1145                               const TargetRegisterClass *NewRC,
1146                               LiveIntervals &LIS) const
1147   { return true; }
1148 
1149   /// Region split has a high compile time cost especially for large live range.
1150   /// This method is used to decide whether or not \p VirtReg should
1151   /// go through this expensive splitting heuristic.
1152   virtual bool shouldRegionSplitForVirtReg(const MachineFunction &MF,
1153                                            const LiveInterval &VirtReg) const;
1154 
1155   /// Last chance recoloring has a high compile time cost especially for
1156   /// targets with a lot of registers.
1157   /// This method is used to decide whether or not \p VirtReg should
1158   /// go through this expensive heuristic.
1159   /// When this target hook is hit, by returning false, there is a high
1160   /// chance that the register allocation will fail altogether (usually with
1161   /// "ran out of registers").
1162   /// That said, this error usually points to another problem in the
1163   /// optimization pipeline.
1164   virtual bool
1165   shouldUseLastChanceRecoloringForVirtReg(const MachineFunction &MF,
1166                                           const LiveInterval &VirtReg) const {
1167     return true;
1168   }
1169 
1170   /// Deferred spilling delays the spill insertion of a virtual register
1171   /// after every other allocation. By deferring the spilling, it is
1172   /// sometimes possible to eliminate that spilling altogether because
1173   /// something else could have been eliminated, thus leaving some space
1174   /// for the virtual register.
1175   /// However, this comes with a compile time impact because it adds one
1176   /// more stage to the greedy register allocator.
1177   /// This method is used to decide whether \p VirtReg should use the deferred
1178   /// spilling stage instead of being spilled right away.
1179   virtual bool
1180   shouldUseDeferredSpillingForVirtReg(const MachineFunction &MF,
1181                                       const LiveInterval &VirtReg) const {
1182     return false;
1183   }
1184 
1185   /// When prioritizing live ranges in register allocation, if this hook returns
1186   /// true then the AllocationPriority of the register class will be treated as
1187   /// more important than whether the range is local to a basic block or global.
1188   virtual bool
1189   regClassPriorityTrumpsGlobalness(const MachineFunction &MF) const {
1190     return false;
1191   }
1192 
1193   //===--------------------------------------------------------------------===//
1194   /// Debug information queries.
1195 
1196   /// getFrameRegister - This method should return the register used as a base
1197   /// for values allocated in the current stack frame.
1198   virtual Register getFrameRegister(const MachineFunction &MF) const = 0;
1199 
1200   /// Mark a register and all its aliases as reserved in the given set.
1201   void markSuperRegs(BitVector &RegisterSet, MCRegister Reg) const;
1202 
1203   /// Returns true if for every register in the set all super registers are part
1204   /// of the set as well.
1205   bool checkAllSuperRegsMarked(const BitVector &RegisterSet,
1206       ArrayRef<MCPhysReg> Exceptions = ArrayRef<MCPhysReg>()) const;
1207 
1208   virtual const TargetRegisterClass *
1209   getConstrainedRegClassForOperand(const MachineOperand &MO,
1210                                    const MachineRegisterInfo &MRI) const {
1211     return nullptr;
1212   }
1213 
1214   /// Returns the physical register number of sub-register "Index"
1215   /// for physical register RegNo. Return zero if the sub-register does not
1216   /// exist.
1217   inline MCRegister getSubReg(MCRegister Reg, unsigned Idx) const {
1218     return static_cast<const MCRegisterInfo *>(this)->getSubReg(Reg, Idx);
1219   }
1220 
1221   /// Some targets have non-allocatable registers that aren't technically part
1222   /// of the explicit callee saved register list, but should be handled as such
1223   /// in certain cases.
1224   virtual bool isNonallocatableRegisterCalleeSave(MCRegister Reg) const {
1225     return false;
1226   }
1227 
1228   virtual std::optional<uint8_t> getVRegFlagValue(StringRef Name) const {
1229     return {};
1230   }
1231 
1232   virtual SmallVector<StringLiteral>
1233   getVRegFlagsOfReg(Register Reg, const MachineFunction &MF) const {
1234     return {};
1235   }
1236 };
1237 
1238 //===----------------------------------------------------------------------===//
1239 //                           SuperRegClassIterator
1240 //===----------------------------------------------------------------------===//
1241 //
1242 // Iterate over the possible super-registers for a given register class. The
1243 // iterator will visit a list of pairs (Idx, Mask) corresponding to the
1244 // possible classes of super-registers.
1245 //
1246 // Each bit mask will have at least one set bit, and each set bit in Mask
1247 // corresponds to a SuperRC such that:
1248 //
1249 //   For all Reg in SuperRC: Reg:Idx is in RC.
1250 //
1251 // The iterator can include (O, RC->getSubClassMask()) as the first entry which
1252 // also satisfies the above requirement, assuming Reg:0 == Reg.
1253 //
1254 class SuperRegClassIterator {
1255   const unsigned RCMaskWords;
1256   unsigned SubReg = 0;
1257   const uint16_t *Idx;
1258   const uint32_t *Mask;
1259 
1260 public:
1261   /// Create a SuperRegClassIterator that visits all the super-register classes
1262   /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
1263   SuperRegClassIterator(const TargetRegisterClass *RC,
1264                         const TargetRegisterInfo *TRI,
1265                         bool IncludeSelf = false)
1266     : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
1267       Idx(RC->getSuperRegIndices()), Mask(RC->getSubClassMask()) {
1268     if (!IncludeSelf)
1269       ++*this;
1270   }
1271 
1272   /// Returns true if this iterator is still pointing at a valid entry.
1273   bool isValid() const { return Idx; }
1274 
1275   /// Returns the current sub-register index.
1276   unsigned getSubReg() const { return SubReg; }
1277 
1278   /// Returns the bit mask of register classes that getSubReg() projects into
1279   /// RC.
1280   /// See TargetRegisterClass::getSubClassMask() for how to use it.
1281   const uint32_t *getMask() const { return Mask; }
1282 
1283   /// Advance iterator to the next entry.
1284   void operator++() {
1285     assert(isValid() && "Cannot move iterator past end.");
1286     Mask += RCMaskWords;
1287     SubReg = *Idx++;
1288     if (!SubReg)
1289       Idx = nullptr;
1290   }
1291 };
1292 
1293 //===----------------------------------------------------------------------===//
1294 //                           BitMaskClassIterator
1295 //===----------------------------------------------------------------------===//
1296 /// This class encapuslates the logic to iterate over bitmask returned by
1297 /// the various RegClass related APIs.
1298 /// E.g., this class can be used to iterate over the subclasses provided by
1299 /// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask.
1300 class BitMaskClassIterator {
1301   /// Total number of register classes.
1302   const unsigned NumRegClasses;
1303   /// Base index of CurrentChunk.
1304   /// In other words, the number of bit we read to get at the
1305   /// beginning of that chunck.
1306   unsigned Base = 0;
1307   /// Adjust base index of CurrentChunk.
1308   /// Base index + how many bit we read within CurrentChunk.
1309   unsigned Idx = 0;
1310   /// Current register class ID.
1311   unsigned ID = 0;
1312   /// Mask we are iterating over.
1313   const uint32_t *Mask;
1314   /// Current chunk of the Mask we are traversing.
1315   uint32_t CurrentChunk;
1316 
1317   /// Move ID to the next set bit.
1318   void moveToNextID() {
1319     // If the current chunk of memory is empty, move to the next one,
1320     // while making sure we do not go pass the number of register
1321     // classes.
1322     while (!CurrentChunk) {
1323       // Move to the next chunk.
1324       Base += 32;
1325       if (Base >= NumRegClasses) {
1326         ID = NumRegClasses;
1327         return;
1328       }
1329       CurrentChunk = *++Mask;
1330       Idx = Base;
1331     }
1332     // Otherwise look for the first bit set from the right
1333     // (representation of the class ID is big endian).
1334     // See getSubClassMask for more details on the representation.
1335     unsigned Offset = llvm::countr_zero(CurrentChunk);
1336     // Add the Offset to the adjusted base number of this chunk: Idx.
1337     // This is the ID of the register class.
1338     ID = Idx + Offset;
1339 
1340     // Consume the zeros, if any, and the bit we just read
1341     // so that we are at the right spot for the next call.
1342     // Do not do Offset + 1 because Offset may be 31 and 32
1343     // will be UB for the shift, though in that case we could
1344     // have make the chunk being equal to 0, but that would
1345     // have introduced a if statement.
1346     moveNBits(Offset);
1347     moveNBits(1);
1348   }
1349 
1350   /// Move \p NumBits Bits forward in CurrentChunk.
1351   void moveNBits(unsigned NumBits) {
1352     assert(NumBits < 32 && "Undefined behavior spotted!");
1353     // Consume the bit we read for the next call.
1354     CurrentChunk >>= NumBits;
1355     // Adjust the base for the chunk.
1356     Idx += NumBits;
1357   }
1358 
1359 public:
1360   /// Create a BitMaskClassIterator that visits all the register classes
1361   /// represented by \p Mask.
1362   ///
1363   /// \pre \p Mask != nullptr
1364   BitMaskClassIterator(const uint32_t *Mask, const TargetRegisterInfo &TRI)
1365       : NumRegClasses(TRI.getNumRegClasses()), Mask(Mask), CurrentChunk(*Mask) {
1366     // Move to the first ID.
1367     moveToNextID();
1368   }
1369 
1370   /// Returns true if this iterator is still pointing at a valid entry.
1371   bool isValid() const { return getID() != NumRegClasses; }
1372 
1373   /// Returns the current register class ID.
1374   unsigned getID() const { return ID; }
1375 
1376   /// Advance iterator to the next entry.
1377   void operator++() {
1378     assert(isValid() && "Cannot move iterator past end.");
1379     moveToNextID();
1380   }
1381 };
1382 
1383 // This is useful when building IndexedMaps keyed on virtual registers
1384 struct VirtReg2IndexFunctor {
1385   using argument_type = Register;
1386   unsigned operator()(Register Reg) const {
1387     return Register::virtReg2Index(Reg);
1388   }
1389 };
1390 
1391 /// Prints virtual and physical registers with or without a TRI instance.
1392 ///
1393 /// The format is:
1394 ///   %noreg          - NoRegister
1395 ///   %5              - a virtual register.
1396 ///   %5:sub_8bit     - a virtual register with sub-register index (with TRI).
1397 ///   %eax            - a physical register
1398 ///   %physreg17      - a physical register when no TRI instance given.
1399 ///
1400 /// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n';
1401 Printable printReg(Register Reg, const TargetRegisterInfo *TRI = nullptr,
1402                    unsigned SubIdx = 0,
1403                    const MachineRegisterInfo *MRI = nullptr);
1404 
1405 /// Create Printable object to print register units on a \ref raw_ostream.
1406 ///
1407 /// Register units are named after their root registers:
1408 ///
1409 ///   al      - Single root.
1410 ///   fp0~st7 - Dual roots.
1411 ///
1412 /// Usage: OS << printRegUnit(Unit, TRI) << '\n';
1413 Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI);
1414 
1415 /// Create Printable object to print virtual registers and physical
1416 /// registers on a \ref raw_ostream.
1417 Printable printVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI);
1418 
1419 /// Create Printable object to print register classes or register banks
1420 /// on a \ref raw_ostream.
1421 Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo,
1422                               const TargetRegisterInfo *TRI);
1423 
1424 } // end namespace llvm
1425 
1426 #endif // LLVM_CODEGEN_TARGETREGISTERINFO_H