LLVM 23.0.0git
RegAllocBase.cpp
Go to the documentation of this file.
1//===- RegAllocBase.cpp - Register Allocator Base Class -------------------===//
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 RegAllocBase class which provides common functionality
10// for LiveIntervalUnion-based register allocators.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RegAllocBase.h"
16#include "llvm/ADT/Statistic.h"
27#include "llvm/IR/Module.h"
29#include "llvm/Pass.h"
31#include "llvm/Support/Debug.h"
33#include "llvm/Support/Timer.h"
35#include <cassert>
36
37using namespace llvm;
38
39#define DEBUG_TYPE "regalloc"
40
41STATISTIC(NumNewQueued, "Number of new live ranges queued");
42
43// Temporary verification option until we can put verification inside
44// MachineVerifier.
47 cl::Hidden, cl::desc("Verify during register allocation"));
48
49const char RegAllocBase::TimerGroupName[] = "regalloc";
50const char RegAllocBase::TimerGroupDescription[] = "Register Allocation";
52
53//===----------------------------------------------------------------------===//
54// RegAllocBase Implementation
55//===----------------------------------------------------------------------===//
56
57// Pin the vtable to this file.
58void RegAllocBase::anchor() {}
59
61 LiveRegMatrix &mat) {
62 TRI = &vrm.getTargetRegInfo();
63 MRI = &vrm.getRegInfo();
64 VRM = &vrm;
65 LIS = &lis;
66 Matrix = &mat;
67 MRI->freezeReservedRegs();
68 RegClassInfo.runOnMachineFunction(vrm.getMachineFunction());
69 FailedVRegs.clear();
70}
71
72// Visit all the live registers. If they are already assigned to a physical
73// register, unify them with the corresponding LiveIntervalUnion, otherwise push
74// them on the priority queue for later assignment.
75void RegAllocBase::seedLiveRegs() {
76 NamedRegionTimer T("seed", "Seed Live Regs", TimerGroupName,
78 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
80 if (MRI->reg_nodbg_empty(Reg))
81 continue;
82 enqueue(&LIS->getInterval(Reg));
83 }
84}
85
86// Top-level driver to manage the queue of unassigned VirtRegs and call the
87// selectOrSplit implementation.
89 seedLiveRegs();
90
91 // Continue assigning vregs one at a time to available physical registers.
92 while (const LiveInterval *VirtReg = dequeue()) {
93 assert(!VRM->hasPhys(VirtReg->reg()) && "Register already assigned");
94
95 // Unused registers can appear when the spiller coalesces snippets.
96 if (MRI->reg_nodbg_empty(VirtReg->reg())) {
97 LLVM_DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
98 aboutToRemoveInterval(*VirtReg);
99 LIS->removeInterval(VirtReg->reg());
100 continue;
101 }
102
103 // Invalidate all interference queries, live ranges could have changed.
104 Matrix->invalidateVirtRegs();
105
106 // selectOrSplit requests the allocator to return an available physical
107 // register if possible and populate a list of new live intervals that
108 // result from splitting.
109 LLVM_DEBUG(dbgs() << "\nselectOrSplit "
110 << TRI->getRegClassName(MRI->getRegClass(VirtReg->reg()))
111 << ':' << *VirtReg << '\n');
112
113 using VirtRegVec = SmallVector<Register, 4>;
114
115 VirtRegVec SplitVRegs;
116 MCRegister AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
117
118 if (AvailablePhysReg == ~0u) {
119 // selectOrSplit failed to find a register!
120 // Probably caused by an inline asm.
121 MachineInstr *MI = nullptr;
122 for (MachineInstr &MIR : MRI->reg_instructions(VirtReg->reg())) {
123 MI = &MIR;
124 if (MI->isInlineAsm())
125 break;
126 }
127
128 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg->reg());
129 AvailablePhysReg = getErrorAssignment(*RC, MI);
130
131 // Keep going after reporting the error.
132 cleanupFailedVReg(VirtReg->reg(), AvailablePhysReg, SplitVRegs);
133 } else if (AvailablePhysReg)
134 Matrix->assign(*VirtReg, AvailablePhysReg);
135
136 for (Register Reg : SplitVRegs) {
137 assert(LIS->hasInterval(Reg));
138
139 LiveInterval *SplitVirtReg = &LIS->getInterval(Reg);
140 assert(!VRM->hasPhys(SplitVirtReg->reg()) && "Register already assigned");
141 if (MRI->reg_nodbg_empty(SplitVirtReg->reg())) {
142 assert(SplitVirtReg->empty() && "Non-empty but used interval");
143 LLVM_DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
144 aboutToRemoveInterval(*SplitVirtReg);
145 LIS->removeInterval(SplitVirtReg->reg());
146 continue;
147 }
148 LLVM_DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
149 assert(SplitVirtReg->reg().isVirtual() &&
150 "expect split value in virtual register");
151 enqueue(SplitVirtReg);
152 ++NumNewQueued;
153 }
154 }
155}
156
159
160 // Verify LiveRegMatrix after spilling (no dangling pointers).
161 assert(Matrix->isValid() && "LiveRegMatrix validation failed");
162
163 for (auto *DeadInst : DeadRemats) {
164 LIS->RemoveMachineInstrFromMaps(*DeadInst);
165 DeadInst->eraseFromParent();
166 }
167 DeadRemats.clear();
168}
169
171 SmallVectorImpl<Register> &SplitRegs) {
172 // We still should produce valid IR. Kill all the uses and reduce the live
173 // ranges so that we don't think it's possible to introduce kill flags later
174 // which will fail the verifier.
175 for (MachineOperand &MO : MRI->reg_operands(FailedReg)) {
176 if (MO.readsReg())
177 MO.setIsUndef(true);
178 }
179
180 if (!MRI->isReserved(PhysReg)) {
181 // Physical liveness for any aliasing registers is now unreliable, so delete
182 // the uses.
183 for (MCRegAliasIterator Aliases(PhysReg, TRI, true); Aliases.isValid();
184 ++Aliases) {
185 for (MachineOperand &MO : MRI->reg_operands(*Aliases)) {
186 if (MO.readsReg())
187 MO.setIsUndef(true);
188 }
189 }
190 }
191
192 // Directly perform the rewrite, and do not leave it to VirtRegRewriter as
193 // usual. This avoids trying to manage illegal overlapping assignments in
194 // LiveRegMatrix.
195 MRI->replaceRegWith(FailedReg, PhysReg);
196 LIS->removeInterval(FailedReg);
197}
198
200 const Register Reg = LI->reg();
201
202 assert(Reg.isVirtual() && "Can only enqueue virtual registers");
203
204 if (VRM->hasPhys(Reg))
205 return;
206
207 if (shouldAllocateRegister(Reg)) {
208 LLVM_DEBUG(dbgs() << "Enqueuing " << printReg(Reg, TRI) << '\n');
209 enqueueImpl(LI);
210 } else {
211 LLVM_DEBUG(dbgs() << "Not enqueueing " << printReg(Reg, TRI)
212 << " in skipped register class\n");
213 }
214}
215
217 const MachineInstr *CtxMI) {
218 MachineFunction &MF = VRM->getMachineFunction();
219
220 // Avoid printing the error for every single instance of the register. It
221 // would be better if this were per register class.
222 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
223 if (EmitError)
224 MF.getProperties().setFailedRegAlloc();
225
226 const Function &Fn = MF.getFunction();
227 LLVMContext &Context = Fn.getContext();
228
229 ArrayRef<MCPhysReg> AllocOrder = RegClassInfo.getOrder(&RC);
230 if (AllocOrder.empty()) {
231 // If the allocation order is empty, it likely means all registers in the
232 // class are reserved. We still to need to pick something, so look at the
233 // underlying class.
234 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
235
236 if (EmitError) {
237 Context.diagnose(DiagnosticInfoRegAllocFailure(
238 "no registers from class available to allocate", Fn,
239 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
240 }
241
242 assert(!RawRegs.empty() && "register classes cannot have no registers");
243 return RawRegs.front();
244 }
245
246 if (EmitError) {
247 if (CtxMI && CtxMI->isInlineAsm()) {
248 CtxMI->emitInlineAsmError(
249 "inline assembly requires more registers than available");
250 } else {
251 Context.diagnose(DiagnosticInfoRegAllocFailure(
252 "ran out of registers during register allocation", Fn,
253 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
254 }
255 }
256
257 return AllocOrder.front();
258}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define T
This header defines classes/functions to handle pass execution timing information with interfaces for...
static cl::opt< bool, true > VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled), cl::Hidden, cl::desc("Verify during register allocation"))
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
front - Get the first element.
Definition ArrayRef.h:145
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LiveInterval - This class represents the liveness of a register, or stack slot.
Register reg() const
LiveInterval & getInterval(Register Reg)
bool empty() const
MCRegAliasIterator enumerates all registers aliasing Reg.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
bool isInlineAsm() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void emitInlineAsmError(const Twine &ErrMsg) const
Emit an error referring to the source location of this instruction.
MachineOperand class - Representation of each machine instruction operand.
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
virtual void aboutToRemoveInterval(const LiveInterval &LI)
Method called when the allocator is about to remove a LiveInterval.
virtual MCRegister selectOrSplit(const LiveInterval &VirtReg, SmallVectorImpl< Register > &splitLVRs)=0
MCPhysReg getErrorAssignment(const TargetRegisterClass &RC, const MachineInstr *CtxMI=nullptr)
Query a physical register to use as a filler in contexts where the allocation has failed.
void enqueue(const LiveInterval *LI)
enqueue - Add VirtReg to the priority queue of unassigned registers.
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
SmallPtrSet< MachineInstr *, 32 > DeadRemats
Inst which is a def of an original reg and whose defs are already all dead after remat is saved in De...
void cleanupFailedVReg(Register FailedVReg, MCRegister PhysReg, SmallVectorImpl< Register > &SplitRegs)
Perform cleanups on registers that failed to allocate.
SmallSet< Register, 2 > FailedVRegs
virtual Spiller & spiller()=0
const TargetRegisterInfo * TRI
LiveIntervals * LIS
static const char TimerGroupName[]
static const char TimerGroupDescription[]
LiveRegMatrix * Matrix
virtual const LiveInterval * dequeue()=0
dequeue - Return the next unassigned register, or NULL.
virtual void postOptimization()
VirtRegMap * VRM
RegisterClassInfo RegClassInfo
MachineRegisterInfo * MRI
virtual void enqueueImpl(const LiveInterval *LI)=0
enqueue - Add VirtReg to the priority queue of unassigned registers.
bool shouldAllocateRegister(Register Reg)
Get whether a given register should be allocated.
static bool VerifyEnabled
VerifyEnabled - True when -verify-regalloc is given.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
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.
virtual void postOptimization()
Definition Spiller.h:49
ArrayRef< MCPhysReg > getRegisters() const
MachineRegisterInfo & getRegInfo() const
Definition VirtRegMap.h:80
MachineFunction & getMachineFunction() const
Definition VirtRegMap.h:75
const TargetRegisterInfo & getTargetRegInfo() const
Definition VirtRegMap.h:81
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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.
This class is basically a combination of TimeRegion and Timer.
Definition Timer.h:175