LLVM 19.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"
26#include "llvm/CodeGen/Passes.h"
31#include "llvm/Pass.h"
32#include "llvm/Support/Debug.h"
34#include <queue>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "regalloc"
39
40static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
42
43namespace {
44 struct CompSpillWeight {
45 bool operator()(const LiveInterval *A, const LiveInterval *B) const {
46 return A->weight() < B->weight();
47 }
48 };
49}
50
51namespace {
52/// RABasic provides a minimal implementation of the basic register allocation
53/// algorithm. It prioritizes live virtual registers by spill weight and spills
54/// whenever a register is unavailable. This is not practical in production but
55/// provides a useful baseline both for measuring other allocators and comparing
56/// the speed of the basic algorithm against other styles of allocators.
57class RABasic : public MachineFunctionPass,
58 public RegAllocBase,
60 // context
61 MachineFunction *MF = nullptr;
62
63 // state
64 std::unique_ptr<Spiller> SpillerInstance;
65 std::priority_queue<const LiveInterval *, std::vector<const LiveInterval *>,
66 CompSpillWeight>
67 Queue;
68
69 // Scratch space. Allocated here to avoid repeated malloc calls in
70 // selectOrSplit().
71 BitVector UsableRegs;
72
73 bool LRE_CanEraseVirtReg(Register) override;
74 void LRE_WillShrinkVirtReg(Register) override;
75
76public:
78
79 /// Return the pass name.
80 StringRef getPassName() const override { return "Basic Register Allocator"; }
81
82 /// RABasic analysis usage.
83 void getAnalysisUsage(AnalysisUsage &AU) const override;
84
85 void releaseMemory() override;
86
87 Spiller &spiller() override { return *SpillerInstance; }
88
89 void enqueueImpl(const LiveInterval *LI) override { Queue.push(LI); }
90
91 const LiveInterval *dequeue() override {
92 if (Queue.empty())
93 return nullptr;
94 const LiveInterval *LI = Queue.top();
95 Queue.pop();
96 return LI;
97 }
98
100 SmallVectorImpl<Register> &SplitVRegs) override;
101
102 /// Perform register allocation.
103 bool runOnMachineFunction(MachineFunction &mf) override;
104
107 MachineFunctionProperties::Property::NoPHIs);
108 }
109
112 MachineFunctionProperties::Property::IsSSA);
113 }
114
115 // Helper for spilling all live virtual registers currently unified under preg
116 // that interfere with the most recently queried lvr. Return true if spilling
117 // was successful, and append any new spilled/split intervals to splitLVRs.
118 bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg,
119 SmallVectorImpl<Register> &SplitVRegs);
120
121 static char ID;
122};
123
124char RABasic::ID = 0;
125
126} // end anonymous namespace
127
128char &llvm::RABasicID = RABasic::ID;
129
130INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
131 false, false)
135INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
136INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
144 false)
145
146bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
147 LiveInterval &LI = LIS->getInterval(VirtReg);
148 if (VRM->hasPhys(VirtReg)) {
149 Matrix->unassign(LI);
150 aboutToRemoveInterval(LI);
151 return true;
152 }
153 // Unassigned virtreg is probably in the priority queue.
154 // RegAllocBase will erase it after dequeueing.
155 // Nonetheless, clear the live-range so that the debug
156 // dump will show the right state for that VirtReg.
157 LI.clear();
158 return false;
159}
160
161void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
162 if (!VRM->hasPhys(VirtReg))
163 return;
164
165 // Register is assigned, put it back on the queue for reassignment.
166 LiveInterval &LI = LIS->getInterval(VirtReg);
167 Matrix->unassign(LI);
168 enqueue(&LI);
169}
170
171RABasic::RABasic(RegClassFilterFunc F):
173 RegAllocBase(F) {
174}
175
176void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
177 AU.setPreservesCFG();
198}
199
200void RABasic::releaseMemory() {
201 SpillerInstance.reset();
202}
203
204
205// Spill or split all live virtual registers currently unified under PhysReg
206// that interfere with VirtReg. The newly spilled or split live intervals are
207// returned by appending them to SplitVRegs.
208bool RABasic::spillInterferences(const LiveInterval &VirtReg,
209 MCRegister PhysReg,
210 SmallVectorImpl<Register> &SplitVRegs) {
211 // Record each interference and determine if all are spillable before mutating
212 // either the union or live intervals.
214
215 // Collect interferences assigned to any alias of the physical register.
216 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
217 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
218 for (const auto *Intf : reverse(Q.interferingVRegs())) {
219 if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
220 return false;
221 Intfs.push_back(Intf);
222 }
223 }
224 LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
225 << " interferences with " << VirtReg << "\n");
226 assert(!Intfs.empty() && "expected interference");
227
228 // Spill each interfering vreg allocated to PhysReg or an alias.
229 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
230 const LiveInterval &Spill = *Intfs[i];
231
232 // Skip duplicates.
233 if (!VRM->hasPhys(Spill.reg()))
234 continue;
235
236 // Deallocate the interfering vreg by removing it from the union.
237 // A LiveInterval instance may not be in a union during modification!
238 Matrix->unassign(Spill);
239
240 // Spill the extracted interval.
241 LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
242 spiller().spill(LRE);
243 }
244 return true;
245}
246
247// Driver for the register assignment and splitting heuristics.
248// Manages iteration over the LiveIntervalUnions.
249//
250// This is a minimal implementation of register assignment and splitting that
251// spills whenever we run out of registers.
252//
253// selectOrSplit can only be called once per live virtual register. We then do a
254// single interference test for each register the correct class until we find an
255// available register. So, the number of interference tests in the worst case is
256// |vregs| * |machineregs|. And since the number of interference tests is
257// minimal, there is no value in caching them outside the scope of
258// selectOrSplit().
259MCRegister RABasic::selectOrSplit(const LiveInterval &VirtReg,
260 SmallVectorImpl<Register> &SplitVRegs) {
261 // Populate a list of physical register spill candidates.
262 SmallVector<MCRegister, 8> PhysRegSpillCands;
263
264 // Check for an available register in this class.
265 auto Order =
266 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
267 for (MCRegister PhysReg : Order) {
268 assert(PhysReg.isValid());
269 // Check for interference in PhysReg
270 switch (Matrix->checkInterference(VirtReg, PhysReg)) {
272 // PhysReg is available, allocate it.
273 return PhysReg;
274
276 // Only virtual registers in the way, we may be able to spill them.
277 PhysRegSpillCands.push_back(PhysReg);
278 continue;
279
280 default:
281 // RegMask or RegUnit interference.
282 continue;
283 }
284 }
285
286 // Try to spill another interfering reg with less spill weight.
287 for (MCRegister &PhysReg : PhysRegSpillCands) {
288 if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
289 continue;
290
291 assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
292 "Interference after spill.");
293 // Tell the caller to allocate to this newly freed physical register.
294 return PhysReg;
295 }
296
297 // No other spill candidates were found, so spill the current VirtReg.
298 LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
299 if (!VirtReg.isSpillable())
300 return ~0u;
301 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
302 spiller().spill(LRE);
303
304 // The live virtual register requesting allocation was spilled, so tell
305 // the caller not to allocate anything during this round.
306 return 0;
307}
308
309bool RABasic::runOnMachineFunction(MachineFunction &mf) {
310 LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
311 << "********** Function: " << mf.getName() << '\n');
312
313 MF = &mf;
314 RegAllocBase::init(getAnalysis<VirtRegMap>(),
315 getAnalysis<LiveIntervals>(),
316 getAnalysis<LiveRegMatrix>());
317 VirtRegAuxInfo VRAI(*MF, *LIS, *VRM, getAnalysis<MachineLoopInfo>(),
318 getAnalysis<MachineBlockFrequencyInfo>());
319 VRAI.calculateSpillWeightsAndHints();
320
321 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
322
323 allocatePhysRegs();
324 postOptimization();
325
326 // Diagnostic output before rewriting
327 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
328
329 releaseMemory();
330 return true;
331}
332
334 return new RABasic();
335}
336
338 return new RABasic(F);
339}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
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:59
#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:283
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:269
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
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:90
@ IK_Free
No interference, go ahead and assign.
Definition: LiveRegMatrix.h:85
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
constexpr bool isValid() const
Definition: MCRegister.h:81
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:61
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
SlotIndexes pass.
Definition: SlotIndexes.h:300
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Spiller interface.
Definition: Spiller.h:24
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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
static bool allocateAllRegClasses(const TargetRegisterInfo &, const TargetRegisterClass &)
Default register class filter function for register allocation.
Spiller * createInlineSpiller(MachineFunctionPass &Pass, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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.
std::function< bool(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC)> RegClassFilterFunc