1 //==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- C++ -*-==//
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
7 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H
16 #define LLVM_CODEGEN_TARGETREGISTERINFO_H
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"
38 class MachineFunction
;
44 class TargetRegisterClass
{
46 using iterator
= const MCPhysReg
*;
47 using const_iterator
= const MCPhysReg
*;
48 using sc_iterator
= const TargetRegisterClass
* const *;
50 // Instance variables filled by tablegen, do not use!
51 const MCRegisterClass
*MC
;
52 const uint32_t *SubClassMask
;
53 const uint16_t *SuperRegIndices
;
54 const LaneBitmask LaneMask
;
55 /// Classes with a higher priority value are assigned first by register
56 /// allocators using a greedy heuristic. The value is in the range [0,63].
57 const uint8_t AllocationPriority
;
58 /// Whether the class supports two (or more) disjunct subregister indices.
59 const bool HasDisjunctSubRegs
;
60 /// Whether a combination of subregisters can cover every register in the
61 /// class. See also the CoveredBySubRegs description in Target.td.
62 const bool CoveredBySubRegs
;
63 const sc_iterator SuperClasses
;
64 ArrayRef
<MCPhysReg
> (*OrderFunc
)(const MachineFunction
&);
66 /// Return the register class ID number.
67 unsigned getID() const { return MC
->getID(); }
69 /// begin/end - Return all of the registers in this class.
71 iterator
begin() const { return MC
->begin(); }
72 iterator
end() const { return MC
->end(); }
74 /// Return the number of registers in this class.
75 unsigned getNumRegs() const { return MC
->getNumRegs(); }
77 iterator_range
<SmallVectorImpl
<MCPhysReg
>::const_iterator
>
78 getRegisters() const {
79 return make_range(MC
->begin(), MC
->end());
82 /// Return the specified register in the class.
83 unsigned getRegister(unsigned i
) const {
84 return MC
->getRegister(i
);
87 /// Return true if the specified register is included in this register class.
88 /// This does not include virtual registers.
89 bool contains(unsigned Reg
) const {
90 /// FIXME: Historically this function has returned false when given vregs
91 /// but it should probably only receive physical registers
92 if (!Register::isPhysicalRegister(Reg
))
94 return MC
->contains(Reg
);
97 /// Return true if both registers are in this class.
98 bool contains(unsigned Reg1
, unsigned Reg2
) const {
99 /// FIXME: Historically this function has returned false when given a vregs
100 /// but it should probably only receive physical registers
101 if (!Register::isPhysicalRegister(Reg1
) ||
102 !Register::isPhysicalRegister(Reg2
))
104 return MC
->contains(Reg1
, Reg2
);
107 /// Return the cost of copying a value between two registers in this class.
108 /// A negative number means the register class is very expensive
109 /// to copy e.g. status flag register classes.
110 int getCopyCost() const { return MC
->getCopyCost(); }
112 /// Return true if this register class may be used to create virtual
114 bool isAllocatable() const { return MC
->isAllocatable(); }
116 /// Return true if the specified TargetRegisterClass
117 /// is a proper sub-class of this TargetRegisterClass.
118 bool hasSubClass(const TargetRegisterClass
*RC
) const {
119 return RC
!= this && hasSubClassEq(RC
);
122 /// Returns true if RC is a sub-class of or equal to this class.
123 bool hasSubClassEq(const TargetRegisterClass
*RC
) const {
124 unsigned ID
= RC
->getID();
125 return (SubClassMask
[ID
/ 32] >> (ID
% 32)) & 1;
128 /// Return true if the specified TargetRegisterClass is a
129 /// proper super-class of this TargetRegisterClass.
130 bool hasSuperClass(const TargetRegisterClass
*RC
) const {
131 return RC
->hasSubClass(this);
134 /// Returns true if RC is a super-class of or equal to this class.
135 bool hasSuperClassEq(const TargetRegisterClass
*RC
) const {
136 return RC
->hasSubClassEq(this);
139 /// Returns a bit vector of subclasses, including this one.
140 /// The vector is indexed by class IDs.
142 /// To use it, consider the returned array as a chunk of memory that
143 /// contains an array of bits of size NumRegClasses. Each 32-bit chunk
144 /// contains a bitset of the ID of the subclasses in big-endian style.
146 /// I.e., the representation of the memory from left to right at the
147 /// bit level looks like:
148 /// [31 30 ... 1 0] [ 63 62 ... 33 32] ...
149 /// [ XXX NumRegClasses NumRegClasses - 1 ... ]
150 /// Where the number represents the class ID and XXX bits that
151 /// should be ignored.
153 /// See the implementation of hasSubClassEq for an example of how it
155 const uint32_t *getSubClassMask() const {
159 /// Returns a 0-terminated list of sub-register indices that project some
160 /// super-register class into this register class. The list has an entry for
161 /// each Idx such that:
163 /// There exists SuperRC where:
164 /// For all Reg in SuperRC:
165 /// this->contains(Reg:Idx)
166 const uint16_t *getSuperRegIndices() const {
167 return SuperRegIndices
;
170 /// Returns a NULL-terminated list of super-classes. The
171 /// classes are ordered by ID which is also a topological ordering from large
172 /// to small classes. The list does NOT include the current class.
173 sc_iterator
getSuperClasses() const {
177 /// Return true if this TargetRegisterClass is a subset
178 /// class of at least one other TargetRegisterClass.
179 bool isASubClass() const {
180 return SuperClasses
[0] != nullptr;
183 /// Returns the preferred order for allocating registers from this register
184 /// class in MF. The raw order comes directly from the .td file and may
185 /// include reserved registers that are not allocatable.
186 /// Register allocators should also make sure to allocate
187 /// callee-saved registers only after all the volatiles are used. The
188 /// RegisterClassInfo class provides filtered allocation orders with
189 /// callee-saved registers moved to the end.
191 /// The MachineFunction argument can be used to tune the allocatable
192 /// registers based on the characteristics of the function, subtarget, or
195 /// By default, this method returns all registers in the class.
196 ArrayRef
<MCPhysReg
> getRawAllocationOrder(const MachineFunction
&MF
) const {
197 return OrderFunc
? OrderFunc(MF
) : makeArrayRef(begin(), getNumRegs());
200 /// Returns the combination of all lane masks of register in this class.
201 /// The lane masks of the registers are the combination of all lane masks
202 /// of their subregisters. Returns 1 if there are no subregisters.
203 LaneBitmask
getLaneMask() const {
208 /// Extra information, not in MCRegisterDesc, about registers.
209 /// These are used by codegen, not by MC.
210 struct TargetRegisterInfoDesc
{
211 unsigned CostPerUse
; // Extra cost of instructions using register.
212 bool inAllocatableClass
; // Register belongs to an allocatable regclass.
215 /// Each TargetRegisterClass has a per register weight, and weight
216 /// limit which must be less than the limits of its pressure sets.
217 struct RegClassWeight
{
219 unsigned WeightLimit
;
222 /// TargetRegisterInfo base class - We assume that the target defines a static
223 /// array of TargetRegisterDesc objects that represent all of the machine
224 /// registers that the target has. As such, we simply have to track a pointer
225 /// to this array so that we can turn register number into a register
228 class TargetRegisterInfo
: public MCRegisterInfo
{
230 using regclass_iterator
= const TargetRegisterClass
* const *;
231 using vt_iterator
= const MVT::SimpleValueType
*;
232 struct RegClassInfo
{
233 unsigned RegSize
, SpillSize
, SpillAlignment
;
237 const TargetRegisterInfoDesc
*InfoDesc
; // Extra desc array for codegen
238 const char *const *SubRegIndexNames
; // Names of subreg indexes.
239 // Pointer to array of lane masks, one per sub-reg index.
240 const LaneBitmask
*SubRegIndexLaneMasks
;
242 regclass_iterator RegClassBegin
, RegClassEnd
; // List of regclasses
243 LaneBitmask CoveringLanes
;
244 const RegClassInfo
*const RCInfos
;
248 TargetRegisterInfo(const TargetRegisterInfoDesc
*ID
,
249 regclass_iterator RCB
,
250 regclass_iterator RCE
,
251 const char *const *SRINames
,
252 const LaneBitmask
*SRILaneMasks
,
253 LaneBitmask CoveringLanes
,
254 const RegClassInfo
*const RCIs
,
256 virtual ~TargetRegisterInfo();
259 // Register numbers can represent physical registers, virtual registers, and
260 // sometimes stack slots. The unsigned values are divided into these ranges:
262 // 0 Not a register, can be used as a sentinel.
263 // [1;2^30) Physical registers assigned by TableGen.
264 // [2^30;2^31) Stack slots. (Rarely used.)
265 // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
267 // Further sentinels can be allocated from the small negative integers.
268 // DenseMapInfo<unsigned> uses -1u and -2u.
270 /// Return the size in bits of a register from class RC.
271 unsigned getRegSizeInBits(const TargetRegisterClass
&RC
) const {
272 return getRegClassInfo(RC
).RegSize
;
275 /// Return the size in bytes of the stack slot allocated to hold a spilled
276 /// copy of a register from class RC.
277 unsigned getSpillSize(const TargetRegisterClass
&RC
) const {
278 return getRegClassInfo(RC
).SpillSize
/ 8;
281 /// Return the minimum required alignment in bytes for a spill slot for
282 /// a register of this class.
283 unsigned getSpillAlignment(const TargetRegisterClass
&RC
) const {
284 return getRegClassInfo(RC
).SpillAlignment
/ 8;
287 /// Return true if the given TargetRegisterClass has the ValueType T.
288 bool isTypeLegalForClass(const TargetRegisterClass
&RC
, MVT T
) const {
289 for (auto I
= legalclasstypes_begin(RC
); *I
!= MVT::Other
; ++I
)
295 /// Loop over all of the value types that can be represented by values
296 /// in the given register class.
297 vt_iterator
legalclasstypes_begin(const TargetRegisterClass
&RC
) const {
298 return getRegClassInfo(RC
).VTList
;
301 vt_iterator
legalclasstypes_end(const TargetRegisterClass
&RC
) const {
302 vt_iterator I
= legalclasstypes_begin(RC
);
303 while (*I
!= MVT::Other
)
308 /// Returns the Register Class of a physical register of the given type,
309 /// picking the most sub register class of the right type that contains this
311 const TargetRegisterClass
*
312 getMinimalPhysRegClass(unsigned Reg
, MVT VT
= MVT::Other
) const;
314 /// Return the maximal subclass of the given register class that is
315 /// allocatable or NULL.
316 const TargetRegisterClass
*
317 getAllocatableClass(const TargetRegisterClass
*RC
) const;
319 /// Returns a bitset indexed by register number indicating if a register is
320 /// allocatable or not. If a register class is specified, returns the subset
322 BitVector
getAllocatableSet(const MachineFunction
&MF
,
323 const TargetRegisterClass
*RC
= nullptr) const;
325 /// Return the additional cost of using this register instead
326 /// of other registers in its class.
327 unsigned getCostPerUse(unsigned RegNo
) const {
328 return InfoDesc
[RegNo
].CostPerUse
;
331 /// Return true if the register is in the allocation of any register class.
332 bool isInAllocatableClass(unsigned RegNo
) const {
333 return InfoDesc
[RegNo
].inAllocatableClass
;
336 /// Return the human-readable symbolic target-specific
337 /// name for the specified SubRegIndex.
338 const char *getSubRegIndexName(unsigned SubIdx
) const {
339 assert(SubIdx
&& SubIdx
< getNumSubRegIndices() &&
340 "This is not a subregister index");
341 return SubRegIndexNames
[SubIdx
-1];
344 /// Return a bitmask representing the parts of a register that are covered by
345 /// SubIdx \see LaneBitmask.
347 /// SubIdx == 0 is allowed, it has the lane mask ~0u.
348 LaneBitmask
getSubRegIndexLaneMask(unsigned SubIdx
) const {
349 assert(SubIdx
< getNumSubRegIndices() && "This is not a subregister index");
350 return SubRegIndexLaneMasks
[SubIdx
];
353 /// The lane masks returned by getSubRegIndexLaneMask() above can only be
354 /// used to determine if sub-registers overlap - they can't be used to
355 /// determine if a set of sub-registers completely cover another
358 /// The X86 general purpose registers have two lanes corresponding to the
359 /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
360 /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
361 /// sub_32bit sub-register.
363 /// On the other hand, the ARM NEON lanes fully cover their registers: The
364 /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
365 /// This is related to the CoveredBySubRegs property on register definitions.
367 /// This function returns a bit mask of lanes that completely cover their
368 /// sub-registers. More precisely, given:
370 /// Covering = getCoveringLanes();
371 /// MaskA = getSubRegIndexLaneMask(SubA);
372 /// MaskB = getSubRegIndexLaneMask(SubB);
374 /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
376 LaneBitmask
getCoveringLanes() const { return CoveringLanes
; }
378 /// Returns true if the two registers are equal or alias each other.
379 /// The registers may be virtual registers.
380 bool regsOverlap(Register regA
, Register regB
) const {
381 if (regA
== regB
) return true;
382 if (regA
.isVirtual() || regB
.isVirtual())
385 // Regunits are numerically ordered. Find a common unit.
386 MCRegUnitIterator
RUA(regA
, this);
387 MCRegUnitIterator
RUB(regB
, this);
389 if (*RUA
== *RUB
) return true;
390 if (*RUA
< *RUB
) ++RUA
;
392 } while (RUA
.isValid() && RUB
.isValid());
396 /// Returns true if Reg contains RegUnit.
397 bool hasRegUnit(unsigned Reg
, unsigned RegUnit
) const {
398 for (MCRegUnitIterator
Units(Reg
, this); Units
.isValid(); ++Units
)
399 if (*Units
== RegUnit
)
404 /// Returns the original SrcReg unless it is the target of a copy-like
405 /// operation, in which case we chain backwards through all such operations
406 /// to the ultimate source register. If a physical register is encountered,
407 /// we stop the search.
408 virtual unsigned lookThruCopyLike(unsigned SrcReg
,
409 const MachineRegisterInfo
*MRI
) const;
411 /// Return a null-terminated list of all of the callee-saved registers on
412 /// this target. The register should be in the order of desired callee-save
413 /// stack frame offset. The first register is closest to the incoming stack
414 /// pointer if stack grows down, and vice versa.
415 /// Notice: This function does not take into account disabled CSRs.
416 /// In most cases you will want to use instead the function
417 /// getCalleeSavedRegs that is implemented in MachineRegisterInfo.
418 virtual const MCPhysReg
*
419 getCalleeSavedRegs(const MachineFunction
*MF
) const = 0;
421 /// Return a mask of call-preserved registers for the given calling convention
422 /// on the current function. The mask should include all call-preserved
423 /// aliases. This is used by the register allocator to determine which
424 /// registers can be live across a call.
426 /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
427 /// A set bit indicates that all bits of the corresponding register are
428 /// preserved across the function call. The bit mask is expected to be
429 /// sub-register complete, i.e. if A is preserved, so are all its
432 /// Bits are numbered from the LSB, so the bit for physical register Reg can
433 /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
435 /// A NULL pointer means that no register mask will be used, and call
436 /// instructions should use implicit-def operands to indicate call clobbered
439 virtual const uint32_t *getCallPreservedMask(const MachineFunction
&MF
,
440 CallingConv::ID
) const {
441 // The default mask clobbers everything. All targets should override.
445 /// Return a register mask that clobbers everything.
446 virtual const uint32_t *getNoPreservedMask() const {
447 llvm_unreachable("target does not provide no preserved mask");
450 /// Return a list of all of the registers which are clobbered "inside" a call
451 /// to the given function. For example, these might be needed for PLT
452 /// sequences of long-branch veneers.
453 virtual ArrayRef
<MCPhysReg
>
454 getIntraCallClobberedRegs(const MachineFunction
*MF
) const {
458 /// Return true if all bits that are set in mask \p mask0 are also set in
460 bool regmaskSubsetEqual(const uint32_t *mask0
, const uint32_t *mask1
) const;
462 /// Return all the call-preserved register masks defined for this target.
463 virtual ArrayRef
<const uint32_t *> getRegMasks() const = 0;
464 virtual ArrayRef
<const char *> getRegMaskNames() const = 0;
466 /// Returns a bitset indexed by physical register number indicating if a
467 /// register is a special register that has particular uses and should be
468 /// considered unavailable at all times, e.g. stack pointer, return address.
469 /// A reserved register:
470 /// - is not allocatable
471 /// - is considered always live
472 /// - is ignored by liveness tracking
473 /// It is often necessary to reserve the super registers of a reserved
474 /// register as well, to avoid them getting allocated indirectly. You may use
475 /// markSuperRegs() and checkAllSuperRegsMarked() in this case.
476 virtual BitVector
getReservedRegs(const MachineFunction
&MF
) const = 0;
478 /// Returns false if we can't guarantee that Physreg, specified as an IR asm
479 /// clobber constraint, will be preserved across the statement.
480 virtual bool isAsmClobberable(const MachineFunction
&MF
,
481 unsigned PhysReg
) const {
485 /// Returns true if PhysReg is unallocatable and constant throughout the
486 /// function. Used by MachineRegisterInfo::isConstantPhysReg().
487 virtual bool isConstantPhysReg(unsigned PhysReg
) const { return false; }
489 /// Returns true if the register class is considered divergent.
490 virtual bool isDivergentRegClass(const TargetRegisterClass
*RC
) const {
494 /// Physical registers that may be modified within a function but are
495 /// guaranteed to be restored before any uses. This is useful for targets that
496 /// have call sequences where a GOT register may be updated by the caller
497 /// prior to a call and is guaranteed to be restored (also by the caller)
499 virtual bool isCallerPreservedPhysReg(unsigned PhysReg
,
500 const MachineFunction
&MF
) const {
504 /// This is a wrapper around getCallPreservedMask().
505 /// Return true if the register is preserved after the call.
506 virtual bool isCalleeSavedPhysReg(unsigned PhysReg
,
507 const MachineFunction
&MF
) const;
509 /// Prior to adding the live-out mask to a stackmap or patchpoint
510 /// instruction, provide the target the opportunity to adjust it (mainly to
511 /// remove pseudo-registers that should be ignored).
512 virtual void adjustStackMapLiveOutMask(uint32_t *Mask
) const {}
514 /// Return a super-register of the specified register
515 /// Reg so its sub-register of index SubIdx is Reg.
516 unsigned getMatchingSuperReg(unsigned Reg
, unsigned SubIdx
,
517 const TargetRegisterClass
*RC
) const {
518 return MCRegisterInfo::getMatchingSuperReg(Reg
, SubIdx
, RC
->MC
);
521 /// Return a subclass of the specified register
522 /// class A so that each register in it has a sub-register of the
523 /// specified sub-register index which is in the specified register class B.
525 /// TableGen will synthesize missing A sub-classes.
526 virtual const TargetRegisterClass
*
527 getMatchingSuperRegClass(const TargetRegisterClass
*A
,
528 const TargetRegisterClass
*B
, unsigned Idx
) const;
530 // For a copy-like instruction that defines a register of class DefRC with
531 // subreg index DefSubReg, reading from another source with class SrcRC and
532 // subregister SrcSubReg return true if this is a preferable copy
533 // instruction or an earlier use should be used.
534 virtual bool shouldRewriteCopySrc(const TargetRegisterClass
*DefRC
,
536 const TargetRegisterClass
*SrcRC
,
537 unsigned SrcSubReg
) const;
539 /// Returns the largest legal sub-class of RC that
540 /// supports the sub-register index Idx.
541 /// If no such sub-class exists, return NULL.
542 /// If all registers in RC already have an Idx sub-register, return RC.
544 /// TableGen generates a version of this function that is good enough in most
545 /// cases. Targets can override if they have constraints that TableGen
546 /// doesn't understand. For example, the x86 sub_8bit sub-register index is
547 /// supported by the full GR32 register class in 64-bit mode, but only by the
548 /// GR32_ABCD regiister class in 32-bit mode.
550 /// TableGen will synthesize missing RC sub-classes.
551 virtual const TargetRegisterClass
*
552 getSubClassWithSubReg(const TargetRegisterClass
*RC
, unsigned Idx
) const {
553 assert(Idx
== 0 && "Target has no sub-registers");
557 /// Return the subregister index you get from composing
558 /// two subregister indices.
560 /// The special null sub-register index composes as the identity.
562 /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
563 /// returns c. Note that composeSubRegIndices does not tell you about illegal
564 /// compositions. If R does not have a subreg a, or R:a does not have a subreg
565 /// b, composeSubRegIndices doesn't tell you.
567 /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
568 /// ssub_0:S0 - ssub_3:S3 subregs.
569 /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
570 unsigned composeSubRegIndices(unsigned a
, unsigned b
) const {
573 return composeSubRegIndicesImpl(a
, b
);
576 /// Transforms a LaneMask computed for one subregister to the lanemask that
577 /// would have been computed when composing the subsubregisters with IdxA
578 /// first. @sa composeSubRegIndices()
579 LaneBitmask
composeSubRegIndexLaneMask(unsigned IdxA
,
580 LaneBitmask Mask
) const {
583 return composeSubRegIndexLaneMaskImpl(IdxA
, Mask
);
586 /// Transform a lanemask given for a virtual register to the corresponding
587 /// lanemask before using subregister with index \p IdxA.
588 /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a
589 /// valie lane mask (no invalid bits set) the following holds:
590 /// X0 = composeSubRegIndexLaneMask(Idx, Mask)
591 /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0)
593 LaneBitmask
reverseComposeSubRegIndexLaneMask(unsigned IdxA
,
594 LaneBitmask LaneMask
) const {
597 return reverseComposeSubRegIndexLaneMaskImpl(IdxA
, LaneMask
);
600 /// Debugging helper: dump register in human readable form to dbgs() stream.
601 static void dumpReg(unsigned Reg
, unsigned SubRegIndex
= 0,
602 const TargetRegisterInfo
* TRI
= nullptr);
605 /// Overridden by TableGen in targets that have sub-registers.
606 virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
607 llvm_unreachable("Target has no sub-registers");
610 /// Overridden by TableGen in targets that have sub-registers.
612 composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask
) const {
613 llvm_unreachable("Target has no sub-registers");
616 virtual LaneBitmask
reverseComposeSubRegIndexLaneMaskImpl(unsigned,
618 llvm_unreachable("Target has no sub-registers");
622 /// Find a common super-register class if it exists.
624 /// Find a register class, SuperRC and two sub-register indices, PreA and
627 /// 1. PreA + SubA == PreB + SubB (using composeSubRegIndices()), and
629 /// 2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
631 /// 3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
633 /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
634 /// requirements, and there is no register class with a smaller spill size
635 /// that satisfies the requirements.
637 /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
639 /// Either of the PreA and PreB sub-register indices may be returned as 0. In
640 /// that case, the returned register class will be a sub-class of the
641 /// corresponding argument register class.
643 /// The function returns NULL if no register class can be found.
644 const TargetRegisterClass
*
645 getCommonSuperRegClass(const TargetRegisterClass
*RCA
, unsigned SubA
,
646 const TargetRegisterClass
*RCB
, unsigned SubB
,
647 unsigned &PreA
, unsigned &PreB
) const;
649 //===--------------------------------------------------------------------===//
650 // Register Class Information
653 const RegClassInfo
&getRegClassInfo(const TargetRegisterClass
&RC
) const {
654 return RCInfos
[getNumRegClasses() * HwMode
+ RC
.getID()];
658 /// Register class iterators
659 regclass_iterator
regclass_begin() const { return RegClassBegin
; }
660 regclass_iterator
regclass_end() const { return RegClassEnd
; }
661 iterator_range
<regclass_iterator
> regclasses() const {
662 return make_range(regclass_begin(), regclass_end());
665 unsigned getNumRegClasses() const {
666 return (unsigned)(regclass_end()-regclass_begin());
669 /// Returns the register class associated with the enumeration value.
670 /// See class MCOperandInfo.
671 const TargetRegisterClass
*getRegClass(unsigned i
) const {
672 assert(i
< getNumRegClasses() && "Register Class ID out of range");
673 return RegClassBegin
[i
];
676 /// Returns the name of the register class.
677 const char *getRegClassName(const TargetRegisterClass
*Class
) const {
678 return MCRegisterInfo::getRegClassName(Class
->MC
);
681 /// Find the largest common subclass of A and B.
682 /// Return NULL if there is no common subclass.
683 const TargetRegisterClass
*
684 getCommonSubClass(const TargetRegisterClass
*A
,
685 const TargetRegisterClass
*B
) const;
687 /// Returns a TargetRegisterClass used for pointer values.
688 /// If a target supports multiple different pointer register classes,
689 /// kind specifies which one is indicated.
690 virtual const TargetRegisterClass
*
691 getPointerRegClass(const MachineFunction
&MF
, unsigned Kind
=0) const {
692 llvm_unreachable("Target didn't implement getPointerRegClass!");
695 /// Returns a legal register class to copy a register in the specified class
696 /// to or from. If it is possible to copy the register directly without using
697 /// a cross register class copy, return the specified RC. Returns NULL if it
698 /// is not possible to copy between two registers of the specified class.
699 virtual const TargetRegisterClass
*
700 getCrossCopyRegClass(const TargetRegisterClass
*RC
) const {
704 /// Returns the largest super class of RC that is legal to use in the current
705 /// sub-target and has the same spill size.
706 /// The returned register class can be used to create virtual registers which
707 /// means that all its registers can be copied and spilled.
708 virtual const TargetRegisterClass
*
709 getLargestLegalSuperClass(const TargetRegisterClass
*RC
,
710 const MachineFunction
&) const {
711 /// The default implementation is very conservative and doesn't allow the
712 /// register allocator to inflate register classes.
716 /// Return the register pressure "high water mark" for the specific register
717 /// class. The scheduler is in high register pressure mode (for the specific
718 /// register class) if it goes over the limit.
720 /// Note: this is the old register pressure model that relies on a manually
721 /// specified representative register class per value type.
722 virtual unsigned getRegPressureLimit(const TargetRegisterClass
*RC
,
723 MachineFunction
&MF
) const {
727 /// Return a heuristic for the machine scheduler to compare the profitability
728 /// of increasing one register pressure set versus another. The scheduler
729 /// will prefer increasing the register pressure of the set which returns
730 /// the largest value for this function.
731 virtual unsigned getRegPressureSetScore(const MachineFunction
&MF
,
732 unsigned PSetID
) const {
736 /// Get the weight in units of pressure for this register class.
737 virtual const RegClassWeight
&getRegClassWeight(
738 const TargetRegisterClass
*RC
) const = 0;
740 /// Returns size in bits of a phys/virtual/generic register.
741 unsigned getRegSizeInBits(unsigned Reg
, const MachineRegisterInfo
&MRI
) const;
743 /// Get the weight in units of pressure for this register unit.
744 virtual unsigned getRegUnitWeight(unsigned RegUnit
) const = 0;
746 /// Get the number of dimensions of register pressure.
747 virtual unsigned getNumRegPressureSets() const = 0;
749 /// Get the name of this register unit pressure set.
750 virtual const char *getRegPressureSetName(unsigned Idx
) const = 0;
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;
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;
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;
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. If true is returned, regalloc will try to only use
770 /// hints to the greatest extent possible even if it means spilling.
772 /// The Order argument is the allocation order for VirtReg's register class
773 /// as returned from RegisterClassInfo::getOrder(). The hint registers must
774 /// come from Order, and they must not be reserved.
776 /// The default implementation of this function will only add target
777 /// independent register allocation hints. Targets that override this
778 /// function should typically call this default implementation as well and
779 /// expect to see generic copy hints added.
780 virtual bool 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)
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 {
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; }
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; }
814 /// Returns true if the target requires (and can make use of) the register
816 virtual bool requiresRegisterScavenging(const MachineFunction
&MF
) const {
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 {
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 {
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 {
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 {
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 {
856 /// Returns true if the live-ins should be tracked after register allocation.
857 virtual bool trackLivenessAfterRegAlloc(const MachineFunction
&MF
) const {
861 /// True if the stack can be realigned for the target.
862 virtual bool canRealignStack(const MachineFunction
&MF
) const;
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
868 bool needsStackRealignment(const MachineFunction
&MF
) const;
870 /// Get the offset from the referenced frame index in the instruction,
872 virtual int64_t getFrameIndexInstrOffset(const MachineInstr
*MI
,
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 {
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 "
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");
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");
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 virtual bool saveScavengerRegister(MachineBasicBlock
&MBB
,
913 MachineBasicBlock::iterator I
,
914 MachineBasicBlock::iterator
&UseMI
,
915 const TargetRegisterClass
*RC
,
916 unsigned Reg
) const {
920 /// This method must be overriden to eliminate abstract frame indices from
921 /// instructions which may use them. The instruction referenced by the
922 /// iterator contains an MO_FrameIndex operand which must be eliminated by
923 /// this method. This method may modify or replace the specified instruction,
924 /// as long as it keeps the iterator pointing at the finished product.
925 /// SPAdj is the SP adjustment due to call frame setup instruction.
926 /// FIOperandNum is the FI operand number.
927 virtual void eliminateFrameIndex(MachineBasicBlock::iterator MI
,
928 int SPAdj
, unsigned FIOperandNum
,
929 RegScavenger
*RS
= nullptr) const = 0;
931 /// Return the assembly name for \p Reg.
932 virtual StringRef
getRegAsmName(unsigned Reg
) const {
933 // FIXME: We are assuming that the assembly name is equal to the TableGen
934 // name converted to lower case
936 // The TableGen name is the name of the definition for this register in the
937 // target's tablegen files. For example, the TableGen name of
938 // def EAX : Register <...>; is "EAX"
939 return StringRef(getName(Reg
));
942 //===--------------------------------------------------------------------===//
945 /// SrcRC and DstRC will be morphed into NewRC if this returns true.
946 virtual bool shouldCoalesce(MachineInstr
*MI
,
947 const TargetRegisterClass
*SrcRC
,
949 const TargetRegisterClass
*DstRC
,
951 const TargetRegisterClass
*NewRC
,
952 LiveIntervals
&LIS
) const
955 //===--------------------------------------------------------------------===//
956 /// Debug information queries.
958 /// getFrameRegister - This method should return the register used as a base
959 /// for values allocated in the current stack frame.
960 virtual Register
getFrameRegister(const MachineFunction
&MF
) const = 0;
962 /// Mark a register and all its aliases as reserved in the given set.
963 void markSuperRegs(BitVector
&RegisterSet
, unsigned Reg
) const;
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;
970 virtual const TargetRegisterClass
*
971 getConstrainedRegClassForOperand(const MachineOperand
&MO
,
972 const MachineRegisterInfo
&MRI
) const {
976 /// Returns the physical register number of sub-register "Index"
977 /// for physical register RegNo. Return zero if the sub-register does not
979 inline Register
getSubReg(MCRegister Reg
, unsigned Idx
) const {
980 return static_cast<const MCRegisterInfo
*>(this)->getSubReg(Reg
, Idx
);
984 //===----------------------------------------------------------------------===//
985 // SuperRegClassIterator
986 //===----------------------------------------------------------------------===//
988 // Iterate over the possible super-registers for a given register class. The
989 // iterator will visit a list of pairs (Idx, Mask) corresponding to the
990 // possible classes of super-registers.
992 // Each bit mask will have at least one set bit, and each set bit in Mask
993 // corresponds to a SuperRC such that:
995 // For all Reg in SuperRC: Reg:Idx is in RC.
997 // The iterator can include (O, RC->getSubClassMask()) as the first entry which
998 // also satisfies the above requirement, assuming Reg:0 == Reg.
1000 class SuperRegClassIterator
{
1001 const unsigned RCMaskWords
;
1002 unsigned SubReg
= 0;
1003 const uint16_t *Idx
;
1004 const uint32_t *Mask
;
1007 /// Create a SuperRegClassIterator that visits all the super-register classes
1008 /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
1009 SuperRegClassIterator(const TargetRegisterClass
*RC
,
1010 const TargetRegisterInfo
*TRI
,
1011 bool IncludeSelf
= false)
1012 : RCMaskWords((TRI
->getNumRegClasses() + 31) / 32),
1013 Idx(RC
->getSuperRegIndices()), Mask(RC
->getSubClassMask()) {
1018 /// Returns true if this iterator is still pointing at a valid entry.
1019 bool isValid() const { return Idx
; }
1021 /// Returns the current sub-register index.
1022 unsigned getSubReg() const { return SubReg
; }
1024 /// Returns the bit mask of register classes that getSubReg() projects into
1026 /// See TargetRegisterClass::getSubClassMask() for how to use it.
1027 const uint32_t *getMask() const { return Mask
; }
1029 /// Advance iterator to the next entry.
1031 assert(isValid() && "Cannot move iterator past end.");
1032 Mask
+= RCMaskWords
;
1039 //===----------------------------------------------------------------------===//
1040 // BitMaskClassIterator
1041 //===----------------------------------------------------------------------===//
1042 /// This class encapuslates the logic to iterate over bitmask returned by
1043 /// the various RegClass related APIs.
1044 /// E.g., this class can be used to iterate over the subclasses provided by
1045 /// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask.
1046 class BitMaskClassIterator
{
1047 /// Total number of register classes.
1048 const unsigned NumRegClasses
;
1049 /// Base index of CurrentChunk.
1050 /// In other words, the number of bit we read to get at the
1051 /// beginning of that chunck.
1053 /// Adjust base index of CurrentChunk.
1054 /// Base index + how many bit we read within CurrentChunk.
1056 /// Current register class ID.
1058 /// Mask we are iterating over.
1059 const uint32_t *Mask
;
1060 /// Current chunk of the Mask we are traversing.
1061 uint32_t CurrentChunk
;
1063 /// Move ID to the next set bit.
1064 void moveToNextID() {
1065 // If the current chunk of memory is empty, move to the next one,
1066 // while making sure we do not go pass the number of register
1068 while (!CurrentChunk
) {
1069 // Move to the next chunk.
1071 if (Base
>= NumRegClasses
) {
1075 CurrentChunk
= *++Mask
;
1078 // Otherwise look for the first bit set from the right
1079 // (representation of the class ID is big endian).
1080 // See getSubClassMask for more details on the representation.
1081 unsigned Offset
= countTrailingZeros(CurrentChunk
);
1082 // Add the Offset to the adjusted base number of this chunk: Idx.
1083 // This is the ID of the register class.
1086 // Consume the zeros, if any, and the bit we just read
1087 // so that we are at the right spot for the next call.
1088 // Do not do Offset + 1 because Offset may be 31 and 32
1089 // will be UB for the shift, though in that case we could
1090 // have make the chunk being equal to 0, but that would
1091 // have introduced a if statement.
1096 /// Move \p NumBits Bits forward in CurrentChunk.
1097 void moveNBits(unsigned NumBits
) {
1098 assert(NumBits
< 32 && "Undefined behavior spotted!");
1099 // Consume the bit we read for the next call.
1100 CurrentChunk
>>= NumBits
;
1101 // Adjust the base for the chunk.
1106 /// Create a BitMaskClassIterator that visits all the register classes
1107 /// represented by \p Mask.
1109 /// \pre \p Mask != nullptr
1110 BitMaskClassIterator(const uint32_t *Mask
, const TargetRegisterInfo
&TRI
)
1111 : NumRegClasses(TRI
.getNumRegClasses()), Mask(Mask
), CurrentChunk(*Mask
) {
1112 // Move to the first ID.
1116 /// Returns true if this iterator is still pointing at a valid entry.
1117 bool isValid() const { return getID() != NumRegClasses
; }
1119 /// Returns the current register class ID.
1120 unsigned getID() const { return ID
; }
1122 /// Advance iterator to the next entry.
1124 assert(isValid() && "Cannot move iterator past end.");
1129 // This is useful when building IndexedMaps keyed on virtual registers
1130 struct VirtReg2IndexFunctor
{
1131 using argument_type
= unsigned;
1132 unsigned operator()(unsigned Reg
) const {
1133 return Register::virtReg2Index(Reg
);
1137 /// Prints virtual and physical registers with or without a TRI instance.
1140 /// %noreg - NoRegister
1141 /// %5 - a virtual register.
1142 /// %5:sub_8bit - a virtual register with sub-register index (with TRI).
1143 /// %eax - a physical register
1144 /// %physreg17 - a physical register when no TRI instance given.
1146 /// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n';
1147 Printable
printReg(Register Reg
, const TargetRegisterInfo
*TRI
= nullptr,
1148 unsigned SubIdx
= 0,
1149 const MachineRegisterInfo
*MRI
= nullptr);
1151 /// Create Printable object to print register units on a \ref raw_ostream.
1153 /// Register units are named after their root registers:
1155 /// al - Single root.
1156 /// fp0~st7 - Dual roots.
1158 /// Usage: OS << printRegUnit(Unit, TRI) << '\n';
1159 Printable
printRegUnit(unsigned Unit
, const TargetRegisterInfo
*TRI
);
1161 /// Create Printable object to print virtual registers and physical
1162 /// registers on a \ref raw_ostream.
1163 Printable
printVRegOrUnit(unsigned VRegOrUnit
, const TargetRegisterInfo
*TRI
);
1165 /// Create Printable object to print register classes or register banks
1166 /// on a \ref raw_ostream.
1167 Printable
printRegClassOrBank(unsigned Reg
, const MachineRegisterInfo
&RegInfo
,
1168 const TargetRegisterInfo
*TRI
);
1170 } // end namespace llvm
1172 #endif // LLVM_CODEGEN_TARGETREGISTERINFO_H