1 //==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- 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 // This file describes an abstract interface used to get information about a
10 // target machines register file.  This information is used for a variety of
11 // purposed, especially register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H
16 #define LLVM_CODEGEN_TARGETREGISTERINFO_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/IR/CallingConv.h"
24 #include "llvm/MC/LaneBitmask.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MachineValueType.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/Printable.h"
30 #include <cassert>
31 #include <cstdint>
32 #include <functional>
33 
34 namespace llvm {
35 
36 class BitVector;
37 class DIExpression;
38 class LiveRegMatrix;
39 class MachineFunction;
40 class MachineInstr;
41 class RegScavenger;
42 class VirtRegMap;
43 class LiveIntervals;
44 class LiveInterval;
45 
46 class TargetRegisterClass {
47 public:
48   using iterator = const MCPhysReg *;
49   using const_iterator = const MCPhysReg *;
50   using sc_iterator = const TargetRegisterClass* const *;
51 
52   // Instance variables filled by tablegen, do not use!
53   const MCRegisterClass *MC;
54   const uint32_t *SubClassMask;
55   const uint16_t *SuperRegIndices;
56   const LaneBitmask LaneMask;
57   /// Classes with a higher priority value are assigned first by register
58   /// allocators using a greedy heuristic. The value is in the range [0,63].
59   const uint8_t AllocationPriority;
60   /// Whether the class supports two (or more) disjunct subregister indices.
61   const bool HasDisjunctSubRegs;
62   /// Whether a combination of subregisters can cover every register in the
63   /// class. See also the CoveredBySubRegs description in Target.td.
64   const bool CoveredBySubRegs;
65   const sc_iterator SuperClasses;
66   ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&);
67 
68   /// Return the register class ID number.
69   unsigned getID() const { return MC->getID(); }
70 
71   /// begin/end - Return all of the registers in this class.
72   ///
73   iterator       begin() const { return MC->begin(); }
74   iterator         end() const { return MC->end(); }
75 
76   /// Return the number of registers in this class.
77   unsigned getNumRegs() const { return MC->getNumRegs(); }
78 
79   iterator_range<SmallVectorImpl<MCPhysReg>::const_iterator>
80   getRegisters() const {
81     return make_range(MC->begin(), MC->end());
82   }
83 
84   /// Return the specified register in the class.
85   MCRegister getRegister(unsigned i) const {
86     return MC->getRegister(i);
87   }
88 
89   /// Return true if the specified register is included in this register class.
90   /// This does not include virtual registers.
91   bool contains(Register Reg) const {
92     /// FIXME: Historically this function has returned false when given vregs
93     ///        but it should probably only receive physical registers
94     if (!Reg.isPhysical())
95       return false;
96     return MC->contains(Reg.asMCReg());
97   }
98 
99   /// Return true if both registers are in this class.
100   bool contains(Register Reg1, Register Reg2) const {
101     /// FIXME: Historically this function has returned false when given a vregs
102     ///        but it should probably only receive physical registers
103     if (!Reg1.isPhysical() || !Reg2.isPhysical())
104       return false;
105     return MC->contains(Reg1.asMCReg(), Reg2.asMCReg());
106   }
107 
108   /// Return the cost of copying a value between two registers in this class.
109   /// A negative number means the register class is very expensive
110   /// to copy e.g. status flag register classes.
111   int getCopyCost() const { return MC->getCopyCost(); }
112 
113   /// Return true if this register class may be used to create virtual
114   /// registers.
115   bool isAllocatable() const { return MC->isAllocatable(); }
116 
117   /// Return true if the specified TargetRegisterClass
118   /// is a proper sub-class of this TargetRegisterClass.
119   bool hasSubClass(const TargetRegisterClass *RC) const {
120     return RC != this && hasSubClassEq(RC);
121   }
122 
123   /// Returns true if RC is a sub-class of or equal to this class.
124   bool hasSubClassEq(const TargetRegisterClass *RC) const {
125     unsigned ID = RC->getID();
126     return (SubClassMask[ID / 32] >> (ID % 32)) & 1;
127   }
128 
129   /// Return true if the specified TargetRegisterClass is a
130   /// proper super-class of this TargetRegisterClass.
131   bool hasSuperClass(const TargetRegisterClass *RC) const {
132     return RC->hasSubClass(this);
133   }
134 
135   /// Returns true if RC is a super-class of or equal to this class.
136   bool hasSuperClassEq(const TargetRegisterClass *RC) const {
137     return RC->hasSubClassEq(this);
138   }
139 
140   /// Returns a bit vector of subclasses, including this one.
141   /// The vector is indexed by class IDs.
142   ///
143   /// To use it, consider the returned array as a chunk of memory that
144   /// contains an array of bits of size NumRegClasses. Each 32-bit chunk
145   /// contains a bitset of the ID of the subclasses in big-endian style.
146 
147   /// I.e., the representation of the memory from left to right at the
148   /// bit level looks like:
149   /// [31 30 ... 1 0] [ 63 62 ... 33 32] ...
150   ///                     [ XXX NumRegClasses NumRegClasses - 1 ... ]
151   /// Where the number represents the class ID and XXX bits that
152   /// should be ignored.
153   ///
154   /// See the implementation of hasSubClassEq for an example of how it
155   /// can be used.
156   const uint32_t *getSubClassMask() const {
157     return SubClassMask;
158   }
159 
160   /// Returns a 0-terminated list of sub-register indices that project some
161   /// super-register class into this register class. The list has an entry for
162   /// each Idx such that:
163   ///
164   ///   There exists SuperRC where:
165   ///     For all Reg in SuperRC:
166   ///       this->contains(Reg:Idx)
167   const uint16_t *getSuperRegIndices() const {
168     return SuperRegIndices;
169   }
170 
171   /// Returns a NULL-terminated list of super-classes.  The
172   /// classes are ordered by ID which is also a topological ordering from large
173   /// to small classes.  The list does NOT include the current class.
174   sc_iterator getSuperClasses() const {
175     return SuperClasses;
176   }
177 
178   /// Return true if this TargetRegisterClass is a subset
179   /// class of at least one other TargetRegisterClass.
180   bool isASubClass() const {
181     return SuperClasses[0] != nullptr;
182   }
183 
184   /// Returns the preferred order for allocating registers from this register
185   /// class in MF. The raw order comes directly from the .td file and may
186   /// include reserved registers that are not allocatable.
187   /// Register allocators should also make sure to allocate
188   /// callee-saved registers only after all the volatiles are used. The
189   /// RegisterClassInfo class provides filtered allocation orders with
190   /// callee-saved registers moved to the end.
191   ///
192   /// The MachineFunction argument can be used to tune the allocatable
193   /// registers based on the characteristics of the function, subtarget, or
194   /// other criteria.
195   ///
196   /// By default, this method returns all registers in the class.
197   ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const {
198     return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
199   }
200 
201   /// Returns the combination of all lane masks of register in this class.
202   /// The lane masks of the registers are the combination of all lane masks
203   /// of their subregisters. Returns 1 if there are no subregisters.
204   LaneBitmask getLaneMask() const {
205     return LaneMask;
206   }
207 };
208 
209 /// Extra information, not in MCRegisterDesc, about registers.
210 /// These are used by codegen, not by MC.
211 struct TargetRegisterInfoDesc {
212   unsigned CostPerUse;          // Extra cost of instructions using register.
213   bool inAllocatableClass;      // Register belongs to an allocatable regclass.
214 };
215 
216 /// Each TargetRegisterClass has a per register weight, and weight
217 /// limit which must be less than the limits of its pressure sets.
218 struct RegClassWeight {
219   unsigned RegWeight;
220   unsigned WeightLimit;
221 };
222 
223 /// TargetRegisterInfo base class - We assume that the target defines a static
224 /// array of TargetRegisterDesc objects that represent all of the machine
225 /// registers that the target has.  As such, we simply have to track a pointer
226 /// to this array so that we can turn register number into a register
227 /// descriptor.
228 ///
229 class TargetRegisterInfo : public MCRegisterInfo {
230 public:
231   using regclass_iterator = const TargetRegisterClass * const *;
232   using vt_iterator = const MVT::SimpleValueType *;
233   struct RegClassInfo {
234     unsigned RegSize, SpillSize, SpillAlignment;
235     vt_iterator VTList;
236   };
237 private:
238   const TargetRegisterInfoDesc *InfoDesc;     // Extra desc array for codegen
239   const char *const *SubRegIndexNames;        // Names of subreg indexes.
240   // Pointer to array of lane masks, one per sub-reg index.
241   const LaneBitmask *SubRegIndexLaneMasks;
242 
243   regclass_iterator RegClassBegin, RegClassEnd;   // List of regclasses
244   LaneBitmask CoveringLanes;
245   const RegClassInfo *const RCInfos;
246   unsigned HwMode;
247 
248 protected:
249   TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
250                      regclass_iterator RCB,
251                      regclass_iterator RCE,
252                      const char *const *SRINames,
253                      const LaneBitmask *SRILaneMasks,
254                      LaneBitmask CoveringLanes,
255                      const RegClassInfo *const RCIs,
256                      unsigned Mode = 0);
257   virtual ~TargetRegisterInfo();
258 
259 public:
260   // Register numbers can represent physical registers, virtual registers, and
261   // sometimes stack slots. The unsigned values are divided into these ranges:
262   //
263   //   0           Not a register, can be used as a sentinel.
264   //   [1;2^30)    Physical registers assigned by TableGen.
265   //   [2^30;2^31) Stack slots. (Rarely used.)
266   //   [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
267   //
268   // Further sentinels can be allocated from the small negative integers.
269   // DenseMapInfo<unsigned> uses -1u and -2u.
270 
271   /// Return the size in bits of a register from class RC.
272   unsigned getRegSizeInBits(const TargetRegisterClass &RC) const {
273     return getRegClassInfo(RC).RegSize;
274   }
275 
276   /// Return the size in bytes of the stack slot allocated to hold a spilled
277   /// copy of a register from class RC.
278   unsigned getSpillSize(const TargetRegisterClass &RC) const {
279     return getRegClassInfo(RC).SpillSize / 8;
280   }
281 
282   /// Return the minimum required alignment in bytes for a spill slot for
283   /// a register of this class.
284   unsigned getSpillAlignment(const TargetRegisterClass &RC) const {
285     return getRegClassInfo(RC).SpillAlignment / 8;
286   }
287 
288   /// Return the minimum required alignment in bytes for a spill slot for
289   /// a register of this class.
290   Align getSpillAlign(const TargetRegisterClass &RC) const {
291     return Align(getRegClassInfo(RC).SpillAlignment / 8);
292   }
293 
294   /// Return true if the given TargetRegisterClass has the ValueType T.
295   bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const {
296     for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I)
297       if (MVT(*I) == T)
298         return true;
299     return false;
300   }
301 
302   /// Loop over all of the value types that can be represented by values
303   /// in the given register class.
304   vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const {
305     return getRegClassInfo(RC).VTList;
306   }
307 
308   vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const {
309     vt_iterator I = legalclasstypes_begin(RC);
310     while (*I != MVT::Other)
311       ++I;
312     return I;
313   }
314 
315   /// Returns the Register Class of a physical register of the given type,
316   /// picking the most sub register class of the right type that contains this
317   /// physreg.
318   const TargetRegisterClass *getMinimalPhysRegClass(MCRegister Reg,
319                                                     MVT VT = MVT::Other) const;
320 
321   /// Return the maximal subclass of the given register class that is
322   /// allocatable or NULL.
323   const TargetRegisterClass *
324     getAllocatableClass(const TargetRegisterClass *RC) const;
325 
326   /// Returns a bitset indexed by register number indicating if a register is
327   /// allocatable or not. If a register class is specified, returns the subset
328   /// for the class.
329   BitVector getAllocatableSet(const MachineFunction &MF,
330                               const TargetRegisterClass *RC = nullptr) const;
331 
332   /// Return the additional cost of using this register instead
333   /// of other registers in its class.
334   unsigned getCostPerUse(MCRegister RegNo) const {
335     return InfoDesc[RegNo].CostPerUse;
336   }
337 
338   /// Return true if the register is in the allocation of any register class.
339   bool isInAllocatableClass(MCRegister RegNo) const {
340     return InfoDesc[RegNo].inAllocatableClass;
341   }
342 
343   /// Return the human-readable symbolic target-specific
344   /// name for the specified SubRegIndex.
345   const char *getSubRegIndexName(unsigned SubIdx) const {
346     assert(SubIdx && SubIdx < getNumSubRegIndices() &&
347            "This is not a subregister index");
348     return SubRegIndexNames[SubIdx-1];
349   }
350 
351   /// Return a bitmask representing the parts of a register that are covered by
352   /// SubIdx \see LaneBitmask.
353   ///
354   /// SubIdx == 0 is allowed, it has the lane mask ~0u.
355   LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const {
356     assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
357     return SubRegIndexLaneMasks[SubIdx];
358   }
359 
360   /// The lane masks returned by getSubRegIndexLaneMask() above can only be
361   /// used to determine if sub-registers overlap - they can't be used to
362   /// determine if a set of sub-registers completely cover another
363   /// sub-register.
364   ///
365   /// The X86 general purpose registers have two lanes corresponding to the
366   /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
367   /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
368   /// sub_32bit sub-register.
369   ///
370   /// On the other hand, the ARM NEON lanes fully cover their registers: The
371   /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
372   /// This is related to the CoveredBySubRegs property on register definitions.
373   ///
374   /// This function returns a bit mask of lanes that completely cover their
375   /// sub-registers. More precisely, given:
376   ///
377   ///   Covering = getCoveringLanes();
378   ///   MaskA = getSubRegIndexLaneMask(SubA);
379   ///   MaskB = getSubRegIndexLaneMask(SubB);
380   ///
381   /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
382   /// SubB.
383   LaneBitmask getCoveringLanes() const { return CoveringLanes; }
384 
385   /// Returns true if the two registers are equal or alias each other.
386   /// The registers may be virtual registers.
387   bool regsOverlap(Register regA, Register regB) const {
388     if (regA == regB) return true;
389     if (!regA.isPhysical() || !regB.isPhysical())
390       return false;
391 
392     // Regunits are numerically ordered. Find a common unit.
393     MCRegUnitIterator RUA(regA.asMCReg(), this);
394     MCRegUnitIterator RUB(regB.asMCReg(), this);
395     do {
396       if (*RUA == *RUB) return true;
397       if (*RUA < *RUB) ++RUA;
398       else             ++RUB;
399     } while (RUA.isValid() && RUB.isValid());
400     return false;
401   }
402 
403   /// Returns true if Reg contains RegUnit.
404   bool hasRegUnit(MCRegister Reg, Register RegUnit) const {
405     for (MCRegUnitIterator Units(Reg, this); Units.isValid(); ++Units)
406       if (Register(*Units) == RegUnit)
407         return true;
408     return false;
409   }
410 
411   /// Returns the original SrcReg unless it is the target of a copy-like
412   /// operation, in which case we chain backwards through all such operations
413   /// to the ultimate source register.  If a physical register is encountered,
414   /// we stop the search.
415   virtual Register lookThruCopyLike(Register SrcReg,
416                                     const MachineRegisterInfo *MRI) const;
417 
418   /// Find the original SrcReg unless it is the target of a copy-like operation,
419   /// in which case we chain backwards through all such operations to the
420   /// ultimate source register. If a physical register is encountered, we stop
421   /// the search.
422   /// Return the original SrcReg if all the definitions in the chain only have
423   /// one user and not a physical register.
424   virtual Register
425   lookThruSingleUseCopyChain(Register SrcReg,
426                              const MachineRegisterInfo *MRI) const;
427 
428   /// Return a null-terminated list of all of the callee-saved registers on
429   /// this target. The register should be in the order of desired callee-save
430   /// stack frame offset. The first register is closest to the incoming stack
431   /// pointer if stack grows down, and vice versa.
432   /// Notice: This function does not take into account disabled CSRs.
433   ///         In most cases you will want to use instead the function
434   ///         getCalleeSavedRegs that is implemented in MachineRegisterInfo.
435   virtual const MCPhysReg*
436   getCalleeSavedRegs(const MachineFunction *MF) const = 0;
437 
438   /// Return a mask of call-preserved registers for the given calling convention
439   /// on the current function. The mask should include all call-preserved
440   /// aliases. This is used by the register allocator to determine which
441   /// registers can be live across a call.
442   ///
443   /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
444   /// A set bit indicates that all bits of the corresponding register are
445   /// preserved across the function call.  The bit mask is expected to be
446   /// sub-register complete, i.e. if A is preserved, so are all its
447   /// sub-registers.
448   ///
449   /// Bits are numbered from the LSB, so the bit for physical register Reg can
450   /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
451   ///
452   /// A NULL pointer means that no register mask will be used, and call
453   /// instructions should use implicit-def operands to indicate call clobbered
454   /// registers.
455   ///
456   virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF,
457                                                CallingConv::ID) const {
458     // The default mask clobbers everything.  All targets should override.
459     return nullptr;
460   }
461 
462   /// Return a register mask for the registers preserved by the unwinder,
463   /// or nullptr if no custom mask is needed.
464   virtual const uint32_t *
465   getCustomEHPadPreservedMask(const MachineFunction &MF) const {
466     return nullptr;
467   }
468 
469   /// Return a register mask that clobbers everything.
470   virtual const uint32_t *getNoPreservedMask() const {
471     llvm_unreachable("target does not provide no preserved mask");
472   }
473 
474   /// Return a list of all of the registers which are clobbered "inside" a call
475   /// to the given function. For example, these might be needed for PLT
476   /// sequences of long-branch veneers.
477   virtual ArrayRef<MCPhysReg>
478   getIntraCallClobberedRegs(const MachineFunction *MF) const {
479     return {};
480   }
481 
482   /// Return true if all bits that are set in mask \p mask0 are also set in
483   /// \p mask1.
484   bool regmaskSubsetEqual(const uint32_t *mask0, const uint32_t *mask1) const;
485 
486   /// Return all the call-preserved register masks defined for this target.
487   virtual ArrayRef<const uint32_t *> getRegMasks() const = 0;
488   virtual ArrayRef<const char *> getRegMaskNames() const = 0;
489 
490   /// Returns a bitset indexed by physical register number indicating if a
491   /// register is a special register that has particular uses and should be
492   /// considered unavailable at all times, e.g. stack pointer, return address.
493   /// A reserved register:
494   /// - is not allocatable
495   /// - is considered always live
496   /// - is ignored by liveness tracking
497   /// It is often necessary to reserve the super registers of a reserved
498   /// register as well, to avoid them getting allocated indirectly. You may use
499   /// markSuperRegs() and checkAllSuperRegsMarked() in this case.
500   virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
501 
502   /// Returns false if we can't guarantee that Physreg, specified as an IR asm
503   /// clobber constraint, will be preserved across the statement.
504   virtual bool isAsmClobberable(const MachineFunction &MF,
505                                 MCRegister PhysReg) const {
506     return true;
507   }
508 
509   /// Returns true if PhysReg cannot be written to in inline asm statements.
510   virtual bool isInlineAsmReadOnlyReg(const MachineFunction &MF,
511                                       unsigned PhysReg) const {
512     return false;
513   }
514 
515   /// Returns true if PhysReg is unallocatable and constant throughout the
516   /// function.  Used by MachineRegisterInfo::isConstantPhysReg().
517   virtual bool isConstantPhysReg(MCRegister PhysReg) const { return false; }
518 
519   /// Returns true if the register class is considered divergent.
520   virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const {
521     return false;
522   }
523 
524   /// Physical registers that may be modified within a function but are
525   /// guaranteed to be restored before any uses. This is useful for targets that
526   /// have call sequences where a GOT register may be updated by the caller
527   /// prior to a call and is guaranteed to be restored (also by the caller)
528   /// after the call.
529   virtual bool isCallerPreservedPhysReg(MCRegister PhysReg,
530                                         const MachineFunction &MF) const {
531     return false;
532   }
533 
534   /// This is a wrapper around getCallPreservedMask().
535   /// Return true if the register is preserved after the call.
536   virtual bool isCalleeSavedPhysReg(MCRegister PhysReg,
537                                     const MachineFunction &MF) const;
538 
539   /// Prior to adding the live-out mask to a stackmap or patchpoint
540   /// instruction, provide the target the opportunity to adjust it (mainly to
541   /// remove pseudo-registers that should be ignored).
542   virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const {}
543 
544   /// Return a super-register of the specified register
545   /// Reg so its sub-register of index SubIdx is Reg.
546   MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx,
547                                  const TargetRegisterClass *RC) const {
548     return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
549   }
550 
551   /// Return a subclass of the specified register
552   /// class A so that each register in it has a sub-register of the
553   /// specified sub-register index which is in the specified register class B.
554   ///
555   /// TableGen will synthesize missing A sub-classes.
556   virtual const TargetRegisterClass *
557   getMatchingSuperRegClass(const TargetRegisterClass *A,
558                            const TargetRegisterClass *B, unsigned Idx) const;
559 
560   // For a copy-like instruction that defines a register of class DefRC with
561   // subreg index DefSubReg, reading from another source with class SrcRC and
562   // subregister SrcSubReg return true if this is a preferable copy
563   // instruction or an earlier use should be used.
564   virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
565                                     unsigned DefSubReg,
566                                     const TargetRegisterClass *SrcRC,
567                                     unsigned SrcSubReg) const;
568 
569   /// Returns the largest legal sub-class of RC that
570   /// supports the sub-register index Idx.
571   /// If no such sub-class exists, return NULL.
572   /// If all registers in RC already have an Idx sub-register, return RC.
573   ///
574   /// TableGen generates a version of this function that is good enough in most
575   /// cases.  Targets can override if they have constraints that TableGen
576   /// doesn't understand.  For example, the x86 sub_8bit sub-register index is
577   /// supported by the full GR32 register class in 64-bit mode, but only by the
578   /// GR32_ABCD regiister class in 32-bit mode.
579   ///
580   /// TableGen will synthesize missing RC sub-classes.
581   virtual const TargetRegisterClass *
582   getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
583     assert(Idx == 0 && "Target has no sub-registers");
584     return RC;
585   }
586 
587   /// Return the subregister index you get from composing
588   /// two subregister indices.
589   ///
590   /// The special null sub-register index composes as the identity.
591   ///
592   /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
593   /// returns c. Note that composeSubRegIndices does not tell you about illegal
594   /// compositions. If R does not have a subreg a, or R:a does not have a subreg
595   /// b, composeSubRegIndices doesn't tell you.
596   ///
597   /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
598   /// ssub_0:S0 - ssub_3:S3 subregs.
599   /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
600   unsigned composeSubRegIndices(unsigned a, unsigned b) const {
601     if (!a) return b;
602     if (!b) return a;
603     return composeSubRegIndicesImpl(a, b);
604   }
605 
606   /// Transforms a LaneMask computed for one subregister to the lanemask that
607   /// would have been computed when composing the subsubregisters with IdxA
608   /// first. @sa composeSubRegIndices()
609   LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA,
610                                          LaneBitmask Mask) const {
611     if (!IdxA)
612       return Mask;
613     return composeSubRegIndexLaneMaskImpl(IdxA, Mask);
614   }
615 
616   /// Transform a lanemask given for a virtual register to the corresponding
617   /// lanemask before using subregister with index \p IdxA.
618   /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a
619   /// valie lane mask (no invalid bits set) the following holds:
620   /// X0 = composeSubRegIndexLaneMask(Idx, Mask)
621   /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0)
622   /// => X1 == Mask
623   LaneBitmask reverseComposeSubRegIndexLaneMask(unsigned IdxA,
624                                                 LaneBitmask LaneMask) const {
625     if (!IdxA)
626       return LaneMask;
627     return reverseComposeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
628   }
629 
630   /// Debugging helper: dump register in human readable form to dbgs() stream.
631   static void dumpReg(Register Reg, unsigned SubRegIndex = 0,
632                       const TargetRegisterInfo *TRI = nullptr);
633 
634 protected:
635   /// Overridden by TableGen in targets that have sub-registers.
636   virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
637     llvm_unreachable("Target has no sub-registers");
638   }
639 
640   /// Overridden by TableGen in targets that have sub-registers.
641   virtual LaneBitmask
642   composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const {
643     llvm_unreachable("Target has no sub-registers");
644   }
645 
646   virtual LaneBitmask reverseComposeSubRegIndexLaneMaskImpl(unsigned,
647                                                             LaneBitmask) const {
648     llvm_unreachable("Target has no sub-registers");
649   }
650 
651 public:
652   /// Find a common super-register class if it exists.
653   ///
654   /// Find a register class, SuperRC and two sub-register indices, PreA and
655   /// PreB, such that:
656   ///
657   ///   1. PreA + SubA == PreB + SubB  (using composeSubRegIndices()), and
658   ///
659   ///   2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
660   ///
661   ///   3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
662   ///
663   /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
664   /// requirements, and there is no register class with a smaller spill size
665   /// that satisfies the requirements.
666   ///
667   /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
668   ///
669   /// Either of the PreA and PreB sub-register indices may be returned as 0. In
670   /// that case, the returned register class will be a sub-class of the
671   /// corresponding argument register class.
672   ///
673   /// The function returns NULL if no register class can be found.
674   const TargetRegisterClass*
675   getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
676                          const TargetRegisterClass *RCB, unsigned SubB,
677                          unsigned &PreA, unsigned &PreB) const;
678 
679   //===--------------------------------------------------------------------===//
680   // Register Class Information
681   //
682 protected:
683   const RegClassInfo &getRegClassInfo(const TargetRegisterClass &RC) const {
684     return RCInfos[getNumRegClasses() * HwMode + RC.getID()];
685   }
686 
687 public:
688   /// Register class iterators
689   regclass_iterator regclass_begin() const { return RegClassBegin; }
690   regclass_iterator regclass_end() const { return RegClassEnd; }
691   iterator_range<regclass_iterator> regclasses() const {
692     return make_range(regclass_begin(), regclass_end());
693   }
694 
695   unsigned getNumRegClasses() const {
696     return (unsigned)(regclass_end()-regclass_begin());
697   }
698 
699   /// Returns the register class associated with the enumeration value.
700   /// See class MCOperandInfo.
701   const TargetRegisterClass *getRegClass(unsigned i) const {
702     assert(i < getNumRegClasses() && "Register Class ID out of range");
703     return RegClassBegin[i];
704   }
705 
706   /// Returns the name of the register class.
707   const char *getRegClassName(const TargetRegisterClass *Class) const {
708     return MCRegisterInfo::getRegClassName(Class->MC);
709   }
710 
711   /// Find the largest common subclass of A and B.
712   /// Return NULL if there is no common subclass.
713   const TargetRegisterClass *
714   getCommonSubClass(const TargetRegisterClass *A,
715                     const TargetRegisterClass *B) const;
716 
717   /// Returns a TargetRegisterClass used for pointer values.
718   /// If a target supports multiple different pointer register classes,
719   /// kind specifies which one is indicated.
720   virtual const TargetRegisterClass *
721   getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const {
722     llvm_unreachable("Target didn't implement getPointerRegClass!");
723   }
724 
725   /// Returns a legal register class to copy a register in the specified class
726   /// to or from. If it is possible to copy the register directly without using
727   /// a cross register class copy, return the specified RC. Returns NULL if it
728   /// is not possible to copy between two registers of the specified class.
729   virtual const TargetRegisterClass *
730   getCrossCopyRegClass(const TargetRegisterClass *RC) const {
731     return RC;
732   }
733 
734   /// Returns the largest super class of RC that is legal to use in the current
735   /// sub-target and has the same spill size.
736   /// The returned register class can be used to create virtual registers which
737   /// means that all its registers can be copied and spilled.
738   virtual const TargetRegisterClass *
739   getLargestLegalSuperClass(const TargetRegisterClass *RC,
740                             const MachineFunction &) const {
741     /// The default implementation is very conservative and doesn't allow the
742     /// register allocator to inflate register classes.
743     return RC;
744   }
745 
746   /// Return the register pressure "high water mark" for the specific register
747   /// class. The scheduler is in high register pressure mode (for the specific
748   /// register class) if it goes over the limit.
749   ///
750   /// Note: this is the old register pressure model that relies on a manually
751   /// specified representative register class per value type.
752   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
753                                        MachineFunction &MF) const {
754     return 0;
755   }
756 
757   /// Return a heuristic for the machine scheduler to compare the profitability
758   /// of increasing one register pressure set versus another.  The scheduler
759   /// will prefer increasing the register pressure of the set which returns
760   /// the largest value for this function.
761   virtual unsigned getRegPressureSetScore(const MachineFunction &MF,
762                                           unsigned PSetID) const {
763     return PSetID;
764   }
765 
766   /// Get the weight in units of pressure for this register class.
767   virtual const RegClassWeight &getRegClassWeight(
768     const TargetRegisterClass *RC) const = 0;
769 
770   /// Returns size in bits of a phys/virtual/generic register.
771   unsigned getRegSizeInBits(Register Reg, const MachineRegisterInfo &MRI) const;
772 
773   /// Get the weight in units of pressure for this register unit.
774   virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0;
775 
776   /// Get the number of dimensions of register pressure.
777   virtual unsigned getNumRegPressureSets() const = 0;
778 
779   /// Get the name of this register unit pressure set.
780   virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
781 
782   /// Get the register unit pressure limit for this dimension.
783   /// This limit must be adjusted dynamically for reserved registers.
784   virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
785                                           unsigned Idx) const = 0;
786 
787   /// Get the dimensions of register pressure impacted by this register class.
788   /// Returns a -1 terminated array of pressure set IDs.
789   virtual const int *getRegClassPressureSets(
790     const TargetRegisterClass *RC) const = 0;
791 
792   /// Get the dimensions of register pressure impacted by this register unit.
793   /// Returns a -1 terminated array of pressure set IDs.
794   virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0;
795 
796   /// Get a list of 'hint' registers that the register allocator should try
797   /// first when allocating a physical register for the virtual register
798   /// VirtReg. These registers are effectively moved to the front of the
799   /// allocation order. If true is returned, regalloc will try to only use
800   /// hints to the greatest extent possible even if it means spilling.
801   ///
802   /// The Order argument is the allocation order for VirtReg's register class
803   /// as returned from RegisterClassInfo::getOrder(). The hint registers must
804   /// come from Order, and they must not be reserved.
805   ///
806   /// The default implementation of this function will only add target
807   /// independent register allocation hints. Targets that override this
808   /// function should typically call this default implementation as well and
809   /// expect to see generic copy hints added.
810   virtual bool
811   getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order,
812                         SmallVectorImpl<MCPhysReg> &Hints,
813                         const MachineFunction &MF,
814                         const VirtRegMap *VRM = nullptr,
815                         const LiveRegMatrix *Matrix = nullptr) const;
816 
817   /// A callback to allow target a chance to update register allocation hints
818   /// when a register is "changed" (e.g. coalesced) to another register.
819   /// e.g. On ARM, some virtual registers should target register pairs,
820   /// if one of pair is coalesced to another register, the allocation hint of
821   /// the other half of the pair should be changed to point to the new register.
822   virtual void updateRegAllocHint(Register Reg, Register NewReg,
823                                   MachineFunction &MF) const {
824     // Do nothing.
825   }
826 
827   /// Allow the target to reverse allocation order of local live ranges. This
828   /// will generally allocate shorter local live ranges first. For targets with
829   /// many registers, this could reduce regalloc compile time by a large
830   /// factor. It is disabled by default for three reasons:
831   /// (1) Top-down allocation is simpler and easier to debug for targets that
832   /// don't benefit from reversing the order.
833   /// (2) Bottom-up allocation could result in poor evicition decisions on some
834   /// targets affecting the performance of compiled code.
835   /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
836   virtual bool reverseLocalAssignment() const { return false; }
837 
838   /// Allow the target to override the cost of using a callee-saved register for
839   /// the first time. Default value of 0 means we will use a callee-saved
840   /// register if it is available.
841   virtual unsigned getCSRFirstUseCost() const { return 0; }
842 
843   /// Returns true if the target requires (and can make use of) the register
844   /// scavenger.
845   virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
846     return false;
847   }
848 
849   /// Returns true if the target wants to use frame pointer based accesses to
850   /// spill to the scavenger emergency spill slot.
851   virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
852     return true;
853   }
854 
855   /// Returns true if the target requires post PEI scavenging of registers for
856   /// materializing frame index constants.
857   virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
858     return false;
859   }
860 
861   /// Returns true if the target requires using the RegScavenger directly for
862   /// frame elimination despite using requiresFrameIndexScavenging.
863   virtual bool requiresFrameIndexReplacementScavenging(
864       const MachineFunction &MF) const {
865     return false;
866   }
867 
868   /// Returns true if the target wants the LocalStackAllocation pass to be run
869   /// and virtual base registers used for more efficient stack access.
870   virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
871     return false;
872   }
873 
874   /// Return true if target has reserved a spill slot in the stack frame of
875   /// the given function for the specified register. e.g. On x86, if the frame
876   /// register is required, the first fixed stack object is reserved as its
877   /// spill slot. This tells PEI not to create a new stack frame
878   /// object for the given register. It should be called only after
879   /// determineCalleeSaves().
880   virtual bool hasReservedSpillSlot(const MachineFunction &MF, Register Reg,
881                                     int &FrameIdx) const {
882     return false;
883   }
884 
885   /// Returns true if the live-ins should be tracked after register allocation.
886   virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
887     return true;
888   }
889 
890   /// True if the stack can be realigned for the target.
891   virtual bool canRealignStack(const MachineFunction &MF) const;
892 
893   /// True if storage within the function requires the stack pointer to be
894   /// aligned more than the normal calling convention calls for.
895   /// This cannot be overriden by the target, but canRealignStack can be
896   /// overridden.
897   bool needsStackRealignment(const MachineFunction &MF) const;
898 
899   /// Get the offset from the referenced frame index in the instruction,
900   /// if there is one.
901   virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI,
902                                            int Idx) const {
903     return 0;
904   }
905 
906   /// Returns true if the instruction's frame index reference would be better
907   /// served by a base register other than FP or SP.
908   /// Used by LocalStackFrameAllocation to determine which frame index
909   /// references it should create new base registers for.
910   virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
911     return false;
912   }
913 
914   /// Insert defining instruction(s) for a pointer to FrameIdx before
915   /// insertion point I. Return materialized frame pointer.
916   virtual Register materializeFrameBaseRegister(MachineBasicBlock *MBB,
917                                                 int FrameIdx,
918                                                 int64_t Offset) const {
919     llvm_unreachable("materializeFrameBaseRegister does not exist on this "
920                      "target");
921   }
922 
923   /// Resolve a frame index operand of an instruction
924   /// to reference the indicated base register plus offset instead.
925   virtual void resolveFrameIndex(MachineInstr &MI, Register BaseReg,
926                                  int64_t Offset) const {
927     llvm_unreachable("resolveFrameIndex does not exist on this target");
928   }
929 
930   /// Determine whether a given base register plus offset immediate is
931   /// encodable to resolve a frame index.
932   virtual bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg,
933                                   int64_t Offset) const {
934     llvm_unreachable("isFrameOffsetLegal does not exist on this target");
935   }
936 
937   /// Gets the DWARF expression opcodes for \p Offset.
938   virtual void getOffsetOpcodes(const StackOffset &Offset,
939                                 SmallVectorImpl<uint64_t> &Ops) const;
940 
941   /// Prepends a DWARF expression for \p Offset to DIExpression \p Expr.
942   DIExpression *
943   prependOffsetExpression(const DIExpression *Expr, unsigned PrependFlags,
944                           const StackOffset &Offset) const;
945 
946   /// Spill the register so it can be used by the register scavenger.
947   /// Return true if the register was spilled, false otherwise.
948   /// If this function does not spill the register, the scavenger
949   /// will instead spill it to the emergency spill slot.
950   virtual bool saveScavengerRegister(MachineBasicBlock &MBB,
951                                      MachineBasicBlock::iterator I,
952                                      MachineBasicBlock::iterator &UseMI,
953                                      const TargetRegisterClass *RC,
954                                      Register Reg) const {
955     return false;
956   }
957 
958   /// This method must be overriden to eliminate abstract frame indices from
959   /// instructions which may use them. The instruction referenced by the
960   /// iterator contains an MO_FrameIndex operand which must be eliminated by
961   /// this method. This method may modify or replace the specified instruction,
962   /// as long as it keeps the iterator pointing at the finished product.
963   /// SPAdj is the SP adjustment due to call frame setup instruction.
964   /// FIOperandNum is the FI operand number.
965   virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI,
966                                    int SPAdj, unsigned FIOperandNum,
967                                    RegScavenger *RS = nullptr) const = 0;
968 
969   /// Return the assembly name for \p Reg.
970   virtual StringRef getRegAsmName(MCRegister Reg) const {
971     // FIXME: We are assuming that the assembly name is equal to the TableGen
972     // name converted to lower case
973     //
974     // The TableGen name is the name of the definition for this register in the
975     // target's tablegen files.  For example, the TableGen name of
976     // def EAX : Register <...>; is "EAX"
977     return StringRef(getName(Reg));
978   }
979 
980   //===--------------------------------------------------------------------===//
981   /// Subtarget Hooks
982 
983   /// SrcRC and DstRC will be morphed into NewRC if this returns true.
984   virtual bool shouldCoalesce(MachineInstr *MI,
985                               const TargetRegisterClass *SrcRC,
986                               unsigned SubReg,
987                               const TargetRegisterClass *DstRC,
988                               unsigned DstSubReg,
989                               const TargetRegisterClass *NewRC,
990                               LiveIntervals &LIS) const
991   { return true; }
992 
993   /// Region split has a high compile time cost especially for large live range.
994   /// This method is used to decide whether or not \p VirtReg should
995   /// go through this expensive splitting heuristic.
996   virtual bool shouldRegionSplitForVirtReg(const MachineFunction &MF,
997                                            const LiveInterval &VirtReg) const;
998 
999   /// Last chance recoloring has a high compile time cost especially for
1000   /// targets with a lot of registers.
1001   /// This method is used to decide whether or not \p VirtReg should
1002   /// go through this expensive heuristic.
1003   /// When this target hook is hit, by returning false, there is a high
1004   /// chance that the register allocation will fail altogether (usually with
1005   /// "ran out of registers").
1006   /// That said, this error usually points to another problem in the
1007   /// optimization pipeline.
1008   virtual bool
1009   shouldUseLastChanceRecoloringForVirtReg(const MachineFunction &MF,
1010                                           const LiveInterval &VirtReg) const {
1011     return true;
1012   }
1013 
1014   /// Deferred spilling delays the spill insertion of a virtual register
1015   /// after every other allocation. By deferring the spilling, it is
1016   /// sometimes possible to eliminate that spilling altogether because
1017   /// something else could have been eliminated, thus leaving some space
1018   /// for the virtual register.
1019   /// However, this comes with a compile time impact because it adds one
1020   /// more stage to the greedy register allocator.
1021   /// This method is used to decide whether \p VirtReg should use the deferred
1022   /// spilling stage instead of being spilled right away.
1023   virtual bool
1024   shouldUseDeferredSpillingForVirtReg(const MachineFunction &MF,
1025                                       const LiveInterval &VirtReg) const {
1026     return false;
1027   }
1028 
1029   //===--------------------------------------------------------------------===//
1030   /// Debug information queries.
1031 
1032   /// getFrameRegister - This method should return the register used as a base
1033   /// for values allocated in the current stack frame.
1034   virtual Register getFrameRegister(const MachineFunction &MF) const = 0;
1035 
1036   /// Mark a register and all its aliases as reserved in the given set.
1037   void markSuperRegs(BitVector &RegisterSet, MCRegister Reg) const;
1038 
1039   /// Returns true if for every register in the set all super registers are part
1040   /// of the set as well.
1041   bool checkAllSuperRegsMarked(const BitVector &RegisterSet,
1042       ArrayRef<MCPhysReg> Exceptions = ArrayRef<MCPhysReg>()) const;
1043 
1044   virtual const TargetRegisterClass *
1045   getConstrainedRegClassForOperand(const MachineOperand &MO,
1046                                    const MachineRegisterInfo &MRI) const {
1047     return nullptr;
1048   }
1049 
1050   /// Returns the physical register number of sub-register "Index"
1051   /// for physical register RegNo. Return zero if the sub-register does not
1052   /// exist.
1053   inline MCRegister getSubReg(MCRegister Reg, unsigned Idx) const {
1054     return static_cast<const MCRegisterInfo *>(this)->getSubReg(Reg, Idx);
1055   }
1056 };
1057 
1058 //===----------------------------------------------------------------------===//
1059 //                           SuperRegClassIterator
1060 //===----------------------------------------------------------------------===//
1061 //
1062 // Iterate over the possible super-registers for a given register class. The
1063 // iterator will visit a list of pairs (Idx, Mask) corresponding to the
1064 // possible classes of super-registers.
1065 //
1066 // Each bit mask will have at least one set bit, and each set bit in Mask
1067 // corresponds to a SuperRC such that:
1068 //
1069 //   For all Reg in SuperRC: Reg:Idx is in RC.
1070 //
1071 // The iterator can include (O, RC->getSubClassMask()) as the first entry which
1072 // also satisfies the above requirement, assuming Reg:0 == Reg.
1073 //
1074 class SuperRegClassIterator {
1075   const unsigned RCMaskWords;
1076   unsigned SubReg = 0;
1077   const uint16_t *Idx;
1078   const uint32_t *Mask;
1079 
1080 public:
1081   /// Create a SuperRegClassIterator that visits all the super-register classes
1082   /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
1083   SuperRegClassIterator(const TargetRegisterClass *RC,
1084                         const TargetRegisterInfo *TRI,
1085                         bool IncludeSelf = false)
1086     : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
1087       Idx(RC->getSuperRegIndices()), Mask(RC->getSubClassMask()) {
1088     if (!IncludeSelf)
1089       ++*this;
1090   }
1091 
1092   /// Returns true if this iterator is still pointing at a valid entry.
1093   bool isValid() const { return Idx; }
1094 
1095   /// Returns the current sub-register index.
1096   unsigned getSubReg() const { return SubReg; }
1097 
1098   /// Returns the bit mask of register classes that getSubReg() projects into
1099   /// RC.
1100   /// See TargetRegisterClass::getSubClassMask() for how to use it.
1101   const uint32_t *getMask() const { return Mask; }
1102 
1103   /// Advance iterator to the next entry.
1104   void operator++() {
1105     assert(isValid() && "Cannot move iterator past end.");
1106     Mask += RCMaskWords;
1107     SubReg = *Idx++;
1108     if (!SubReg)
1109       Idx = nullptr;
1110   }
1111 };
1112 
1113 //===----------------------------------------------------------------------===//
1114 //                           BitMaskClassIterator
1115 //===----------------------------------------------------------------------===//
1116 /// This class encapuslates the logic to iterate over bitmask returned by
1117 /// the various RegClass related APIs.
1118 /// E.g., this class can be used to iterate over the subclasses provided by
1119 /// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask.
1120 class BitMaskClassIterator {
1121   /// Total number of register classes.
1122   const unsigned NumRegClasses;
1123   /// Base index of CurrentChunk.
1124   /// In other words, the number of bit we read to get at the
1125   /// beginning of that chunck.
1126   unsigned Base = 0;
1127   /// Adjust base index of CurrentChunk.
1128   /// Base index + how many bit we read within CurrentChunk.
1129   unsigned Idx = 0;
1130   /// Current register class ID.
1131   unsigned ID = 0;
1132   /// Mask we are iterating over.
1133   const uint32_t *Mask;
1134   /// Current chunk of the Mask we are traversing.
1135   uint32_t CurrentChunk;
1136 
1137   /// Move ID to the next set bit.
1138   void moveToNextID() {
1139     // If the current chunk of memory is empty, move to the next one,
1140     // while making sure we do not go pass the number of register
1141     // classes.
1142     while (!CurrentChunk) {
1143       // Move to the next chunk.
1144       Base += 32;
1145       if (Base >= NumRegClasses) {
1146         ID = NumRegClasses;
1147         return;
1148       }
1149       CurrentChunk = *++Mask;
1150       Idx = Base;
1151     }
1152     // Otherwise look for the first bit set from the right
1153     // (representation of the class ID is big endian).
1154     // See getSubClassMask for more details on the representation.
1155     unsigned Offset = countTrailingZeros(CurrentChunk);
1156     // Add the Offset to the adjusted base number of this chunk: Idx.
1157     // This is the ID of the register class.
1158     ID = Idx + Offset;
1159 
1160     // Consume the zeros, if any, and the bit we just read
1161     // so that we are at the right spot for the next call.
1162     // Do not do Offset + 1 because Offset may be 31 and 32
1163     // will be UB for the shift, though in that case we could
1164     // have make the chunk being equal to 0, but that would
1165     // have introduced a if statement.
1166     moveNBits(Offset);
1167     moveNBits(1);
1168   }
1169 
1170   /// Move \p NumBits Bits forward in CurrentChunk.
1171   void moveNBits(unsigned NumBits) {
1172     assert(NumBits < 32 && "Undefined behavior spotted!");
1173     // Consume the bit we read for the next call.
1174     CurrentChunk >>= NumBits;
1175     // Adjust the base for the chunk.
1176     Idx += NumBits;
1177   }
1178 
1179 public:
1180   /// Create a BitMaskClassIterator that visits all the register classes
1181   /// represented by \p Mask.
1182   ///
1183   /// \pre \p Mask != nullptr
1184   BitMaskClassIterator(const uint32_t *Mask, const TargetRegisterInfo &TRI)
1185       : NumRegClasses(TRI.getNumRegClasses()), Mask(Mask), CurrentChunk(*Mask) {
1186     // Move to the first ID.
1187     moveToNextID();
1188   }
1189 
1190   /// Returns true if this iterator is still pointing at a valid entry.
1191   bool isValid() const { return getID() != NumRegClasses; }
1192 
1193   /// Returns the current register class ID.
1194   unsigned getID() const { return ID; }
1195 
1196   /// Advance iterator to the next entry.
1197   void operator++() {
1198     assert(isValid() && "Cannot move iterator past end.");
1199     moveToNextID();
1200   }
1201 };
1202 
1203 // This is useful when building IndexedMaps keyed on virtual registers
1204 struct VirtReg2IndexFunctor {
1205   using argument_type = Register;
1206   unsigned operator()(Register Reg) const {
1207     return Register::virtReg2Index(Reg);
1208   }
1209 };
1210 
1211 /// Prints virtual and physical registers with or without a TRI instance.
1212 ///
1213 /// The format is:
1214 ///   %noreg          - NoRegister
1215 ///   %5              - a virtual register.
1216 ///   %5:sub_8bit     - a virtual register with sub-register index (with TRI).
1217 ///   %eax            - a physical register
1218 ///   %physreg17      - a physical register when no TRI instance given.
1219 ///
1220 /// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n';
1221 Printable printReg(Register Reg, const TargetRegisterInfo *TRI = nullptr,
1222                    unsigned SubIdx = 0,
1223                    const MachineRegisterInfo *MRI = nullptr);
1224 
1225 /// Create Printable object to print register units on a \ref raw_ostream.
1226 ///
1227 /// Register units are named after their root registers:
1228 ///
1229 ///   al      - Single root.
1230 ///   fp0~st7 - Dual roots.
1231 ///
1232 /// Usage: OS << printRegUnit(Unit, TRI) << '\n';
1233 Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI);
1234 
1235 /// Create Printable object to print virtual registers and physical
1236 /// registers on a \ref raw_ostream.
1237 Printable printVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI);
1238 
1239 /// Create Printable object to print register classes or register banks
1240 /// on a \ref raw_ostream.
1241 Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo,
1242                               const TargetRegisterInfo *TRI);
1243 
1244 } // end namespace llvm
1245 
1246 #endif // LLVM_CODEGEN_TARGETREGISTERINFO_H
1247