LLVM 24.0.0git
RegisterClassInfo.cpp
Go to the documentation of this file.
1//===- RegisterClassInfo.cpp - Dynamic Register Class Info ----------------===//
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 implements the RegisterClassInfo class which provides dynamic
10// information about target register classes. Callee-saved vs. caller-saved and
11// reserved registers depend on calling conventions and other dynamic
12// information, so some things cannot be determined statically.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/BitVector.h"
26#include "llvm/Support/Debug.h"
28#include <algorithm>
29#include <cassert>
30#include <cstdint>
31
32using namespace llvm;
33
34#define DEBUG_TYPE "regalloc"
35
37StressRA("stress-regalloc", cl::Hidden, cl::init(0), cl::value_desc("N"),
38 cl::desc("Limit all regclasses to N registers"));
39
41
43 bool Rev) {
44 bool Update = false;
45 MF = &mf;
46
47 auto &STI = MF->getSubtarget();
48
49 // Allocate new array the first time we see a new target.
50 if (STI.getRegisterInfo() != TRI || Reverse != Rev) {
51 Reverse = Rev;
52 TRI = STI.getRegisterInfo();
53 RegClass.reset(new RCInfo[TRI->getNumRegClasses()]);
54 Update = true;
55 }
56
57 // Test if CSRs have changed from the previous function.
58 const MachineRegisterInfo &MRI = MF->getRegInfo();
59 const MCPhysReg *CSR = MRI.getCalleeSavedRegs();
60 bool CSRChanged = true;
61 if (!Update) {
62 CSRChanged = false;
63 size_t LastSize = LastCalleeSavedRegs.size();
64 for (unsigned I = 0;; ++I) {
65 if (CSR[I] == 0) {
66 CSRChanged = I != LastSize;
67 break;
68 }
69 if (I >= LastSize) {
70 CSRChanged = true;
71 break;
72 }
73 if (CSR[I] != LastCalleeSavedRegs[I]) {
74 CSRChanged = true;
75 break;
76 }
77 }
78 }
79
80 // Get the callee saved registers.
81 if (CSRChanged) {
82 LastCalleeSavedRegs.clear();
83 // Build a CSRAlias map. Every CSR alias saves the last
84 // overlapping CSR.
85 CalleeSavedAliases.assign(TRI->getNumRegUnits(), 0);
86 for (const MCPhysReg *I = CSR; *I; ++I) {
87 for (MCRegUnit U : TRI->regunits(*I))
88 CalleeSavedAliases[static_cast<unsigned>(U)] = *I;
89 LastCalleeSavedRegs.push_back(*I);
90 }
91
92 Update = true;
93 }
94
95 // Even if CSR list is same, we could have had a different allocation order
96 // if the target's CSR allocation-order mask changes.
97 BitVector CSRHintsForAllocOrder;
98 STI.getCSRAllocationOrderMask(mf, CSRHintsForAllocOrder);
99 if (IgnoreCSRForAllocOrder != CSRHintsForAllocOrder) {
100 Update = true;
101 IgnoreCSRForAllocOrder = std::move(CSRHintsForAllocOrder);
102 }
103
104 RegCosts = TRI->getRegisterCosts(*MF);
105
106 // Different reserved registers?
107 const BitVector &RR = MF->getRegInfo().getReservedRegs();
108 if (RR != Reserved) {
109 Update = true;
110 Reserved = RR;
111 }
112
113 // Invalidate cached information from previous function.
114 if (Update) {
115 unsigned NumPSets = TRI->getNumRegPressureSets();
116 PSetLimits.reset(new unsigned[NumPSets]);
117 std::fill(&PSetLimits[0], &PSetLimits[NumPSets], 0);
118 ++Tag;
119 }
120}
121
123 return Reserved == MF->getRegInfo().getReservedRegs();
124}
125
127 assert(MF && TRI && RegClass &&
128 "RegisterClassInfo must be initialized before updating reserved regs");
129 assert(ReservedInput.size() == Reserved.size() &&
130 "Reserved register bit vectors must have the same size");
131 if (ReservedInput == Reserved)
132 return;
133
134 // Cached orders cannot regain unreserved registers; recompute them lazily.
135 bool OnlyNewReservations = Reserved.subsetOf(ReservedInput);
136
137 Reserved = ReservedInput;
138
139 // Pressure limits depend on the number of allocatable registers.
140 std::fill_n(PSetLimits.get(), TRI->getNumRegPressureSets(), 0);
141
142 // NumRegs may hide entries beyond the stress limit, so those orders cannot
143 // safely be compacted using only their visible prefix.
144 if (!OnlyNewReservations || StressRA) {
145 ++Tag;
146 return;
147 }
148
149 for (const TargetRegisterClass &RC : TRI->regclasses()) {
150 RCInfo &Info = RegClass[RC.getID()];
151
152 // Skip stale class information.
153 if (Info.Tag != Tag)
154 continue;
155
156 unsigned NewNumRegs = 0;
157 uint8_t MinCost = uint8_t(~0u);
158 uint8_t LastCost = uint8_t(~0u);
159 unsigned LastCostChange = 0;
160
161 for (unsigned I = 0; I != Info.NumRegs; ++I) {
162 MCPhysReg PhysReg = Info.Order[I];
163 if (Reserved.test(PhysReg))
164 continue;
165
166 uint8_t Cost = RegCosts[PhysReg];
167 MinCost = std::min(MinCost, Cost);
168 if (Cost != LastCost)
169 LastCostChange = NewNumRegs;
170
171 Info.Order[NewNumRegs++] = PhysReg;
172 LastCost = Cost;
173 }
174
175 Info.NumRegs = NewNumRegs;
176 Info.MinCost = MinCost;
177 Info.LastCostChange = LastCostChange;
178
179 Info.ProperSubClass = false;
180 if (const TargetRegisterClass *Super =
181 TRI->getLargestLegalSuperClass(&RC, *MF))
182 if (Super != &RC && getNumAllocatableRegs(Super) > Info.NumRegs)
183 Info.ProperSubClass = true;
184 }
185}
186
187/// compute - Compute the preferred allocation order for RC with reserved
188/// registers filtered out. Volatile registers come first followed by CSR
189/// aliases ordered according to the CSR order specified by the target.
190void RegisterClassInfo::compute(const TargetRegisterClass *RC) const {
191 assert(RC && "no register class given");
192 RCInfo &RCI = RegClass[RC->getID()];
193
194 // Raw register count, including all reserved regs.
195 unsigned NumRegs = RC->getNumRegs();
196
197 if (!RCI.Order)
198 RCI.Order.reset(new MCPhysReg[NumRegs]);
199
200 unsigned N = 0;
202 uint8_t MinCost = uint8_t(~0u);
203 uint8_t LastCost = uint8_t(~0u);
204 unsigned LastCostChange = 0;
205
206 // FIXME: Once targets reserve registers instead of removing them from the
207 // allocation order, we can simply use begin/end here.
208 ArrayRef<MCPhysReg> RawOrder = TRI->getRawAllocationOrder(*RC, *MF, Reverse);
209 for (unsigned PhysReg : reverse_conditionally(RawOrder, Reverse)) {
210 // Remove reserved registers from the allocation order.
211 if (Reserved.test(PhysReg))
212 continue;
213 uint8_t Cost = RegCosts[PhysReg];
214 MinCost = std::min(MinCost, Cost);
215
216 if (getLastCalleeSavedAlias(PhysReg) &&
217 (IgnoreCSRForAllocOrder.empty() ||
218 !IgnoreCSRForAllocOrder.test(PhysReg)))
219 // PhysReg aliases a CSR, save it for later.
220 CSRAlias.push_back(PhysReg);
221 else {
222 if (Cost != LastCost)
223 LastCostChange = N;
224 RCI.Order[N++] = PhysReg;
225 LastCost = Cost;
226 }
227 }
228 RCI.NumRegs = N + CSRAlias.size();
229 assert(RCI.NumRegs <= NumRegs && "Allocation order larger than regclass");
230
231 // CSR aliases go after the volatile registers, preserve the target's order.
232 for (unsigned PhysReg : CSRAlias) {
233 uint8_t Cost = RegCosts[PhysReg];
234 if (Cost != LastCost)
235 LastCostChange = N;
236 RCI.Order[N++] = PhysReg;
237 LastCost = Cost;
238 }
239
240 // Register allocator stress test. Clip register class to N registers.
241 if (StressRA && RCI.NumRegs > StressRA)
242 RCI.NumRegs = StressRA;
243
244 // Check if RC is a proper sub-class.
245 if (const TargetRegisterClass *Super =
246 TRI->getLargestLegalSuperClass(RC, *MF))
247 if (Super != RC && getNumAllocatableRegs(Super) > RCI.NumRegs)
248 RCI.ProperSubClass = true;
249
250 RCI.MinCost = MinCost;
251 RCI.LastCostChange = LastCostChange;
252
253 LLVM_DEBUG({
254 dbgs() << "AllocationOrder(" << TRI->getRegClassName(RC) << ") = [";
255 for (unsigned I = 0; I != RCI.NumRegs; ++I)
256 dbgs() << ' ' << printReg(RCI.Order[I], TRI);
257 dbgs() << (RCI.ProperSubClass ? " ] (sub-class)\n" : " ]\n");
258 });
259
260 // RCI is now up-to-date.
261 RCI.Tag = Tag;
262}
263
264/// This is not accurate because two overlapping register sets may have some
265/// nonoverlapping reserved registers. However, computing the allocation order
266/// for all register classes would be too expensive.
267unsigned RegisterClassInfo::computePSetLimit(unsigned Idx) const {
268 const TargetRegisterClass *RC = TRI->getLargestRegClassForRegPressureSet(Idx);
269 assert(RC && "Failed to find register class");
270 unsigned NAllocatableRegs = getNumAllocatableRegs(RC);
271 unsigned RegPressureSetLimit = TRI->getRegPressureSetLimit(*MF, Idx);
272 // If all the regs are reserved, return raw RegPressureSetLimit.
273 // One example is VRSAVERC in PowerPC.
274 // Avoid returning zero, getRegPressureSetLimit(Idx) assumes computePSetLimit
275 // return non-zero value.
276 if (NAllocatableRegs == 0)
277 return RegPressureSetLimit;
278 unsigned NReserved = RC->getNumRegs() - NAllocatableRegs;
279 unsigned ReservedRegWeight = TRI->getRegClassWeight(RC).RegWeight * NReserved;
280 // A target-provided limit may already account for restricted register
281 // availability, such as an AMDGPU occupancy requirement. If the additional
282 // reserved-register adjustment would not leave a positive limit, preserve the
283 // target's nonzero limit; zero is the PSetLimits cache sentinel.
284 if (ReservedRegWeight >= RegPressureSetLimit)
285 return RegPressureSetLimit;
286 return RegPressureSetLimit - ReservedRegWeight;
287}
288
290 "machine-register-class-info",
291 "Machine Register Class Info Analysis", true, true)
292
297 RCI.runOnMachineFunction(MF);
298 return RCI;
299}
300
302
308
310 MachineFunction &MF) {
311 RCI.runOnMachineFunction(MF);
312 return false;
313}
314
315void MachineRegisterClassInfoWrapperPass::anchor() {}
316
317AnalysisKey MachineRegisterClassAnalysis::Key;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the BitVector class.
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
static cl::opt< unsigned > StressRA("stress-regalloc", cl::Hidden, cl::init(0), cl::value_desc("N"), cl::desc("Limit all regclasses to N registers"))
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:175
unsigned getID() const
getID() - Return the register class ID number.
unsigned getNumRegs() const
getNumRegs - Return the number of registers in this class.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
LLVM_ABI void runOnMachineFunction(const MachineFunction &MF, bool Rev=false)
runOnFunction - Prepare to answer questions about MF.
LLVM_ABI void updateReservedRegs(const BitVector &ReservedInput)
Update cached register class information using ReservedInput, MRI's current reserved-register set.
MCRegister getLastCalleeSavedAlias(MCRegister PhysReg) const
getLastCalleeSavedAlias - Returns the last callee saved register that overlaps PhysReg,...
LLVM_ABI RegisterClassInfo()
LLVM_ABI bool hasCurrentReservedRegs() const
Whether the cached information was filtered by MRI's frozen reserved registers, i....
LLVM_ABI unsigned computePSetLimit(unsigned Idx) const
This is not accurate because two overlapping register sets may have some nonoverlapping reserved regi...
A global registry used in conjunction with static constructors to make pluggable components (like tar...
Definition Registry.h:116
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void initializeMachineRegisterClassInfoWrapperPassPass(PassRegistry &)
auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse)
Return a range that conditionally reverses C.
Definition STLExtras.h:1439
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
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.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29