LLVM 20.0.0git
RegAllocBasic.cpp
Go to the documentation of this file.
1//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
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 defines the RABasic function pass, which provides a minimal
10// implementation of the basic register allocator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AllocationOrder.h"
15#include "RegAllocBase.h"
28#include "llvm/CodeGen/Passes.h"
33#include "llvm/Pass.h"
34#include "llvm/Support/Debug.h"
36#include <queue>
37
38using namespace llvm;
39
40#define DEBUG_TYPE "regalloc"
41
42static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
44
45namespace {
46 struct CompSpillWeight {
47 bool operator()(const LiveInterval *A, const LiveInterval *B) const {
48 return A->weight() < B->weight();
49 }
50 };
51}
52
53namespace {
54/// RABasic provides a minimal implementation of the basic register allocation
55/// algorithm. It prioritizes live virtual registers by spill weight and spills
56/// whenever a register is unavailable. This is not practical in production but
57/// provides a useful baseline both for measuring other allocators and comparing
58/// the speed of the basic algorithm against other styles of allocators.
59class RABasic : public MachineFunctionPass,
60 public RegAllocBase,
62 // context
63 MachineFunction *MF = nullptr;
64
65 // state
66 std::unique_ptr<Spiller> SpillerInstance;
67 std::priority_queue<const LiveInterval *, std::vector<const LiveInterval *>,
68 CompSpillWeight>
69 Queue;
70
71 // Scratch space. Allocated here to avoid repeated malloc calls in
72 // selectOrSplit().
73 BitVector UsableRegs;
74
75 bool LRE_CanEraseVirtReg(Register) override;
76 void LRE_WillShrinkVirtReg(Register) override;
77
78public:
79 RABasic(const RegAllocFilterFunc F = nullptr);
80
81 /// Return the pass name.
82 StringRef getPassName() const override { return "Basic Register Allocator"; }
83
84 /// RABasic analysis usage.
85 void getAnalysisUsage(AnalysisUsage &AU) const override;
86
87 void releaseMemory() override;
88
89 Spiller &spiller() override { return *SpillerInstance; }
90
91 void enqueueImpl(const LiveInterval *LI) override { Queue.push(LI); }
92
93 const LiveInterval *dequeue() override {
94 if (Queue.empty())
95 return nullptr;
96 const LiveInterval *LI = Queue.top();
97 Queue.pop();
98 return LI;
99 }
100
102 SmallVectorImpl<Register> &SplitVRegs) override;
103
104 /// Perform register allocation.
105 bool runOnMachineFunction(MachineFunction &mf) override;
106
109 MachineFunctionProperties::Property::NoPHIs);
110 }
111
114 MachineFunctionProperties::Property::IsSSA);
115 }
116
117 // Helper for spilling all live virtual registers currently unified under preg
118 // that interfere with the most recently queried lvr. Return true if spilling
119 // was successful, and append any new spilled/split intervals to splitLVRs.
120 bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg,
121 SmallVectorImpl<Register> &SplitVRegs);
122
123 static char ID;
124};
125
126char RABasic::ID = 0;
127
128} // end anonymous namespace
129
130char &llvm::RABasicID = RABasic::ID;
131
132INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
133 false, false)
137INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
138INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
147 false)
148
149bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
150 LiveInterval &LI = LIS->getInterval(VirtReg);
151 if (VRM->hasPhys(VirtReg)) {
152 Matrix->unassign(LI);
153 aboutToRemoveInterval(LI);
154 return true;
155 }
156 // Unassigned virtreg is probably in the priority queue.
157 // RegAllocBase will erase it after dequeueing.
158 // Nonetheless, clear the live-range so that the debug
159 // dump will show the right state for that VirtReg.
160 LI.clear();
161 return false;
162}
163
164void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
165 if (!VRM->hasPhys(VirtReg))
166 return;
167
168 // Register is assigned, put it back on the queue for reassignment.
169 LiveInterval &LI = LIS->getInterval(VirtReg);
170 Matrix->unassign(LI);
171 enqueue(&LI);
172}
173
174RABasic::RABasic(RegAllocFilterFunc F)
176
177void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
178 AU.setPreservesCFG();
201}
202
203void RABasic::releaseMemory() {
204 SpillerInstance.reset();
205}
206
207
208// Spill or split all live virtual registers currently unified under PhysReg
209// that interfere with VirtReg. The newly spilled or split live intervals are
210// returned by appending them to SplitVRegs.
211bool RABasic::spillInterferences(const LiveInterval &VirtReg,
212 MCRegister PhysReg,
213 SmallVectorImpl<Register> &SplitVRegs) {
214 // Record each interference and determine if all are spillable before mutating
215 // either the union or live intervals.
217
218 // Collect interferences assigned to any alias of the physical register.
219 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
220 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
221 for (const auto *Intf : reverse(Q.interferingVRegs())) {
222 if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
223 return false;
224 Intfs.push_back(Intf);
225 }
226 }
227 LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
228 << " interferences with " << VirtReg << "\n");
229 assert(!Intfs.empty() && "expected interference");
230
231 // Spill each interfering vreg allocated to PhysReg or an alias.
232 for (const LiveInterval *Spill : Intfs) {
233 // Skip duplicates.
234 if (!VRM->hasPhys(Spill->reg()))
235 continue;
236
237 // Deallocate the interfering vreg by removing it from the union.
238 // A LiveInterval instance may not be in a union during modification!
239 Matrix->unassign(*Spill);
240
241 // Spill the extracted interval.
242 LiveRangeEdit LRE(Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
243 spiller().spill(LRE);
244 }
245 return true;
246}
247
248// Driver for the register assignment and splitting heuristics.
249// Manages iteration over the LiveIntervalUnions.
250//
251// This is a minimal implementation of register assignment and splitting that
252// spills whenever we run out of registers.
253//
254// selectOrSplit can only be called once per live virtual register. We then do a
255// single interference test for each register the correct class until we find an
256// available register. So, the number of interference tests in the worst case is
257// |vregs| * |machineregs|. And since the number of interference tests is
258// minimal, there is no value in caching them outside the scope of
259// selectOrSplit().
260MCRegister RABasic::selectOrSplit(const LiveInterval &VirtReg,
261 SmallVectorImpl<Register> &SplitVRegs) {
262 // Populate a list of physical register spill candidates.
263 SmallVector<MCRegister, 8> PhysRegSpillCands;
264
265 // Check for an available register in this class.
266 auto Order =
267 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
268 for (MCRegister PhysReg : Order) {
269 assert(PhysReg.isValid());
270 // Check for interference in PhysReg
271 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
273 // PhysReg is available, allocate it.
274 return PhysReg;
275
277 // Only virtual registers in the way, we may be able to spill them.
278 PhysRegSpillCands.push_back(PhysReg);
279 continue;
280
281 default:
282 // RegMask or RegUnit interference.
283 continue;
284 }
285 }
286
287 // Try to spill another interfering reg with less spill weight.
288 for (MCRegister &PhysReg : PhysRegSpillCands) {
289 if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
290 continue;
291
292 assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
293 "Interference after spill.");
294 // Tell the caller to allocate to this newly freed physical register.
295 return PhysReg;
296 }
297
298 // No other spill candidates were found, so spill the current VirtReg.
299 LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
300 if (!VirtReg.isSpillable())
301 return ~0u;
302 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
303 spiller().spill(LRE);
304
305 // The live virtual register requesting allocation was spilled, so tell
306 // the caller not to allocate anything during this round.
307 return 0;
308}
309
310bool RABasic::runOnMachineFunction(MachineFunction &mf) {
311 LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
312 << "********** Function: " << mf.getName() << '\n');
313
314 MF = &mf;
315 auto &MBFI = getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
316 auto &LiveStks = getAnalysis<LiveStacksWrapperLegacy>().getLS();
317 auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
318
319 RegAllocBase::init(getAnalysis<VirtRegMapWrapperLegacy>().getVRM(),
320 getAnalysis<LiveIntervalsWrapperPass>().getLIS(),
321 getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM());
322 VirtRegAuxInfo VRAI(*MF, *LIS, *VRM,
323 getAnalysis<MachineLoopInfoWrapperPass>().getLI(), MBFI,
324 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
325 VRAI.calculateSpillWeightsAndHints();
326
327 SpillerInstance.reset(
328 createInlineSpiller({*LIS, LiveStks, MDT, MBFI}, *MF, *VRM, VRAI));
329
330 allocatePhysRegs();
331 postOptimization();
332
333 // Diagnostic output before rewriting
334 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
335
336 releaseMemory();
337 return true;
338}
339
341 return new RABasic();
342}
343
345 return new RABasic(F);
346}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
Live Register Matrix
#define F(x, y, z)
Definition: MD5.cpp:55
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
regallocbasic
Basic Register Allocator
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static AllocationOrder create(unsigned VirtReg, const VirtRegMap &VRM, const RegisterClassInfo &RegClassInfo, const LiveRegMatrix *Matrix)
Create a new AllocationOrder for VirtReg.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:270
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
Query interferences between a single live virtual register and a live interval union.
const SmallVectorImpl< const LiveInterval * > & interferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
float weight() const
Definition: LiveInterval.h:719
Register reg() const
Definition: LiveInterval.h:718
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:826
Callback methods for LiveRangeEdit owners.
Definition: LiveRangeEdit.h:45
virtual bool LRE_CanEraseVirtReg(Register)
Called when a virtual register is no longer used.
Definition: LiveRangeEdit.h:56
virtual void LRE_WillShrinkVirtReg(Register)
Called before shrinking the live range of a virtual register.
Definition: LiveRangeEdit.h:59
@ IK_VirtReg
Virtual register interference.
Definition: LiveRegMatrix.h:91
@ IK_Free
No interference, go ahead and assign.
Definition: LiveRegMatrix.h:86
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
constexpr bool isValid() const
Definition: MCRegister.h:81
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual MachineFunctionProperties getClearedProperties() const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
virtual void releaseMemory()
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: Pass.cpp:102
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:62
virtual MCRegister selectOrSplit(const LiveInterval &VirtReg, SmallVectorImpl< Register > &splitLVRs)=0
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
virtual Spiller & spiller()=0
virtual const LiveInterval * dequeue()=0
dequeue - Return the next unassigned register, or NULL.
virtual void enqueueImpl(const LiveInterval *LI)=0
enqueue - Add VirtReg to the priority queue of unassigned registers.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
bool empty() const
Definition: SmallVector.h:81
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
Spiller interface.
Definition: Spiller.h:31
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
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.
Definition: AddressRanges.h:18
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Spiller * createInlineSpiller(const Spiller::RequiredAnalyses &Analyses, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
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.
char & RABasicID
Basic register allocator.