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