LLVM  14.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 "LiveDebugVariables.h"
16 #include "RegAllocBase.h"
28 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/Spiller.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
36 #include <cstdlib>
37 #include <queue>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "regalloc"
42 
43 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
45 
46 namespace {
47  struct CompSpillWeight {
48  bool operator()(LiveInterval *A, LiveInterval *B) const {
49  return A->weight() < B->weight();
50  }
51  };
52 }
53 
54 namespace {
55 /// RABasic provides a minimal implementation of the basic register allocation
56 /// algorithm. It prioritizes live virtual registers by spill weight and spills
57 /// whenever a register is unavailable. This is not practical in production but
58 /// provides a useful baseline both for measuring other allocators and comparing
59 /// the speed of the basic algorithm against other styles of allocators.
60 class RABasic : public MachineFunctionPass,
61  public RegAllocBase,
62  private LiveRangeEdit::Delegate {
63  // context
64  MachineFunction *MF;
65 
66  // state
67  std::unique_ptr<Spiller> SpillerInstance;
68  std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
69  CompSpillWeight> 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 
78 public:
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(LiveInterval *LI) override {
92  Queue.push(LI);
93  }
94 
95  LiveInterval *dequeue() override {
96  if (Queue.empty())
97  return nullptr;
98  LiveInterval *LI = Queue.top();
99  Queue.pop();
100  return LI;
101  }
102 
103  MCRegister selectOrSplit(LiveInterval &VirtReg,
104  SmallVectorImpl<Register> &SplitVRegs) override;
105 
106  /// Perform register allocation.
107  bool runOnMachineFunction(MachineFunction &mf) override;
108 
109  MachineFunctionProperties getRequiredProperties() const override {
112  }
113 
114  MachineFunctionProperties getClearedProperties() const override {
117  }
118 
119  // Helper for spilling all live virtual registers currently unified under preg
120  // that interfere with the most recently queried lvr. Return true if spilling
121  // was successful, and append any new spilled/split intervals to splitLVRs.
122  bool spillInterferences(LiveInterval &VirtReg, MCRegister PhysReg,
123  SmallVectorImpl<Register> &SplitVRegs);
124 
125  static char ID;
126 };
127 
128 char RABasic::ID = 0;
129 
130 } // end anonymous namespace
131 
133 
134 INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
135  false, false)
139 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
140 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
147  false)
148 
149 bool 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 
164 void 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 
174 RABasic::RABasic(RegClassFilterFunc F):
176  RegAllocBase(F) {
177 }
178 
179 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
180  AU.setPreservesCFG();
188  AU.addRequired<LiveStacks>();
189  AU.addPreserved<LiveStacks>();
196  AU.addRequired<VirtRegMap>();
197  AU.addPreserved<VirtRegMap>();
200  MachineFunctionPass::getAnalysisUsage(AU);
201 }
202 
203 void 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.
211 bool RABasic::spillInterferences(LiveInterval &VirtReg, MCRegister PhysReg,
212  SmallVectorImpl<Register> &SplitVRegs) {
213  // Record each interference and determine if all are spillable before mutating
214  // either the union or live intervals.
216 
217  // Collect interferences assigned to any alias of the physical register.
218  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
219  LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
221  for (unsigned i = Q.interferingVRegs().size(); i; --i) {
222  LiveInterval *Intf = Q.interferingVRegs()[i - 1];
223  if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
224  return false;
225  Intfs.push_back(Intf);
226  }
227  }
228  LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
229  << " interferences with " << VirtReg << "\n");
230  assert(!Intfs.empty() && "expected interference");
231 
232  // Spill each interfering vreg allocated to PhysReg or an alias.
233  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
234  LiveInterval &Spill = *Intfs[i];
235 
236  // Skip duplicates.
237  if (!VRM->hasPhys(Spill.reg()))
238  continue;
239 
240  // Deallocate the interfering vreg by removing it from the union.
241  // A LiveInterval instance may not be in a union during modification!
242  Matrix->unassign(Spill);
243 
244  // Spill the extracted interval.
245  LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
246  spiller().spill(LRE);
247  }
248  return true;
249 }
250 
251 // Driver for the register assignment and splitting heuristics.
252 // Manages iteration over the LiveIntervalUnions.
253 //
254 // This is a minimal implementation of register assignment and splitting that
255 // spills whenever we run out of registers.
256 //
257 // selectOrSplit can only be called once per live virtual register. We then do a
258 // single interference test for each register the correct class until we find an
259 // available register. So, the number of interference tests in the worst case is
260 // |vregs| * |machineregs|. And since the number of interference tests is
261 // minimal, there is no value in caching them outside the scope of
262 // selectOrSplit().
263 MCRegister RABasic::selectOrSplit(LiveInterval &VirtReg,
264  SmallVectorImpl<Register> &SplitVRegs) {
265  // Populate a list of physical register spill candidates.
266  SmallVector<MCRegister, 8> PhysRegSpillCands;
267 
268  // Check for an available register in this class.
269  auto Order =
270  AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
271  for (MCRegister PhysReg : Order) {
272  assert(PhysReg.isValid());
273  // Check for interference in PhysReg
274  switch (Matrix->checkInterference(VirtReg, PhysReg)) {
275  case LiveRegMatrix::IK_Free:
276  // PhysReg is available, allocate it.
277  return PhysReg;
278 
279  case LiveRegMatrix::IK_VirtReg:
280  // Only virtual registers in the way, we may be able to spill them.
281  PhysRegSpillCands.push_back(PhysReg);
282  continue;
283 
284  default:
285  // RegMask or RegUnit interference.
286  continue;
287  }
288  }
289 
290  // Try to spill another interfering reg with less spill weight.
291  for (MCRegister &PhysReg : PhysRegSpillCands) {
292  if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
293  continue;
294 
295  assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
296  "Interference after spill.");
297  // Tell the caller to allocate to this newly freed physical register.
298  return PhysReg;
299  }
300 
301  // No other spill candidates were found, so spill the current VirtReg.
302  LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
303  if (!VirtReg.isSpillable())
304  return ~0u;
305  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
306  spiller().spill(LRE);
307 
308  // The live virtual register requesting allocation was spilled, so tell
309  // the caller not to allocate anything during this round.
310  return 0;
311 }
312 
313 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
314  LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
315  << "********** Function: " << mf.getName() << '\n');
316 
317  MF = &mf;
318  RegAllocBase::init(getAnalysis<VirtRegMap>(),
319  getAnalysis<LiveIntervals>(),
320  getAnalysis<LiveRegMatrix>());
321  VirtRegAuxInfo VRAI(*MF, *LIS, *VRM, getAnalysis<MachineLoopInfo>(),
322  getAnalysis<MachineBlockFrequencyInfo>());
323  VRAI.calculateSpillWeightsAndHints();
324 
325  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
326 
327  allocatePhysRegs();
328  postOptimization();
329 
330  // Diagnostic output before rewriting
331  LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
332 
333  releaseMemory();
334  return true;
335 }
336 
338  return new RABasic();
339 }
340 
342  return new RABasic(F);
343 }
i
i
Definition: README.txt:29
llvm::Spiller
Spiller interface.
Definition: Spiller.h:24
LiveRegMatrix.h
MachineInstr.h
llvm
This file implements support for optimizing divisions by a constant.
Definition: AllocatorList.h:23
llvm::RABasicID
char & RABasicID
Basic register allocator.
Definition: RegAllocBasic.cpp:132
AllocationOrder.h
Pass.h
llvm::LiveInterval::isSpillable
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:813
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
LiveDebugVariables.h
llvm::VirtRegAuxInfo
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
Definition: CalcSpillWeights.h:46
llvm::LiveInterval::weight
float weight() const
Definition: LiveInterval.h:712
llvm::MCRegister::isValid
bool isValid() const
Definition: MCRegister.h:76
llvm::VirtRegMap
Definition: VirtRegMap.h:33
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
Spiller.h
llvm::MachineFunctionProperties::Property::IsSSA
@ IsSSA
llvm::MachineFunctionProperties
Properties which a MachineFunction may have at a given point in time.
Definition: MachineFunction.h:111
TRI
unsigned const TargetRegisterInfo * TRI
Definition: MachineSink.cpp:1567
llvm::RegisterRegAlloc
Definition: RegAllocRegistry.h:61
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::AMDGPU::HSAMD::ValueKind::Queue
@ Queue
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::MachineLoopInfo
Definition: MachineLoopInfo.h:90
MachineRegisterInfo.h
AliasAnalysis.h
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::createInlineSpiller
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...
Definition: InlineSpiller.cpp:246
MachineLoopInfo.h
llvm::MachineBlockFrequencyInfo
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
Definition: MachineBlockFrequencyInfo.h:33
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
false
Definition: StackSlotColoring.cpp:142
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::LiveRangeEdit
Definition: LiveRangeEdit.h:46
llvm::MachineFunctionProperties::set
MachineFunctionProperties & set(Property P)
Definition: MachineFunction.h:169
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator", false, false) INITIALIZE_PASS_END(RABasic
llvm::SlotIndexes
SlotIndexes pass.
Definition: SlotIndexes.h:314
llvm::BitVector
Definition: BitVector.h:74
llvm::LiveInterval
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:680
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
Passes.h
LiveIntervals.h
VirtRegMap.h
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
llvm::RegClassFilterFunc
std::function< bool(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC)> RegClassFilterFunc
Definition: RegAllocCommon.h:17
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:441
MachineFunctionPass.h
llvm::MachineFunction::getName
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Definition: MachineFunction.cpp:541
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::LiveDebugVariables
Definition: LiveDebugVariables.h:32
llvm::MachineFunction
Definition: MachineFunction.h:230
Matrix
Live Register Matrix
Definition: LiveRegMatrix.cpp:44
llvm::AnalysisUsage::setPreservesCFG
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::AnalysisUsage::addPreservedID
AnalysisUsage & addPreservedID(const void *ID)
Definition: PassAnalysisSupport.h:88
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
llvm::LiveIntervalUnion::Query::interferingVRegs
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
Definition: LiveIntervalUnion.h:166
llvm::Register
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
LiveRangeEdit.h
RegAllocBase.h
llvm::MachineFunctionProperties::Property::NoPHIs
@ NoPHIs
llvm::allocateAllRegClasses
static bool allocateAllRegClasses(const TargetRegisterInfo &, const TargetRegisterClass &)
Default register class filter function for register allocation.
Definition: RegAllocCommon.h:24
llvm::RegAllocBase
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:61
llvm::LiveIntervals
Definition: LiveIntervals.h:54
llvm::LiveIntervalUnion::Query::collectInterferingVRegs
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
Definition: LiveIntervalUnion.cpp:128
llvm::MCRegUnitIterator
Definition: MCRegisterInfo.h:677
llvm::LiveIntervalUnion::Query
Query interferences between a single live virtual register and a live interval union.
Definition: LiveIntervalUnion.h:112
LiveStacks.h
Allocator
Basic Register Allocator
Definition: RegAllocBasic.cpp:146
llvm::MCRegisterInfo::DiffListIterator::isValid
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
Definition: MCRegisterInfo.h:224
llvm::AAResultsWrapperPass
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Definition: AliasAnalysis.h:1336
llvm::MachineDominatorsID
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
llvm::LiveInterval::reg
Register reg() const
Definition: LiveInterval.h:711
llvm::LiveRange::clear
void clear()
Definition: LiveInterval.h:292
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:43
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
llvm::createBasicRegisterAllocator
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
Definition: RegAllocBasic.cpp:337
llvm::AnalysisUsage::addRequiredID
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:267
llvm::LiveRangeEdit::Delegate
Callback methods for LiveRangeEdit owners.
Definition: LiveRangeEdit.h:49
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
CalcSpillWeights.h
regallocbasic
regallocbasic
Definition: RegAllocBasic.cpp:146
raw_ostream.h
llvm::MachineDominatorTree
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Definition: MachineDominators.h:45
llvm::printReg
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.
Definition: TargetRegisterInfo.cpp:110
llvm::LiveStacks
Definition: LiveStacks.h:31
MachineBlockFrequencyInfo.h
basicRegAlloc
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator)
TargetRegisterInfo.h
Debug.h
RegAllocRegistry.h
llvm::MCRegister
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:24
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:37
llvm::LiveRegMatrix
Definition: LiveRegMatrix.h:40