LLVM 22.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"
28#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
32#include "llvm/Support/Timer.h"
34#include <cassert>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "regalloc"
39
40STATISTIC(NumNewQueued, "Number of new live ranges queued");
41
42// Temporary verification option until we can put verification inside
43// MachineVerifier.
46 cl::Hidden, cl::desc("Verify during register allocation"));
47
48const char RegAllocBase::TimerGroupName[] = "regalloc";
49const char RegAllocBase::TimerGroupDescription[] = "Register Allocation";
51
52//===----------------------------------------------------------------------===//
53// RegAllocBase Implementation
54//===----------------------------------------------------------------------===//
55
56// Pin the vtable to this file.
57void RegAllocBase::anchor() {}
58
60 LiveRegMatrix &mat) {
61 TRI = &vrm.getTargetRegInfo();
62 MRI = &vrm.getRegInfo();
63 VRM = &vrm;
64 LIS = &lis;
65 Matrix = &mat;
68 FailedVRegs.clear();
69}
70
71// Visit all the live registers. If they are already assigned to a physical
72// register, unify them with the corresponding LiveIntervalUnion, otherwise push
73// them on the priority queue for later assignment.
74void RegAllocBase::seedLiveRegs() {
75 NamedRegionTimer T("seed", "Seed Live Regs", TimerGroupName,
77 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
79 if (MRI->reg_nodbg_empty(Reg))
80 continue;
81 enqueue(&LIS->getInterval(Reg));
82 }
83}
84
85// Top-level driver to manage the queue of unassigned VirtRegs and call the
86// selectOrSplit implementation.
88 seedLiveRegs();
89
90 // Continue assigning vregs one at a time to available physical registers.
91 while (const LiveInterval *VirtReg = dequeue()) {
92 assert(!VRM->hasPhys(VirtReg->reg()) && "Register already assigned");
93
94 // Unused registers can appear when the spiller coalesces snippets.
95 if (MRI->reg_nodbg_empty(VirtReg->reg())) {
96 LLVM_DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
97 aboutToRemoveInterval(*VirtReg);
98 LIS->removeInterval(VirtReg->reg());
99 continue;
100 }
101
102 // Invalidate all interference queries, live ranges could have changed.
104
105 // selectOrSplit requests the allocator to return an available physical
106 // register if possible and populate a list of new live intervals that
107 // result from splitting.
108 LLVM_DEBUG(dbgs() << "\nselectOrSplit "
109 << TRI->getRegClassName(MRI->getRegClass(VirtReg->reg()))
110 << ':' << *VirtReg << '\n');
111
112 using VirtRegVec = SmallVector<Register, 4>;
113
114 VirtRegVec SplitVRegs;
115 MCRegister AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
116
117 if (AvailablePhysReg == ~0u) {
118 // selectOrSplit failed to find a register!
119 // Probably caused by an inline asm.
120 MachineInstr *MI = nullptr;
121 for (MachineInstr &MIR : MRI->reg_instructions(VirtReg->reg())) {
122 MI = &MIR;
123 if (MI->isInlineAsm())
124 break;
125 }
126
127 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg->reg());
128 AvailablePhysReg = getErrorAssignment(*RC, MI);
129
130 // Keep going after reporting the error.
131 cleanupFailedVReg(VirtReg->reg(), AvailablePhysReg, SplitVRegs);
132 } else if (AvailablePhysReg)
133 Matrix->assign(*VirtReg, AvailablePhysReg);
134
135 for (Register Reg : SplitVRegs) {
136 assert(LIS->hasInterval(Reg));
137
138 LiveInterval *SplitVirtReg = &LIS->getInterval(Reg);
139 assert(!VRM->hasPhys(SplitVirtReg->reg()) && "Register already assigned");
140 if (MRI->reg_nodbg_empty(SplitVirtReg->reg())) {
141 assert(SplitVirtReg->empty() && "Non-empty but used interval");
142 LLVM_DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
143 aboutToRemoveInterval(*SplitVirtReg);
144 LIS->removeInterval(SplitVirtReg->reg());
145 continue;
146 }
147 LLVM_DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
148 assert(SplitVirtReg->reg().isVirtual() &&
149 "expect split value in virtual register");
150 enqueue(SplitVirtReg);
151 ++NumNewQueued;
152 }
153 }
154}
155
158 for (auto *DeadInst : DeadRemats) {
160 DeadInst->eraseFromParent();
161 }
162 DeadRemats.clear();
163}
164
166 SmallVectorImpl<Register> &SplitRegs) {
167 // We still should produce valid IR. Kill all the uses and reduce the live
168 // ranges so that we don't think it's possible to introduce kill flags later
169 // which will fail the verifier.
170 for (MachineOperand &MO : MRI->reg_operands(FailedReg)) {
171 if (MO.readsReg())
172 MO.setIsUndef(true);
173 }
174
175 if (!MRI->isReserved(PhysReg)) {
176 // Physical liveness for any aliasing registers is now unreliable, so delete
177 // the uses.
178 for (MCRegAliasIterator Aliases(PhysReg, TRI, true); Aliases.isValid();
179 ++Aliases) {
180 for (MachineOperand &MO : MRI->reg_operands(*Aliases)) {
181 if (MO.readsReg())
182 MO.setIsUndef(true);
183 }
184 }
185 }
186
187 // Directly perform the rewrite, and do not leave it to VirtRegRewriter as
188 // usual. This avoids trying to manage illegal overlapping assignments in
189 // LiveRegMatrix.
190 MRI->replaceRegWith(FailedReg, PhysReg);
191 LIS->removeInterval(FailedReg);
192}
193
195 const Register Reg = LI->reg();
196
197 assert(Reg.isVirtual() && "Can only enqueue virtual registers");
198
199 if (VRM->hasPhys(Reg))
200 return;
201
202 if (shouldAllocateRegister(Reg)) {
203 LLVM_DEBUG(dbgs() << "Enqueuing " << printReg(Reg, TRI) << '\n');
204 enqueueImpl(LI);
205 } else {
206 LLVM_DEBUG(dbgs() << "Not enqueueing " << printReg(Reg, TRI)
207 << " in skipped register class\n");
208 }
209}
210
212 const MachineInstr *CtxMI) {
214
215 // Avoid printing the error for every single instance of the register. It
216 // would be better if this were per register class.
217 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
218 if (EmitError)
219 MF.getProperties().setFailedRegAlloc();
220
221 const Function &Fn = MF.getFunction();
223
224 ArrayRef<MCPhysReg> AllocOrder = RegClassInfo.getOrder(&RC);
225 if (AllocOrder.empty()) {
226 // If the allocation order is empty, it likely means all registers in the
227 // class are reserved. We still to need to pick something, so look at the
228 // underlying class.
229 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
230
231 if (EmitError) {
233 "no registers from class available to allocate", Fn,
234 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
235 }
236
237 assert(!RawRegs.empty() && "register classes cannot have no registers");
238 return RawRegs.front();
239 }
240
241 if (EmitError) {
242 if (CtxMI && CtxMI->isInlineAsm()) {
243 CtxMI->emitInlineAsmError(
244 "inline assembly requires more registers than available");
245 } else {
247 "ran out of registers during register allocation", Fn,
248 CtxMI ? CtxMI->getDebugLoc() : DiagnosticLocation()));
249 }
250 }
251
252 return AllocOrder.front();
253}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
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:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:150
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:142
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:359
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.
Definition: LiveInterval.h:690
Register reg() const
Definition: LiveInterval.h:721
bool hasInterval(Register Reg) const
void RemoveMachineInstrFromMaps(MachineInstr &MI)
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
bool empty() const
Definition: LiveInterval.h:384
void invalidateVirtRegs()
Invalidate cached interference queries after modifying virtual register live ranges.
Definition: LiveRegMatrix.h:82
void assign(const LiveInterval &VirtReg, MCRegister PhysReg)
Assign VirtReg to PhysReg.
MCRegAliasIterator enumerates all registers aliasing Reg.
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
Definition: MachineInstr.h:72
bool isInlineAsm() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:511
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.
iterator_range< reg_iterator > reg_operands(Register Reg) const
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
iterator_range< reg_instr_iterator > reg_instructions(Register Reg) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
virtual void aboutToRemoveInterval(const LiveInterval &LI)
Method called when the allocator is about to remove a LiveInterval.
Definition: RegAllocBase.h:144
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...
Definition: RegAllocBase.h:83
void cleanupFailedVReg(Register FailedVReg, MCRegister PhysReg, SmallVectorImpl< Register > &SplitRegs)
Perform cleanups on registers that failed to allocate.
SmallSet< Register, 2 > FailedVRegs
Definition: RegAllocBase.h:85
virtual Spiller & spiller()=0
const TargetRegisterInfo * TRI
Definition: RegAllocBase.h:67
LiveIntervals * LIS
Definition: RegAllocBase.h:70
static const char TimerGroupName[]
Definition: RegAllocBase.h:140
static const char TimerGroupDescription[]
Definition: RegAllocBase.h:141
LiveRegMatrix * Matrix
Definition: RegAllocBase.h:71
virtual const LiveInterval * dequeue()=0
dequeue - Return the next unassigned register, or NULL.
virtual void postOptimization()
VirtRegMap * VRM
Definition: RegAllocBase.h:69
RegisterClassInfo RegClassInfo
Definition: RegAllocBase.h:72
MachineRegisterInfo * MRI
Definition: RegAllocBase.h:68
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.
Definition: RegAllocBase.h:95
static bool VerifyEnabled
VerifyEnabled - True when -verify-regalloc is given.
Definition: RegAllocBase.h:148
LLVM_ABI void runOnMachineFunction(const MachineFunction &MF, bool Rev=false)
runOnFunction - Prepare to answer questions about MF.
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:67
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:74
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
virtual void postOptimization()
Definition: Spiller.h:49
ArrayRef< MCPhysReg > getRegisters() const
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
MachineRegisterInfo & getRegInfo() const
Definition: VirtRegMap.h:80
MachineFunction & getMachineFunction() const
Definition: VirtRegMap.h:75
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition: VirtRegMap.h:87
const TargetRegisterInfo & getTargetRegInfo() const
Definition: VirtRegMap.h:81
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:464
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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
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:170