LLVM 24.0.0git
TargetRegisterInfo.h
Go to the documentation of this file.
1//==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file describes an abstract interface used to get information about a
10// target machines register file. This information is used for a variety of
11// purposed, especially register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H
16#define LLVM_CODEGEN_TARGETREGISTERINFO_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/StringRef.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/MC/LaneBitmask.h"
33#include <cassert>
34#include <cstdint>
35
36namespace llvm {
37
38class BitVector;
39class DIExpression;
40class LiveRegMatrix;
41class MachineFunction;
42class MachineInstr;
44class RegScavenger;
45class VirtRegMap;
46class LiveIntervals;
47class LiveInterval;
48
49// TODO: Remove.
51
52/// Extra information, not in MCRegisterDesc, about registers.
53/// These are used by codegen, not by MC.
55 const uint8_t *CostPerUse; // Extra cost of instructions using register.
56 unsigned NumCosts; // Number of cost values associated with each register.
57 const bool
58 *InAllocatableClass; // Register belongs to an allocatable regclass.
59};
60
61/// Each TargetRegisterClass has a per register weight, and weight
62/// limit which must be less than the limits of its pressure sets.
64 unsigned RegWeight;
65 unsigned WeightLimit;
66};
67
68/// TargetRegisterInfo base class - We assume that the target defines a static
69/// array of TargetRegisterDesc objects that represent all of the machine
70/// registers that the target has. As such, we simply have to track a pointer
71/// to this array so that we can turn register number into a register
72/// descriptor.
73///
75public:
77 struct RegClassInfo {
79 unsigned VTListOffset;
80 };
81
82 /// SubRegCoveredBits - Emitted by tablegen: bit range covered by a subreg
83 /// index, -1 in any being invalid.
88
89private:
90 const TargetRegisterInfoDesc *InfoDesc; // Extra desc array for codegen
91 const char *SubRegIndexStrings; // Names of subreg indexes.
92 ArrayRef<uint32_t> SubRegIndexNameOffsets;
93 const SubRegCoveredBits *SubRegIdxRanges; // Pointer to the subreg covered
94 // bit ranges array.
95
96 // Pointer to array of lane masks, one per sub-reg index.
97 const LaneBitmask *SubRegIndexLaneMasks;
98
99 LaneBitmask CoveringLanes;
100 const RegClassInfo *const RCInfos;
101 const MVT::SimpleValueType *const RCVTLists;
102 unsigned HwMode;
103
104protected:
106 const char *SubRegIndexStrings,
107 ArrayRef<uint32_t> SubRegIndexNameOffsets,
108 const SubRegCoveredBits *SubRegIdxRanges,
109 const LaneBitmask *SubRegIndexLaneMasks,
110 LaneBitmask CoveringLanes,
111 const RegClassInfo *const RCInfos,
112 const MVT::SimpleValueType *const RCVTLists,
113 unsigned Mode = 0);
114
115public:
117
118 /// Return the number of registers for the function. (may overestimate)
119 virtual unsigned getNumSupportedRegs(const MachineFunction &) const {
120 return getNumRegs();
121 }
122
123 // Register numbers can represent physical registers, virtual registers, and
124 // sometimes stack slots. The unsigned values are divided into these ranges:
125 //
126 // 0 Not a register, can be used as a sentinel.
127 // [1;2^30) Physical registers assigned by TableGen.
128 // [2^30;2^31) Stack slots. (Rarely used.)
129 // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
130 //
131 // Further sentinels can be allocated from the small negative integers.
132 // DenseMapInfo<unsigned> uses -1u and -2u.
133
134 /// Return the size in bits of a register from class RC.
138
139 /// Return the size in bytes of the stack slot allocated to hold a spilled
140 /// copy of a register from class RC.
141 unsigned getSpillSize(const TargetRegisterClass &RC) const {
142 return getRegClassInfo(RC).SpillSize / 8;
143 }
144
145 /// Return the minimum required alignment in bytes for a spill slot for
146 /// a register of this class.
148 return Align(getRegClassInfo(RC).SpillAlignment / 8);
149 }
150
151 /// Return the stack ID for spill slots holding a spilled copy of a register
152 /// from this class.
154 return static_cast<TargetStackID::Value>(RC.SpillStackID);
155 }
156
157 /// Return true if the given TargetRegisterClass has the ValueType T.
159 for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I)
160 if (MVT(*I) == T)
161 return true;
162 return false;
163 }
164
165 /// Return true if the given TargetRegisterClass is compatible with LLT T.
167 for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I) {
168 MVT VT(*I);
169 if (VT == MVT::Untyped)
170 return true;
171
172 if (LLT(VT) == T)
173 return true;
174 }
175 return false;
176 }
177
178 /// Loop over all of the value types that can be represented by values
179 /// in the given register class.
181 return &RCVTLists[getRegClassInfo(RC).VTListOffset];
182 }
183
186 while (*I != MVT::Other)
187 ++I;
188 return I;
189 }
190
191 /// Returns the Register Class of a physical register, picking the smallest
192 /// register subclass that contains this physreg.
193 virtual const TargetRegisterClass *
195
196 /// Returns the common Register Class of two physical registers, picking the
197 /// smallest register subclass that contains these two physregs.
198 const TargetRegisterClass *
200
201 /// Return the maximal subclass of the given register class that is
202 /// allocatable or NULL.
203 const TargetRegisterClass *
205
206 /// Returns a bitset indexed by register number indicating if a register is
207 /// allocatable or not. If a register class is specified, returns the subset
208 /// for the class.
210 const TargetRegisterClass *RC = nullptr) const;
211
212 /// Get a list of cost values for all registers that correspond to the index
213 /// returned by RegisterCostTableIndex.
215 unsigned Idx = getRegisterCostTableIndex(MF);
216 unsigned NumRegs = getNumRegs();
217 assert(Idx < InfoDesc->NumCosts && "CostPerUse index out of bounds");
218
219 return ArrayRef(&InfoDesc->CostPerUse[Idx * NumRegs], NumRegs);
220 }
221
222 /// Return true if the register is in the allocation of any register class.
224 return InfoDesc->InAllocatableClass[RegNo];
225 }
226
227 /// Return the human-readable symbolic target-specific name for the specified
228 /// SubRegIndex.
229 const char *getSubRegIndexName(unsigned SubIdx) const {
230 assert(SubIdx && SubIdx < getNumSubRegIndices() &&
231 "This is not a subregister index");
232 return SubRegIndexStrings + SubRegIndexNameOffsets[SubIdx - 1];
233 }
234
235 /// Get the size of the bit range covered by a sub-register index.
236 /// If the index isn't continuous, return the sum of the sizes of its parts.
237 /// If the index is used to access subregisters of different sizes, return -1.
238 unsigned getSubRegIdxSize(unsigned Idx) const;
239
240 /// Get the offset of the bit range covered by a sub-register index.
241 /// If an Offset doesn't make sense (the index isn't continuous, or is used to
242 /// access sub-registers at different offsets), return -1.
243 unsigned getSubRegIdxOffset(unsigned Idx) const;
244
245 /// Return a bitmask representing the parts of a register that are covered by
246 /// SubIdx \see LaneBitmask.
247 ///
248 /// SubIdx == 0 is allowed, it has the lane mask ~0u.
249 LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const {
250 assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index");
251 return SubRegIndexLaneMasks[SubIdx];
252 }
253
254 /// Try to find one or more subregister indexes to cover \p LaneMask.
255 ///
256 /// If this is possible, returns true and appends the best matching set of
257 /// indexes to \p Indexes. If this is not possible, returns false.
258 bool getCoveringSubRegIndexes(const TargetRegisterClass *RC,
259 LaneBitmask LaneMask,
260 SmallVectorImpl<unsigned> &Indexes) const;
261
262 /// The lane masks returned by getSubRegIndexLaneMask() above can only be
263 /// used to determine if sub-registers overlap - they can't be used to
264 /// determine if a set of sub-registers completely cover another
265 /// sub-register.
266 ///
267 /// The X86 general purpose registers have two lanes corresponding to the
268 /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have
269 /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the
270 /// sub_32bit sub-register.
271 ///
272 /// On the other hand, the ARM NEON lanes fully cover their registers: The
273 /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes.
274 /// This is related to the CoveredBySubRegs property on register definitions.
275 ///
276 /// This function returns a bit mask of lanes that completely cover their
277 /// sub-registers. More precisely, given:
278 ///
279 /// Covering = getCoveringLanes();
280 /// MaskA = getSubRegIndexLaneMask(SubA);
281 /// MaskB = getSubRegIndexLaneMask(SubB);
282 ///
283 /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by
284 /// SubB.
285 LaneBitmask getCoveringLanes() const { return CoveringLanes; }
286
287 /// Returns true if the two registers are equal or alias each other.
288 /// The registers may be virtual registers.
289 bool regsOverlap(Register RegA, Register RegB) const {
290 if (RegA == RegB)
291 return true;
292 if (RegA.isPhysical() && RegB.isPhysical())
293 return MCRegisterInfo::regsOverlap(RegA.asMCReg(), RegB.asMCReg());
294 return false;
295 }
296
297 /// Returns true if the two subregisters are equal or overlap.
298 /// The registers may be virtual registers.
299 bool checkSubRegInterference(Register RegA, unsigned SubA, Register RegB,
300 unsigned SubB) const;
301
302 /// Returns true if Reg contains RegUnit.
303 bool hasRegUnit(MCRegister Reg, MCRegUnit RegUnit) const {
304 return llvm::is_contained(regunits(Reg), RegUnit);
305 }
306
307 /// Returns the original SrcReg unless it is the target of a copy-like
308 /// operation, in which case we chain backwards through all such operations
309 /// to the ultimate source register. If a physical register is encountered,
310 /// we stop the search.
311 virtual Register lookThruCopyLike(Register SrcReg,
312 const MachineRegisterInfo *MRI) const;
313
314 /// Find the original SrcReg unless it is the target of a copy-like operation,
315 /// in which case we chain backwards through all such operations to the
316 /// ultimate source register. If a physical register is encountered, we stop
317 /// the search.
318 /// Return the original SrcReg if all the definitions in the chain only have
319 /// one user and not a physical register.
320 virtual Register
321 lookThruSingleUseCopyChain(Register SrcReg,
322 const MachineRegisterInfo *MRI) const;
323
324 /// Return a null-terminated list of all of the callee-saved registers on
325 /// this target. The register should be in the order of desired callee-save
326 /// stack frame offset. The first register is closest to the incoming stack
327 /// pointer if stack grows down, and vice versa.
328 /// Notice: This function does not take into account disabled CSRs.
329 /// In most cases you will want to use instead the function
330 /// getCalleeSavedRegs that is implemented in MachineRegisterInfo.
331 virtual const MCPhysReg*
333
334 /// Return a null-terminated list of all of the callee-saved registers on
335 /// this target when IPRA is on. The list should include any non-allocatable
336 /// registers that the backend uses and assumes will be saved by all calling
337 /// conventions. This is typically the ISA-standard frame pointer, but could
338 /// include the thread pointer, TOC pointer, or base pointer for different
339 /// targets.
340 virtual const MCPhysReg *getIPRACSRegs(const MachineFunction *MF) const {
341 return nullptr;
342 }
343
344 /// Return a mask of call-preserved registers for the given calling convention
345 /// on the current function. The mask should include all call-preserved
346 /// aliases. This is used by the register allocator to determine which
347 /// registers can be live across a call.
348 ///
349 /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
350 /// A set bit indicates that all bits of the corresponding register are
351 /// preserved across the function call. The bit mask is expected to be
352 /// sub-register complete, i.e. if A is preserved, so are all its
353 /// sub-registers.
354 ///
355 /// Bits are numbered from the LSB, so the bit for physical register Reg can
356 /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
357 ///
358 /// A NULL pointer means that no register mask will be used, and call
359 /// instructions should use implicit-def operands to indicate call clobbered
360 /// registers.
361 ///
363 CallingConv::ID) const {
364 // The default mask clobbers everything. All targets should override.
365 return nullptr;
366 }
367
368 /// Return a register mask for the registers preserved by the unwinder,
369 /// or nullptr if no custom mask is needed.
370 virtual const uint32_t *
372 return nullptr;
373 }
374
375 /// Return a register mask that clobbers everything.
376 virtual const uint32_t *getNoPreservedMask() const {
377 llvm_unreachable("target does not provide no preserved mask");
378 }
379
380 /// Return a list of all of the registers which are clobbered "inside" a call
381 /// to the given function. For example, these might be needed for PLT
382 /// sequences of long-branch veneers.
383 virtual ArrayRef<MCPhysReg>
385 return {};
386 }
387
388 /// Return true if all bits that are set in mask \p mask0 are also set in
389 /// \p mask1.
390 bool regmaskSubsetEqual(const uint32_t *mask0, const uint32_t *mask1) const;
391
392 /// Return all the call-preserved register masks defined for this target.
395
396 /// Returns a bitset indexed by physical register number indicating if a
397 /// register is a special register that has particular uses and should be
398 /// considered unavailable at all times, e.g. stack pointer, return address.
399 /// A reserved register:
400 /// - is not allocatable
401 /// - is considered always live
402 /// - is ignored by liveness tracking
403 /// It is often necessary to reserve the super registers of a reserved
404 /// register as well, to avoid them getting allocated indirectly. You may use
405 /// markSuperRegs() and checkAllSuperRegsMarked() in this case.
406 virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0;
407
408 /// Returns either a string explaining why the given register is reserved for
409 /// this function, or an empty optional if no explanation has been written.
410 /// The absence of an explanation does not mean that the register is not
411 /// reserved (meaning, you should check that PhysReg is in fact reserved
412 /// before calling this).
413 virtual std::optional<std::string>
415 return {};
416 }
417
418 /// Returns false if we can't guarantee that Physreg, specified as an IR asm
419 /// clobber constraint, will be preserved across the statement.
420 virtual bool isAsmClobberable(const MachineFunction &MF,
421 MCRegister PhysReg) const {
422 return true;
423 }
424
425 /// Returns true if PhysReg cannot be written to in inline asm statements.
427 MCRegister PhysReg) const {
428 return false;
429 }
430
431 /// Returns true if PhysReg is unallocatable and constant throughout the
432 /// function. Used by MachineRegisterInfo::isConstantPhysReg().
433 virtual bool isConstantPhysReg(MCRegister PhysReg) const { return false; }
434
435 /// Returns true if the register class is considered divergent.
436 virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const {
437 return false;
438 }
439
440 /// Returns true if the register is considered uniform.
441 virtual bool isUniformReg(const MachineRegisterInfo &MRI,
442 const RegisterBankInfo &RBI, Register Reg) const {
443 return false;
444 }
445
446 /// Returns true if MachineLoopInfo should analyze the given physreg
447 /// for loop invariance.
449 return false;
450 }
451
452 /// Physical registers that may be modified within a function but are
453 /// guaranteed to be restored before any uses. This is useful for targets that
454 /// have call sequences where a GOT register may be updated by the caller
455 /// prior to a call and is guaranteed to be restored (also by the caller)
456 /// after the call.
458 const MachineFunction &MF) const {
459 return false;
460 }
461
462 /// This is a wrapper around getCallPreservedMask().
463 /// Return true if the register is preserved after the call.
464 virtual bool isCalleeSavedPhysReg(MCRegister PhysReg,
465 const MachineFunction &MF) const;
466
467 /// Returns true if PhysReg can be used as an argument to a function.
468 virtual bool isArgumentRegister(const MachineFunction &MF,
469 MCRegister PhysReg) const {
470 return false;
471 }
472
473 /// Returns true if PhysReg is a fixed register.
474 virtual bool isFixedRegister(const MachineFunction &MF,
475 MCRegister PhysReg) const {
476 return false;
477 }
478
479 /// Returns true if PhysReg is a general purpose register.
481 MCRegister PhysReg) const {
482 return false;
483 }
484
485 /// Returns true if RC is a class/subclass of general purpose register.
486 virtual bool
488 return false;
489 }
490
491 /// Prior to adding the live-out mask to a stackmap or patchpoint
492 /// instruction, provide the target the opportunity to adjust it (mainly to
493 /// remove pseudo-registers that should be ignored).
494 virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const {}
495
496 /// Return a subclass of the register class \p A so that each register in it
497 /// has a sub-register of sub-register index \p Idx which is in the register
498 /// class \p B.
499 ///
500 /// TableGen will synthesize missing A sub-classes.
501 virtual const TargetRegisterClass *
502 getMatchingSuperRegClass(const TargetRegisterClass *A,
503 const TargetRegisterClass *B, unsigned Idx) const;
504
505 /// Find a common register class that can accomodate both the source and
506 /// destination operands of a copy-like instruction:
507 ///
508 /// DefRC:DefSubReg = COPY SrcRC:SrcSubReg
509 ///
510 /// This is a generalized form of getMatchingSuperRegClass,
511 /// getCommonSuperRegClass, and getCommonSubClass which handles 0, 1, or 2
512 /// subregister indexes. Those utilities should be preferred if the number of
513 /// non-0 subregister indexes is known.
514 const TargetRegisterClass *
515 findCommonRegClass(const TargetRegisterClass *DefRC, unsigned DefSubReg,
516 const TargetRegisterClass *SrcRC,
517 unsigned SrcSubReg) const;
518
519 // For a copy-like instruction that defines a register of class DefRC with
520 // subreg index DefSubReg, reading from another source with class SrcRC and
521 // subregister SrcSubReg return true if this is a preferable copy
522 // instruction or an earlier use should be used.
523 virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
524 unsigned DefSubReg,
525 const TargetRegisterClass *SrcRC,
526 unsigned SrcSubReg) const {
527 // If this source does not incur a cross register bank copy, use it.
528 return findCommonRegClass(DefRC, DefSubReg, SrcRC, SrcSubReg) != nullptr;
529 }
530
531 /// Returns the largest legal sub-class of \p RC that supports the
532 /// sub-register index \p Idx.
533 /// If no such sub-class exists, return NULL.
534 /// If all registers in RC already have an Idx sub-register, return RC.
535 ///
536 /// TableGen generates a version of this function that is good enough in most
537 /// cases. Targets can override if they have constraints that TableGen
538 /// doesn't understand. For example, the x86 sub_8bit sub-register index is
539 /// supported by the full GR32 register class in 64-bit mode, but only by the
540 /// GR32_ABCD regiister class in 32-bit mode.
541 ///
542 /// TableGen will synthesize missing RC sub-classes.
543 virtual const TargetRegisterClass *
544 getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const {
545 assert(Idx == 0 && "Target has no sub-registers");
546 return RC;
547 }
548
549 /// Returns the register class of all sub-registers of \p SuperRC obtained by
550 /// applying the sub-register index \p SubRegIdx.
551 ///
552 /// TableGen *may not* synthesize the missing sub-register classes, so this
553 /// function may return null even if SubRegIdx can be applied to all registers
554 /// in SuperRC, i.e., even if
555 /// isSubRegValidForRegClass(SuperRC, SubRegIdx) is true.
556 virtual const TargetRegisterClass *
558 unsigned SubRegIdx) const {
559 return nullptr;
560 }
561
562 /// Returns true if sub-register \p Idx can be used with register class \p RC.
563 /// Idx is valid if the largest subclass of RC that supports sub-register
564 /// index Idx is same as RC. That is, every physical register in RC supports
565 /// sub-register index Idx.
567 unsigned Idx) const {
568 return getSubClassWithSubReg(RC, Idx) == RC;
569 }
570
571 /// Return the subregister index you get from composing
572 /// two subregister indices.
573 ///
574 /// The special null sub-register index composes as the identity.
575 ///
576 /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b)
577 /// returns c. Note that composeSubRegIndices does not tell you about illegal
578 /// compositions. If R does not have a subreg a, or R:a does not have a subreg
579 /// b, composeSubRegIndices doesn't tell you.
580 ///
581 /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has
582 /// ssub_0:S0 - ssub_3:S3 subregs.
583 /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2.
584 unsigned composeSubRegIndices(unsigned a, unsigned b) const {
585 if (!a) return b;
586 if (!b) return a;
587 return composeSubRegIndicesImpl(a, b);
588 }
589
590 /// Return a subregister index that will compose to give you the subregister
591 /// index.
592 ///
593 /// Finds a subregister index x such that composeSubRegIndices(a, x) ==
594 /// b. Note that this relationship does not hold if
595 /// reverseComposeSubRegIndices returns the null subregister.
596 ///
597 /// The special null sub-register index composes as the identity.
598 unsigned reverseComposeSubRegIndices(unsigned a, unsigned b) const {
599 if (!a)
600 return b;
601 if (!b)
602 return a;
604 }
605
606 /// Transforms a LaneMask computed for one subregister to the lanemask that
607 /// would have been computed when composing the subsubregisters with IdxA
608 /// first. @sa composeSubRegIndices()
610 LaneBitmask Mask) const {
611 if (!IdxA)
612 return Mask;
613 return composeSubRegIndexLaneMaskImpl(IdxA, Mask);
614 }
615
616 /// Transform a lanemask given for a virtual register to the corresponding
617 /// lanemask before using subregister with index \p IdxA.
618 /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a
619 /// valie lane mask (no invalid bits set) the following holds:
620 /// X0 = composeSubRegIndexLaneMask(Idx, Mask)
621 /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0)
622 /// => X1 == Mask
624 LaneBitmask LaneMask) const {
625 if (!IdxA)
626 return LaneMask;
627 return reverseComposeSubRegIndexLaneMaskImpl(IdxA, LaneMask);
628 }
629
630 /// Debugging helper: dump register in human readable form to dbgs() stream.
631 static void dumpReg(Register Reg, unsigned SubRegIndex = 0,
632 const TargetRegisterInfo *TRI = nullptr);
633
634 /// Return target defined base register class for a physical register.
635 /// This is the register class with the lowest BaseClassOrder containing the
636 /// register.
637 /// Will be nullptr if the register is not in any base register class.
639 return nullptr;
640 }
641
642protected:
643 /// Overridden by TableGen in targets that have sub-registers.
644 virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const {
645 llvm_unreachable("Target has no sub-registers");
646 }
647
648 /// Overridden by TableGen in targets that have sub-registers.
649 virtual unsigned reverseComposeSubRegIndicesImpl(unsigned, unsigned) const {
650 llvm_unreachable("Target has no sub-registers");
651 }
652
653 /// Overridden by TableGen in targets that have sub-registers.
654 virtual LaneBitmask
656 llvm_unreachable("Target has no sub-registers");
657 }
658
660 LaneBitmask) const {
661 llvm_unreachable("Target has no sub-registers");
662 }
663
664 /// Return the register cost table index. This implementation is sufficient
665 /// for most architectures and can be overriden by targets in case there are
666 /// multiple cost values associated with each register.
667 virtual unsigned getRegisterCostTableIndex(const MachineFunction &MF) const {
668 return 0;
669 }
670
671public:
672 /// Find a common super-register class if it exists.
673 ///
674 /// Find a register class, SuperRC and two sub-register indices, PreA and
675 /// PreB, such that:
676 ///
677 /// 1. PreA + SubA == PreB + SubB (using composeSubRegIndices()), and
678 ///
679 /// 2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and
680 ///
681 /// 3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()).
682 ///
683 /// SuperRC will be chosen such that no super-class of SuperRC satisfies the
684 /// requirements, and there is no register class with a smaller spill size
685 /// that satisfies the requirements.
686 ///
687 /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead.
688 ///
689 /// Either of the PreA and PreB sub-register indices may be returned as 0. In
690 /// that case, the returned register class will be a sub-class of the
691 /// corresponding argument register class.
692 ///
693 /// The function returns NULL if no register class can be found.
695 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
696 const TargetRegisterClass *RCB, unsigned SubB,
697 unsigned &PreA, unsigned &PreB) const;
698
699 //===--------------------------------------------------------------------===//
700 // Register Class Information
701 //
702protected:
704 return RCInfos[getNumRegClasses() * HwMode + RC.getID()];
705 }
706
707 /// Custom reordering of the allocation order.
708 virtual void filterAndSortForAntiHintedRegs(
709 Register VirtReg, MutableArrayRef<MCPhysReg> CustomOrder,
710 const BitVector &AntiHintedRegUnits, const MachineFunction &MF,
711 const LiveRegMatrix *Matrix = nullptr,
712 const RegisterClassInfo *RegClassInfo = nullptr) const;
713
714public:
715 /// Returns the register class associated with the enumeration value.
716 /// See class MCOperandInfo.
717 const TargetRegisterClass *getRegClass(unsigned i) const {
719 }
720
721 /// Find the largest common subclass of A and B.
722 /// Return NULL if there is no common subclass.
723 const TargetRegisterClass *
724 getCommonSubClass(const TargetRegisterClass *A,
725 const TargetRegisterClass *B) const;
726
727 /// Returns a legal register class to copy a register in the specified class
728 /// to or from. If it is possible to copy the register directly without using
729 /// a cross register class copy, return the specified RC. Returns NULL if it
730 /// is not possible to copy between two registers of the specified class.
731 virtual const TargetRegisterClass *
733 return RC;
734 }
735
736 /// Returns the largest super class of RC that is legal to use in the current
737 /// sub-target and has the same spill size.
738 /// The returned register class can be used to create virtual registers which
739 /// means that all its registers can be copied and spilled.
740 virtual const TargetRegisterClass *
742 const MachineFunction &) const {
743 /// The default implementation is very conservative and doesn't allow the
744 /// register allocator to inflate register classes.
745 return RC;
746 }
747
748 /// Return the register pressure "high water mark" for the specific register
749 /// class. The scheduler is in high register pressure mode (for the specific
750 /// register class) if it goes over the limit.
751 ///
752 /// Note: this is the old register pressure model that relies on a manually
753 /// specified representative register class per value type.
754 virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
755 MachineFunction &MF) const {
756 return 0;
757 }
758
759 /// Return a heuristic for the machine scheduler to compare the profitability
760 /// of increasing one register pressure set versus another. The scheduler
761 /// will prefer increasing the register pressure of the set which returns
762 /// the largest value for this function.
763 virtual unsigned getRegPressureSetScore(const MachineFunction &MF,
764 unsigned PSetID) const {
765 return PSetID;
766 }
767
768 /// Get the weight in units of pressure for this register class.
770 const TargetRegisterClass *RC) const = 0;
771
772 /// Returns size in bits of a phys/virtual/generic register.
774
775 /// Get the weight in units of pressure for this register unit.
776 virtual unsigned getRegUnitWeight(MCRegUnit RegUnit) const = 0;
777
778 /// Get the number of dimensions of register pressure.
779 virtual unsigned getNumRegPressureSets() const = 0;
780
781 /// Get the name of this register unit pressure set.
782 virtual const char *getRegPressureSetName(unsigned Idx) const = 0;
783
784 /// Get the register unit pressure limit for this dimension.
785 /// This limit must be adjusted dynamically for reserved registers.
786 virtual unsigned getRegPressureSetLimit(const MachineFunction &MF,
787 unsigned Idx) const = 0;
788
789 /// Get the register class for this pressure set with the largest
790 /// `RegClassWeight::WeightLimit`.
791 virtual const TargetRegisterClass *
792 getLargestRegClassForRegPressureSet(unsigned Idx) const = 0;
793
794 /// Get the dimensions of register pressure impacted by this register class.
795 /// Returns a -1 terminated array of pressure set IDs.
796 virtual const int *getRegClassPressureSets(
797 const TargetRegisterClass *RC) const = 0;
798
799 /// Get the dimensions of register pressure impacted by this register unit.
800 /// Returns a -1 terminated array of pressure set IDs.
801 virtual const int *getRegUnitPressureSets(MCRegUnit RegUnit) const = 0;
802
803 /// Get the scale factor of spill weight for this register class.
804 virtual float getSpillWeightScaleFactor(const TargetRegisterClass *RC) const;
805
806 /// Returns the preferred order for allocating registers from this register
807 /// class in MF. The raw order comes directly from the .td file and may
808 /// include reserved registers that are not allocatable.
809 /// Register allocators should also make sure to allocate
810 /// callee-saved registers only after all the volatiles are used. The
811 /// RegisterClassInfo class provides filtered allocation orders with
812 /// callee-saved registers moved to the end.
813 ///
814 /// The MachineFunction argument can be used to tune the allocatable
815 /// registers based on the characteristics of the function, subtarget, or
816 /// other criteria.
817 ///
818 /// By default, this method returns all registers in the class.
819 virtual ArrayRef<MCPhysReg>
821 bool /*Rev*/ = false) const {
822 return RC.getRegisters();
823 }
824
825 /// Get a list of 'hint' registers that the register allocator should try
826 /// first when allocating a physical register for the virtual register
827 /// VirtReg. These registers are effectively moved to the front of the
828 /// allocation order. If true is returned, regalloc will try to only use
829 /// hints to the greatest extent possible even if it means spilling.
830 ///
831 /// The Order argument is the allocation order for VirtReg's register class
832 /// as returned from RegisterClassInfo::getOrder(). The hint registers must
833 /// come from Order, and they must not be reserved.
834 ///
835 /// The default implementation of this function will only add target
836 /// independent register allocation hints. Targets that override this
837 /// function should typically call this default implementation as well and
838 /// expect to see generic copy hints added.
839 virtual bool
840 getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order,
842 const MachineFunction &MF,
843 const VirtRegMap *VRM = nullptr,
844 const LiveRegMatrix *Matrix = nullptr) const;
845
846 /// A callback to allow target a chance to update register allocation hints
847 /// when a register is "changed" (e.g. coalesced) to another register.
848 /// e.g. On ARM, some virtual registers should target register pairs,
849 /// if one of pair is coalesced to another register, the allocation hint of
850 /// the other half of the pair should be changed to point to the new register.
852 MachineFunction &MF) const {
853 // Do nothing.
854 }
855
856 /// Return true if Reg overlaps one of the anti-hinted register units.
857 bool isAntiHintedReg(MCPhysReg Reg,
858 const BitVector &AntiHintedRegUnits) const;
859
860 /// Apply anti-hints to the allocation order.
861 void applyRegAllocationAntiHints(
862 Register VirtReg, ArrayRef<MCPhysReg> Order,
863 SmallVectorImpl<MCPhysReg> &HintsAndCustomOrder, unsigned NumHints,
864 const BitVector &AntiHintedRegUnits, const MachineFunction &MF,
865 const LiveRegMatrix *Matrix = nullptr,
866 const RegisterClassInfo *RegClassInfo = nullptr) const;
867
868 /// Allow the target to reverse allocation order of local live ranges. This
869 /// will generally allocate shorter local live ranges first. For targets with
870 /// many registers, this could reduce regalloc compile time by a large
871 /// factor. It is disabled by default for three reasons:
872 /// (1) Top-down allocation is simpler and easier to debug for targets that
873 /// don't benefit from reversing the order.
874 /// (2) Bottom-up allocation could result in poor evicition decisions on some
875 /// targets affecting the performance of compiled code.
876 /// (3) Bottom-up allocation is no longer guaranteed to optimally color.
877 virtual bool reverseLocalAssignment() const { return false; }
878
879 /// Allow the target to override the cost of using a callee-saved register for
880 /// the first time. Default value of 0 means we will use a callee-saved
881 /// register if it is available.
882 virtual unsigned getCSRFirstUseCost(const MachineFunction &MF) const {
883 return 0;
884 }
885 /// FIXME: We should deprecate this usage.
886 virtual unsigned getCSRCost() const { return 0; }
887
888 /// Scale the CSRFirstUseCost with this number.
889 /// The scale is a percentage (e.g., 30 means 30% of the base cost).
890 /// Target can tune and override this default value.
891 virtual unsigned getCSRCostScale(const MachineFunction &MF) const {
892 return 30;
893 }
894
895 /// Returns true if the target requires (and can make use of) the register
896 /// scavenger.
897 virtual bool requiresRegisterScavenging(const MachineFunction &MF) const {
898 return false;
899 }
900
901 /// Returns true if the target wants to use frame pointer based accesses to
902 /// spill to the scavenger emergency spill slot.
903 virtual bool useFPForScavengingIndex(const MachineFunction &MF) const {
904 return true;
905 }
906
907 /// Returns true if the target requires post PEI scavenging of registers for
908 /// materializing frame index constants.
909 virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const {
910 return false;
911 }
912
913 /// Returns true if the target requires using the RegScavenger directly for
914 /// frame elimination despite using requiresFrameIndexScavenging.
916 const MachineFunction &MF) const {
917 return false;
918 }
919
920 /// Returns true if the target wants the LocalStackAllocation pass to be run
921 /// and virtual base registers used for more efficient stack access.
922 virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const {
923 return false;
924 }
925
926 /// Return true if target has reserved a spill slot in the stack frame of
927 /// the given function for the specified register. e.g. On x86, if the frame
928 /// register is required, the first fixed stack object is reserved as its
929 /// spill slot. This tells PEI not to create a new stack frame
930 /// object for the given register. It should be called only after
931 /// determineCalleeSaves().
933 int &FrameIdx) const {
934 return false;
935 }
936
937 /// Returns true if the live-ins should be tracked after register allocation.
938 virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
939 return true;
940 }
941
942 /// True if the stack can be realigned for the target.
943 virtual bool canRealignStack(const MachineFunction &MF) const;
944
945 /// True if storage within the function requires the stack pointer to be
946 /// aligned more than the normal calling convention calls for.
947 virtual bool shouldRealignStack(const MachineFunction &MF) const;
948
949 /// True if stack realignment is required and still possible.
950 bool hasStackRealignment(const MachineFunction &MF) const {
951 return shouldRealignStack(MF) && canRealignStack(MF);
952 }
953
954 /// Get the offset from the referenced frame index in the instruction,
955 /// if there is one.
957 int Idx) const {
958 return 0;
959 }
960
961 /// Returns true if the instruction's frame index reference would be better
962 /// served by a base register other than FP or SP.
963 /// Used by LocalStackFrameAllocation to determine which frame index
964 /// references it should create new base registers for.
965 virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
966 return false;
967 }
968
969 /// Insert defining instruction(s) for a pointer to FrameIdx before
970 /// insertion point I. Return materialized frame pointer.
972 int FrameIdx,
973 int64_t Offset) const {
974 llvm_unreachable("materializeFrameBaseRegister does not exist on this "
975 "target");
976 }
977
978 /// Resolve a frame index operand of an instruction
979 /// to reference the indicated base register plus offset instead.
981 int64_t Offset) const {
982 llvm_unreachable("resolveFrameIndex does not exist on this target");
983 }
984
985 /// Determine whether a given base register plus offset immediate is
986 /// encodable to resolve a frame index.
987 virtual bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg,
988 int64_t Offset) const {
989 llvm_unreachable("isFrameOffsetLegal does not exist on this target");
990 }
991
992 /// Gets the DWARF expression opcodes for \p Offset.
993 virtual void getOffsetOpcodes(const StackOffset &Offset,
995
996 /// Prepends a DWARF expression for \p Offset to DIExpression \p Expr.
998 prependOffsetExpression(const DIExpression *Expr, unsigned PrependFlags,
999 const StackOffset &Offset) const;
1000
1001 virtual int64_t getDwarfRegNumForVirtReg(Register RegNum, bool isEH) const {
1002 llvm_unreachable("getDwarfRegNumForVirtReg does not exist on this target");
1003 }
1004
1005 /// Spill the register so it can be used by the register scavenger.
1006 /// Return true if the register was spilled, false otherwise.
1007 /// If this function does not spill the register, the scavenger
1008 /// will instead spill it to the emergency spill slot.
1012 const TargetRegisterClass *RC,
1013 Register Reg) const {
1014 return false;
1015 }
1016
1017 /// Process frame indices in reverse block order. This changes the behavior of
1018 /// the RegScavenger passed to eliminateFrameIndex. If this is true targets
1019 /// should scavengeRegisterBackwards in eliminateFrameIndex. New targets
1020 /// should prefer reverse scavenging behavior.
1021 /// TODO: Remove this when all targets return true.
1022 virtual bool eliminateFrameIndicesBackwards() const { return true; }
1023
1024 /// This method must be overriden to eliminate abstract frame indices from
1025 /// instructions which may use them. The instruction referenced by the
1026 /// iterator contains an MO_FrameIndex operand which must be eliminated by
1027 /// this method. This method may modify or replace the specified instruction,
1028 /// as long as it keeps the iterator pointing at the finished product.
1029 /// SPAdj is the SP adjustment due to call frame setup instruction.
1030 /// FIOperandNum is the FI operand number.
1031 /// Returns true if the current instruction was removed and the iterator
1032 /// is not longer valid
1034 int SPAdj, unsigned FIOperandNum,
1035 RegScavenger *RS = nullptr) const = 0;
1036
1037 /// Return the assembly name for \p Reg.
1039 // FIXME: We are assuming that the assembly name is equal to the TableGen
1040 // name converted to lower case
1041 //
1042 // The TableGen name is the name of the definition for this register in the
1043 // target's tablegen files. For example, the TableGen name of
1044 // def EAX : Register <...>; is "EAX"
1045 return StringRef(getName(Reg));
1046 }
1047
1048 //===--------------------------------------------------------------------===//
1049 /// Subtarget Hooks
1050
1051 /// SrcRC and DstRC will be morphed into NewRC if this returns true.
1053 const TargetRegisterClass *SrcRC,
1054 unsigned SubReg,
1055 const TargetRegisterClass *DstRC,
1056 unsigned DstSubReg,
1057 const TargetRegisterClass *NewRC,
1058 LiveIntervals &LIS) const
1059 { return true; }
1060
1061 /// Region split has a high compile time cost especially for large live range.
1062 /// This method is used to decide whether or not \p VirtReg should
1063 /// go through this expensive splitting heuristic.
1064 virtual bool shouldRegionSplitForVirtReg(const MachineFunction &MF,
1065 const LiveInterval &VirtReg) const;
1066
1067 /// Last chance recoloring has a high compile time cost especially for
1068 /// targets with a lot of registers.
1069 /// This method is used to decide whether or not \p VirtReg should
1070 /// go through this expensive heuristic.
1071 /// When this target hook is hit, by returning false, there is a high
1072 /// chance that the register allocation will fail altogether (usually with
1073 /// "ran out of registers").
1074 /// That said, this error usually points to another problem in the
1075 /// optimization pipeline.
1076 virtual bool
1078 const LiveInterval &VirtReg) const {
1079 return true;
1080 }
1081
1082 /// When prioritizing live ranges in register allocation, if this hook returns
1083 /// true then the AllocationPriority of the register class will be treated as
1084 /// more important than whether the range is local to a basic block or global.
1085 virtual bool
1087 return false;
1088 }
1089
1090 //===--------------------------------------------------------------------===//
1091 /// Debug information queries.
1092
1093 /// getFrameRegister - This method should return the register used as a base
1094 /// for values allocated in the current stack frame.
1095 virtual Register getFrameRegister(const MachineFunction &MF) const = 0;
1096
1097 /// Mark a register and all its aliases as reserved in the given set.
1098 void markSuperRegs(BitVector &RegisterSet, MCRegister Reg) const;
1099
1100 /// Returns true if for every register in the set all super registers are part
1101 /// of the set as well.
1102 bool checkAllSuperRegsMarked(const BitVector &RegisterSet,
1103 ArrayRef<MCPhysReg> Exceptions = ArrayRef<MCPhysReg>()) const;
1104
1105 virtual const TargetRegisterClass *
1107 const MachineRegisterInfo &MRI) const {
1108 return nullptr;
1109 }
1110
1111 /// Some targets have non-allocatable registers that aren't technically part
1112 /// of the explicit callee saved register list, but should be handled as such
1113 /// in certain cases.
1115 return false;
1116 }
1117
1118 /// Some targets delay assigning the frame until late and use a placeholder
1119 /// to represent it earlier. This method can be used to identify the frame
1120 /// register placeholder.
1121 virtual bool isVirtualFrameRegister(MCRegister Reg) const { return false; }
1122
1123 virtual std::optional<uint8_t> getVRegFlagValue(StringRef Name) const {
1124 return {};
1125 }
1126
1129 return {};
1130 }
1131
1132 // Whether this register should be ignored when generating CodeView debug
1133 // info, because it's a known there is no mapping available.
1134 virtual bool isIgnoredCVReg(MCRegister LLVMReg) const { return false; }
1135};
1136
1137//===----------------------------------------------------------------------===//
1138// SuperRegClassIterator
1139//===----------------------------------------------------------------------===//
1140//
1141// Iterate over the possible super-registers for a given register class. The
1142// iterator will visit a list of pairs (Idx, Mask) corresponding to the
1143// possible classes of super-registers.
1144//
1145// Each bit mask will have at least one set bit, and each set bit in Mask
1146// corresponds to a SuperRC such that:
1147//
1148// For all Reg in SuperRC: Reg:Idx is in RC.
1149//
1150// The iterator can include (O, RC->getSubClassMask()) as the first entry which
1151// also satisfies the above requirement, assuming Reg:0 == Reg.
1152//
1154 const unsigned RCMaskWords;
1155 unsigned SubReg = 0;
1156 const uint16_t *Idx;
1157 const uint32_t *Mask;
1158
1159public:
1160 /// Create a SuperRegClassIterator that visits all the super-register classes
1161 /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry.
1163 const TargetRegisterInfo *TRI,
1164 bool IncludeSelf = false)
1165 : RCMaskWords((TRI->getNumRegClasses() + 31) / 32),
1166 Idx(RC->getSuperRegIndices()), Mask(RC->getSubClassMask()) {
1167 if (!IncludeSelf)
1168 ++*this;
1169 }
1170
1171 /// Returns true if this iterator is still pointing at a valid entry.
1172 bool isValid() const { return Idx; }
1173
1174 /// Returns the current sub-register index.
1175 unsigned getSubReg() const { return SubReg; }
1176
1177 /// Returns the bit mask of register classes that getSubReg() projects into
1178 /// RC.
1179 /// See TargetRegisterClass::getSubClassMask() for how to use it.
1180 const uint32_t *getMask() const { return Mask; }
1181
1182 /// Advance iterator to the next entry.
1183 void operator++() {
1184 assert(isValid() && "Cannot move iterator past end.");
1185 Mask += RCMaskWords;
1186 SubReg = *Idx++;
1187 if (!SubReg)
1188 Idx = nullptr;
1189 }
1190};
1191
1192//===----------------------------------------------------------------------===//
1193// BitMaskClassIterator
1194//===----------------------------------------------------------------------===//
1195/// This class encapuslates the logic to iterate over bitmask returned by
1196/// the various RegClass related APIs.
1197/// E.g., this class can be used to iterate over the subclasses provided by
1198/// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask.
1200 /// Total number of register classes.
1201 const unsigned NumRegClasses;
1202 /// Base index of CurrentChunk.
1203 /// In other words, the number of bit we read to get at the
1204 /// beginning of that chunck.
1205 unsigned Base = 0;
1206 /// Adjust base index of CurrentChunk.
1207 /// Base index + how many bit we read within CurrentChunk.
1208 unsigned Idx = 0;
1209 /// Current register class ID.
1210 unsigned ID = 0;
1211 /// Mask we are iterating over.
1212 const uint32_t *Mask;
1213 /// Current chunk of the Mask we are traversing.
1214 uint32_t CurrentChunk;
1215
1216 /// Move ID to the next set bit.
1217 void moveToNextID() {
1218 // If the current chunk of memory is empty, move to the next one,
1219 // while making sure we do not go pass the number of register
1220 // classes.
1221 while (!CurrentChunk) {
1222 // Move to the next chunk.
1223 Base += 32;
1224 if (Base >= NumRegClasses) {
1225 ID = NumRegClasses;
1226 return;
1227 }
1228 CurrentChunk = *++Mask;
1229 Idx = Base;
1230 }
1231 // Otherwise look for the first bit set from the right
1232 // (representation of the class ID is big endian).
1233 // See getSubClassMask for more details on the representation.
1234 unsigned Offset = llvm::countr_zero(CurrentChunk);
1235 // Add the Offset to the adjusted base number of this chunk: Idx.
1236 // This is the ID of the register class.
1237 ID = Idx + Offset;
1238
1239 // Consume the zeros, if any, and the bit we just read
1240 // so that we are at the right spot for the next call.
1241 // Do not do Offset + 1 because Offset may be 31 and 32
1242 // will be UB for the shift, though in that case we could
1243 // have make the chunk being equal to 0, but that would
1244 // have introduced a if statement.
1245 moveNBits(Offset);
1246 moveNBits(1);
1247 }
1248
1249 /// Move \p NumBits Bits forward in CurrentChunk.
1250 void moveNBits(unsigned NumBits) {
1251 assert(NumBits < 32 && "Undefined behavior spotted!");
1252 // Consume the bit we read for the next call.
1253 CurrentChunk >>= NumBits;
1254 // Adjust the base for the chunk.
1255 Idx += NumBits;
1256 }
1257
1258public:
1259 /// Create a BitMaskClassIterator that visits all the register classes
1260 /// represented by \p Mask.
1261 ///
1262 /// \pre \p Mask != nullptr
1264 : NumRegClasses(TRI.getNumRegClasses()), Mask(Mask), CurrentChunk(*Mask) {
1265 // Move to the first ID.
1266 moveToNextID();
1267 }
1268
1269 /// Returns true if this iterator is still pointing at a valid entry.
1270 bool isValid() const { return getID() != NumRegClasses; }
1271
1272 /// Returns the current register class ID.
1273 unsigned getID() const { return ID; }
1274
1275 /// Advance iterator to the next entry.
1276 void operator++() {
1277 assert(isValid() && "Cannot move iterator past end.");
1278 moveToNextID();
1279 }
1280};
1281
1282// This is useful when building IndexedMaps keyed on virtual registers
1285 unsigned operator()(Register Reg) const { return Reg.virtRegIndex(); }
1286};
1287
1288/// Prints virtual and physical registers with or without a TRI instance.
1289///
1290/// The format is:
1291/// %noreg - NoRegister
1292/// %5 - a virtual register.
1293/// %5:sub_8bit - a virtual register with sub-register index (with TRI).
1294/// %eax - a physical register
1295/// %physreg17 - a physical register when no TRI instance given.
1296///
1297/// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n';
1298LLVM_ABI Printable printReg(Register Reg,
1299 const TargetRegisterInfo *TRI = nullptr,
1300 unsigned SubIdx = 0,
1301 const MachineRegisterInfo *MRI = nullptr);
1302
1303/// Create Printable object to print register units on a \ref raw_ostream.
1304///
1305/// Register units are named after their root registers:
1306///
1307/// al - Single root.
1308/// fp0~st7 - Dual roots.
1309///
1310/// Usage: OS << printRegUnit(Unit, TRI) << '\n';
1311LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI);
1312
1313/// Create Printable object to print virtual registers and physical
1314/// registers on a \ref raw_ostream.
1315LLVM_ABI Printable printVRegOrUnit(VirtRegOrUnit VRegOrUnit,
1316 const TargetRegisterInfo *TRI);
1317
1318/// Create Printable object to print register classes or register banks
1319/// on a \ref raw_ostream.
1321 const MachineRegisterInfo &RegInfo,
1322 const TargetRegisterInfo *TRI);
1323
1324} // end namespace llvm
1325
1326#endif // LLVM_CODEGEN_TARGETREGISTERINFO_H
MachineInstrBuilder & UseMI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
A common definition of LaneBitmask for use in TableGen and CodeGen.
Live Register Matrix
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static StringRef getName(Value *V)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
static const TargetRegisterClass * getCommonMinimalPhysRegClass(const TargetRegisterInfo *TRI, MCRegister Reg1, MCRegister Reg2)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
void operator++()
Advance iterator to the next entry.
unsigned getID() const
Returns the current register class ID.
BitMaskClassIterator(const uint32_t *Mask, const TargetRegisterInfo &TRI)
Create a BitMaskClassIterator that visits all the register classes represented by Mask.
bool isValid() const
Returns true if this iterator is still pointing at a valid entry.
DWARF expression.
LiveInterval - This class represents the liveness of a register, or stack slot.
MCRegisterClass - Base class of TargetRegisterClass.
const uint8_t SpillStackID
unsigned getID() const
getID() - Return the register class ID number.
ArrayRef< MCPhysReg > getRegisters() const
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
unsigned getNumSubRegIndices() const
Return the number of sub-register indices understood by the target.
bool regsOverlap(MCRegister RegA, MCRegister RegB) const
Returns true if the two registers are equal or alias each other.
unsigned getNumRegClasses() const
iota_range< MCRegUnit > regunits() const
Returns an iterator range over all regunits.
const MCRegisterClass & getRegClass(unsigned i) const
Returns the register class associated with the enumeration value.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Machine Value Type.
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Holds all the information related to register banks.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
void operator++()
Advance iterator to the next entry.
unsigned getSubReg() const
Returns the current sub-register index.
const uint32_t * getMask() const
Returns the bit mask of register classes that getSubReg() projects into RC.
SuperRegClassIterator(const TargetRegisterClass *RC, const TargetRegisterInfo *TRI, bool IncludeSelf=false)
Create a SuperRegClassIterator that visits all the super-register classes of RC.
bool isValid() const
Returns true if this iterator is still pointing at a valid entry.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
virtual SmallVector< StringLiteral > getVRegFlagsOfReg(Register Reg, const MachineFunction &MF) const
virtual bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg, int64_t Offset) const
Determine whether a given base register plus offset immediate is encodable to resolve a frame index.
virtual ArrayRef< MCPhysReg > getRawAllocationOrder(const TargetRegisterClass &RC, const MachineFunction &, bool=false) const
Returns the preferred order for allocating registers from this register class in MF.
vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const
bool isTypeLegalForClass(const TargetRegisterClass &RC, LLT T) const
Return true if the given TargetRegisterClass is compatible with LLT T.
bool hasRegUnit(MCRegister Reg, MCRegUnit RegUnit) const
Returns true if Reg contains RegUnit.
virtual unsigned getNumRegPressureSets() const =0
Get the number of dimensions of register pressure.
~TargetRegisterInfo() override
unsigned reverseComposeSubRegIndices(unsigned a, unsigned b) const
Return a subregister index that will compose to give you the subregister index.
virtual const int * getRegUnitPressureSets(MCRegUnit RegUnit) const =0
Get the dimensions of register pressure impacted by this register unit.
virtual const TargetRegisterClass * getPhysRegBaseClass(MCRegister Reg) const
Return target defined base register class for a physical register.
virtual bool canRealignStack(const MachineFunction &MF) const
True if the stack can be realigned for the target.
virtual bool isAsmClobberable(const MachineFunction &MF, MCRegister PhysReg) const
Returns false if we can't guarantee that Physreg, specified as an IR asm clobber constraint,...
virtual const TargetRegisterClass * getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const
Returns the largest legal sub-class of RC that supports the sub-register index Idx.
virtual const TargetRegisterClass * getLargestRegClassForRegPressureSet(unsigned Idx) const =0
Get the register class for this pressure set with the largest RegClassWeight::WeightLimit.
const TargetRegisterClass * getRegClass(unsigned i) const
Returns the register class associated with the enumeration value.
virtual bool useFPForScavengingIndex(const MachineFunction &MF) const
Returns true if the target wants to use frame pointer based accesses to spill to the scavenger emerge...
virtual const TargetRegisterClass * getCrossCopyRegClass(const TargetRegisterClass *RC) const
Returns a legal register class to copy a register in the specified class to or from.
virtual bool isVirtualFrameRegister(MCRegister Reg) const
Some targets delay assigning the frame until late and use a placeholder to represent it earlier.
virtual bool shouldUseLastChanceRecoloringForVirtReg(const MachineFunction &MF, const LiveInterval &VirtReg) const
Last chance recoloring has a high compile time cost especially for targets with a lot of registers.
virtual bool eliminateFrameIndicesBackwards() const
Process frame indices in reverse block order.
unsigned composeSubRegIndices(unsigned a, unsigned b) const
Return the subregister index you get from composing two subregister indices.
virtual LaneBitmask composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const
Overridden by TableGen in targets that have sub-registers.
virtual bool isIgnoredCVReg(MCRegister LLVMReg) const
virtual bool isGeneralPurposeRegisterClass(const TargetRegisterClass *RC) const
Returns true if RC is a class/subclass of general purpose register.
void markSuperRegs(BitVector &RegisterSet, MCRegister Reg) const
Mark a register and all its aliases as reserved in the given set.
virtual const MCPhysReg * getIPRACSRegs(const MachineFunction *MF) const
Return a null-terminated list of all of the callee-saved registers on this target when IPRA is on.
virtual const uint32_t * getCustomEHPadPreservedMask(const MachineFunction &MF) const
Return a register mask for the registers preserved by the unwinder, or nullptr if no custom mask is n...
virtual float getSpillWeightScaleFactor(const TargetRegisterClass *RC) const
Get the scale factor of spill weight for this register class.
const MVT::SimpleValueType * vt_iterator
virtual bool isUniformReg(const MachineRegisterInfo &MRI, const RegisterBankInfo &RBI, Register Reg) const
Returns true if the register is considered uniform.
TypeSize getRegSizeInBits(const TargetRegisterClass &RC) const
Return the size in bits of a register from class RC.
virtual std::optional< std::string > explainReservedReg(const MachineFunction &MF, MCRegister PhysReg) const
Returns either a string explaining why the given register is reserved for this function,...
virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const
Returns true if the target requires post PEI scavenging of registers for materializing frame index co...
const char * getSubRegIndexName(unsigned SubIdx) const
Return the human-readable symbolic target-specific name for the specified SubRegIndex.
virtual const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const
Return a mask of call-preserved registers for the given calling convention on the current function.
virtual const char * getRegPressureSetName(unsigned Idx) const =0
Get the name of this register unit pressure set.
virtual LaneBitmask reverseComposeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const
LaneBitmask getCoveringLanes() const
The lane masks returned by getSubRegIndexLaneMask() above can only be used to determine if sub-regist...
virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const
Get the offset from the referenced frame index in the instruction, if there is one.
ArrayRef< uint8_t > getRegisterCosts(const MachineFunction &MF) const
Get a list of cost values for all registers that correspond to the index returned by RegisterCostTabl...
virtual bool isGeneralPurposeRegister(const MachineFunction &MF, MCRegister PhysReg) const
Returns true if PhysReg is a general purpose register.
virtual ArrayRef< const uint32_t * > getRegMasks() const =0
Return all the call-preserved register masks defined for this target.
LaneBitmask reverseComposeSubRegIndexLaneMask(unsigned IdxA, LaneBitmask LaneMask) const
Transform a lanemask given for a virtual register to the corresponding lanemask before using subregis...
virtual unsigned getRegPressureSetScore(const MachineFunction &MF, unsigned PSetID) const
Return a heuristic for the machine scheduler to compare the profitability of increasing one register ...
virtual const int * getRegClassPressureSets(const TargetRegisterClass *RC) const =0
Get the dimensions of register pressure impacted by this register class.
virtual unsigned getCSRCostScale(const MachineFunction &MF) const
Scale the CSRFirstUseCost with this number.
virtual const RegClassWeight & getRegClassWeight(const TargetRegisterClass *RC) const =0
Get the weight in units of pressure for this register class.
virtual ArrayRef< MCPhysReg > getIntraCallClobberedRegs(const MachineFunction *MF) const
Return a list of all of the registers which are clobbered "inside" a call to the given function.
virtual bool reverseLocalAssignment() const
Allow the target to reverse allocation order of local live ranges.
virtual bool isNonallocatableRegisterCalleeSave(MCRegister Reg) const
Some targets have non-allocatable registers that aren't technically part of the explicit callee saved...
vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const
Loop over all of the value types that can be represented by values in the given register class.
virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC, MachineFunction &MF) const
Return the register pressure "high water mark" for the specific register class.
LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const
Return a bitmask representing the parts of a register that are covered by SubIdx.
virtual const TargetRegisterClass * getMinimalPhysRegClass(MCRegister Reg) const =0
Returns the Register Class of a physical register, picking the smallest register subclass that contai...
bool checkAllSuperRegsMarked(const BitVector &RegisterSet, ArrayRef< MCPhysReg > Exceptions=ArrayRef< MCPhysReg >()) const
Returns true if for every register in the set all super registers are part of the set as well.
virtual int64_t getDwarfRegNumForVirtReg(Register RegNum, bool isEH) const
virtual const TargetRegisterClass * getLargestLegalSuperClass(const TargetRegisterClass *RC, const MachineFunction &) const
Returns the largest super class of RC that is legal to use in the current sub-target and has the same...
virtual BitVector getReservedRegs(const MachineFunction &MF) const =0
Returns a bitset indexed by physical register number indicating if a register is a special register t...
const RegClassInfo & getRegClassInfo(const TargetRegisterClass &RC) const
virtual const uint32_t * getNoPreservedMask() const
Return a register mask that clobbers everything.
virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const
Returns true if the live-ins should be tracked after register allocation.
virtual bool isArgumentRegister(const MachineFunction &MF, MCRegister PhysReg) const
Returns true if PhysReg can be used as an argument to a function.
Align getSpillAlign(const TargetRegisterClass &RC) const
Return the minimum required alignment in bytes for a spill slot for a register of this class.
virtual std::optional< uint8_t > getVRegFlagValue(StringRef Name) const
virtual const TargetRegisterClass * getSubRegisterClass(const TargetRegisterClass *SuperRC, unsigned SubRegIdx) const
Returns the register class of all sub-registers of SuperRC obtained by applying the sub-register inde...
virtual unsigned getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const =0
Get the register unit pressure limit for this dimension.
virtual bool requiresFrameIndexReplacementScavenging(const MachineFunction &MF) const
Returns true if the target requires using the RegScavenger directly for frame elimination despite usi...
virtual bool eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj, unsigned FIOperandNum, RegScavenger *RS=nullptr) const =0
This method must be overriden to eliminate abstract frame indices from instructions which may use the...
virtual unsigned getRegUnitWeight(MCRegUnit RegUnit) const =0
Get the weight in units of pressure for this register unit.
virtual bool requiresRegisterScavenging(const MachineFunction &MF) const
Returns true if the target requires (and can make use of) the register scavenger.
const TargetRegisterClass * getAllocatableClass(const TargetRegisterClass *RC) const
Return the maximal subclass of the given register class that is allocatable or NULL.
LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA, LaneBitmask Mask) const
Transforms a LaneMask computed for one subregister to the lanemask that would have been computed when...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual bool shouldAnalyzePhysregInMachineLoopInfo(MCRegister R) const
Returns true if MachineLoopInfo should analyze the given physreg for loop invariance.
virtual bool saveScavengerRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, MachineBasicBlock::iterator &UseMI, const TargetRegisterClass *RC, Register Reg) const
Spill the register so it can be used by the register scavenger.
virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC, unsigned DefSubReg, const TargetRegisterClass *SrcRC, unsigned SrcSubReg) const
virtual bool isCallerPreservedPhysReg(MCRegister PhysReg, const MachineFunction &MF) const
Physical registers that may be modified within a function but are guaranteed to be restored before an...
virtual bool hasReservedSpillSlot(const MachineFunction &MF, Register Reg, int &FrameIdx) const
Return true if target has reserved a spill slot in the stack frame of the given function for the spec...
virtual void resolveFrameIndex(MachineInstr &MI, Register BaseReg, int64_t Offset) const
Resolve a frame index operand of an instruction to reference the indicated base register plus offset ...
virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const
Returns true if the register class is considered divergent.
virtual Register materializeFrameBaseRegister(MachineBasicBlock *MBB, int FrameIdx, int64_t Offset) const
Insert defining instruction(s) for a pointer to FrameIdx before insertion point I.
bool regsOverlap(Register RegA, Register RegB) const
Returns true if the two registers are equal or alias each other.
virtual bool shouldRealignStack(const MachineFunction &MF) const
True if storage within the function requires the stack pointer to be aligned more than the normal cal...
virtual unsigned getNumSupportedRegs(const MachineFunction &) const
Return the number of registers for the function. (may overestimate)
TargetStackID::Value getSpillStackID(const TargetRegisterClass &RC) const
Return the stack ID for spill slots holding a spilled copy of a register from this class.
virtual unsigned getCSRCost() const
FIXME: We should deprecate this usage.
virtual ArrayRef< const char * > getRegMaskNames() const =0
virtual bool isFixedRegister(const MachineFunction &MF, MCRegister PhysReg) const
Returns true if PhysReg is a fixed register.
virtual const TargetRegisterClass * getConstrainedRegClassForReg(Register Reg, const MachineRegisterInfo &MRI) const
const TargetRegisterClass * findCommonRegClass(const TargetRegisterClass *DefRC, unsigned DefSubReg, const TargetRegisterClass *SrcRC, unsigned SrcSubReg) const
Find a common register class that can accomodate both the source and destination operands of a copy-l...
unsigned getSpillSize(const TargetRegisterClass &RC) const
Return the size in bytes of the stack slot allocated to hold a spilled copy of a register from class ...
virtual StringRef getRegAsmName(MCRegister Reg) const
Return the assembly name for Reg.
virtual const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const =0
Return a null-terminated list of all of the callee-saved registers on this target.
TargetRegisterInfo(const TargetRegisterInfoDesc *ID, const char *SubRegIndexStrings, ArrayRef< uint32_t > SubRegIndexNameOffsets, const SubRegCoveredBits *SubRegIdxRanges, const LaneBitmask *SubRegIndexLaneMasks, LaneBitmask CoveringLanes, const RegClassInfo *const RCInfos, const MVT::SimpleValueType *const RCVTLists, unsigned Mode=0)
bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const
Return true if the given TargetRegisterClass has the ValueType T.
virtual unsigned getRegisterCostTableIndex(const MachineFunction &MF) const
Return the register cost table index.
virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const
Returns true if the instruction's frame index reference would be better served by a base register oth...
virtual unsigned getCSRFirstUseCost(const MachineFunction &MF) const
Allow the target to override the cost of using a callee-saved register for the first time.
virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const
Overridden by TableGen in targets that have sub-registers.
virtual unsigned reverseComposeSubRegIndicesImpl(unsigned, unsigned) const
Overridden by TableGen in targets that have sub-registers.
virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const
Prior to adding the live-out mask to a stackmap or patchpoint instruction, provide the target the opp...
bool isSubRegValidForRegClass(const TargetRegisterClass *RC, unsigned Idx) const
Returns true if sub-register Idx can be used with register class RC.
virtual bool isInlineAsmReadOnlyReg(const MachineFunction &MF, MCRegister PhysReg) const
Returns true if PhysReg cannot be written to in inline asm statements.
virtual bool shouldCoalesce(MachineInstr *MI, const TargetRegisterClass *SrcRC, unsigned SubReg, const TargetRegisterClass *DstRC, unsigned DstSubReg, const TargetRegisterClass *NewRC, LiveIntervals &LIS) const
Subtarget Hooks.
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
virtual bool regClassPriorityTrumpsGlobalness(const MachineFunction &MF) const
When prioritizing live ranges in register allocation, if this hook returns true then the AllocationPr...
bool isInAllocatableClass(MCRegister RegNo) const
Return true if the register is in the allocation of any register class.
BitVector getAllocatableSet(const MachineFunction &MF, const TargetRegisterClass *RC=nullptr) const
Returns a bitset indexed by register number indicating if a register is allocatable or not.
virtual void updateRegAllocHint(Register Reg, Register NewReg, MachineFunction &MF) const
A callback to allow target a chance to update register allocation hints when a register is "changed" ...
virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const
Returns true if the target wants the LocalStackAllocation pass to be run and virtual base registers u...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo, const TargetRegisterInfo *TRI)
Create Printable object to print register classes or register banks on a raw_ostream.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printVRegOrUnit(VirtRegOrUnit VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Each TargetRegisterClass has a per register weight, and weight limit which must be less than the limi...
Extra information, not in MCRegisterDesc, about registers.
SubRegCoveredBits - Emitted by tablegen: bit range covered by a subreg index, -1 in any being invalid...
unsigned operator()(Register Reg) const