LLVM  4.0.0
RegAllocBasic.cpp
Go to the documentation of this file.
1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the RABasic function pass, which provides a minimal
11 // implementation of the basic register allocator.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/Passes.h"
16 #include "AllocationOrder.h"
17 #include "LiveDebugVariables.h"
18 #include "RegAllocBase.h"
19 #include "Spiller.h"
34 #include "llvm/Support/Debug.h"
37 #include <cstdlib>
38 #include <queue>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "regalloc"
43 
44 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
46 
47 namespace {
48  struct CompSpillWeight {
49  bool operator()(LiveInterval *A, LiveInterval *B) const {
50  return A->weight < B->weight;
51  }
52  };
53 }
54 
55 namespace {
56 /// RABasic provides a minimal implementation of the basic register allocation
57 /// algorithm. It prioritizes live virtual registers by spill weight and spills
58 /// whenever a register is unavailable. This is not practical in production but
59 /// provides a useful baseline both for measuring other allocators and comparing
60 /// the speed of the basic algorithm against other styles of allocators.
61 class RABasic : public MachineFunctionPass, public RegAllocBase
62 {
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 public:
76  RABasic();
77 
78  /// Return the pass name.
79  StringRef getPassName() const override { return "Basic Register Allocator"; }
80 
81  /// RABasic analysis usage.
82  void getAnalysisUsage(AnalysisUsage &AU) const override;
83 
84  void releaseMemory() override;
85 
86  Spiller &spiller() override { return *SpillerInstance; }
87 
88  void enqueue(LiveInterval *LI) override {
89  Queue.push(LI);
90  }
91 
92  LiveInterval *dequeue() override {
93  if (Queue.empty())
94  return nullptr;
95  LiveInterval *LI = Queue.top();
96  Queue.pop();
97  return LI;
98  }
99 
100  unsigned selectOrSplit(LiveInterval &VirtReg,
101  SmallVectorImpl<unsigned> &SplitVRegs) override;
102 
103  /// Perform register allocation.
104  bool runOnMachineFunction(MachineFunction &mf) override;
105 
106  MachineFunctionProperties getRequiredProperties() const override {
109  }
110 
111  // Helper for spilling all live virtual registers currently unified under preg
112  // that interfere with the most recently queried lvr. Return true if spilling
113  // was successful, and append any new spilled/split intervals to splitLVRs.
114  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
115  SmallVectorImpl<unsigned> &SplitVRegs);
116 
117  static char ID;
118 };
119 
120 char RABasic::ID = 0;
121 
122 } // end anonymous namespace
123 
124 RABasic::RABasic(): MachineFunctionPass(ID) {
125  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
126  initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
127  initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
128  initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
129  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
130  initializeLiveStacksPass(*PassRegistry::getPassRegistry());
131  initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
132  initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
133  initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
134  initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
135 }
136 
137 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
138  AU.setPreservesCFG();
146  AU.addRequired<LiveStacks>();
147  AU.addPreserved<LiveStacks>();
154  AU.addRequired<VirtRegMap>();
155  AU.addPreserved<VirtRegMap>();
158  MachineFunctionPass::getAnalysisUsage(AU);
159 }
160 
161 void RABasic::releaseMemory() {
162  SpillerInstance.reset();
163 }
164 
165 
166 // Spill or split all live virtual registers currently unified under PhysReg
167 // that interfere with VirtReg. The newly spilled or split live intervals are
168 // returned by appending them to SplitVRegs.
169 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
170  SmallVectorImpl<unsigned> &SplitVRegs) {
171  // Record each interference and determine if all are spillable before mutating
172  // either the union or live intervals.
174 
175  // Collect interferences assigned to any alias of the physical register.
176  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
177  LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
179  if (Q.seenUnspillableVReg())
180  return false;
181  for (unsigned i = Q.interferingVRegs().size(); i; --i) {
182  LiveInterval *Intf = Q.interferingVRegs()[i - 1];
183  if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
184  return false;
185  Intfs.push_back(Intf);
186  }
187  }
188  DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
189  " interferences with " << VirtReg << "\n");
190  assert(!Intfs.empty() && "expected interference");
191 
192  // Spill each interfering vreg allocated to PhysReg or an alias.
193  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
194  LiveInterval &Spill = *Intfs[i];
195 
196  // Skip duplicates.
197  if (!VRM->hasPhys(Spill.reg))
198  continue;
199 
200  // Deallocate the interfering vreg by removing it from the union.
201  // A LiveInterval instance may not be in a union during modification!
202  Matrix->unassign(Spill);
203 
204  // Spill the extracted interval.
205  LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, nullptr, &DeadRemats);
206  spiller().spill(LRE);
207  }
208  return true;
209 }
210 
211 // Driver for the register assignment and splitting heuristics.
212 // Manages iteration over the LiveIntervalUnions.
213 //
214 // This is a minimal implementation of register assignment and splitting that
215 // spills whenever we run out of registers.
216 //
217 // selectOrSplit can only be called once per live virtual register. We then do a
218 // single interference test for each register the correct class until we find an
219 // available register. So, the number of interference tests in the worst case is
220 // |vregs| * |machineregs|. And since the number of interference tests is
221 // minimal, there is no value in caching them outside the scope of
222 // selectOrSplit().
223 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
224  SmallVectorImpl<unsigned> &SplitVRegs) {
225  // Populate a list of physical register spill candidates.
226  SmallVector<unsigned, 8> PhysRegSpillCands;
227 
228  // Check for an available register in this class.
229  AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
230  while (unsigned PhysReg = Order.next()) {
231  // Check for interference in PhysReg
232  switch (Matrix->checkInterference(VirtReg, PhysReg)) {
233  case LiveRegMatrix::IK_Free:
234  // PhysReg is available, allocate it.
235  return PhysReg;
236 
237  case LiveRegMatrix::IK_VirtReg:
238  // Only virtual registers in the way, we may be able to spill them.
239  PhysRegSpillCands.push_back(PhysReg);
240  continue;
241 
242  default:
243  // RegMask or RegUnit interference.
244  continue;
245  }
246  }
247 
248  // Try to spill another interfering reg with less spill weight.
249  for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
250  PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
251  if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
252  continue;
253 
254  assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
255  "Interference after spill.");
256  // Tell the caller to allocate to this newly freed physical register.
257  return *PhysRegI;
258  }
259 
260  // No other spill candidates were found, so spill the current VirtReg.
261  DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
262  if (!VirtReg.isSpillable())
263  return ~0u;
264  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, nullptr, &DeadRemats);
265  spiller().spill(LRE);
266 
267  // The live virtual register requesting allocation was spilled, so tell
268  // the caller not to allocate anything during this round.
269  return 0;
270 }
271 
272 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
273  DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
274  << "********** Function: "
275  << mf.getName() << '\n');
276 
277  MF = &mf;
278  RegAllocBase::init(getAnalysis<VirtRegMap>(),
279  getAnalysis<LiveIntervals>(),
280  getAnalysis<LiveRegMatrix>());
281 
282  calculateSpillWeightsAndHints(*LIS, *MF, VRM,
283  getAnalysis<MachineLoopInfo>(),
284  getAnalysis<MachineBlockFrequencyInfo>());
285 
286  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
287 
288  allocatePhysRegs();
289  postOptimization();
290 
291  // Diagnostic output before rewriting
292  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
293 
294  releaseMemory();
295  return true;
296 }
297 
299 {
300  return new RABasic();
301 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
const unsigned reg
Definition: LiveInterval.h:656
size_t i
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:625
void initializeLiveDebugVariablesPass(PassRegistry &)
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:754
Spiller interface.
Definition: Spiller.h:25
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void initializeMachineLoopInfoPass(PassRegistry &)
void initializeRegisterCoalescerPass(PassRegistry &)
Live Register Matrix
AnalysisUsage & addRequired()
Query interferences between a single live virtual register and a live interval union.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
static RegisterRegAlloc basicRegAlloc("basic","basic register allocator", createBasicRegisterAllocator)
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:58
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
SlotIndexes pass.
Definition: SlotIndexes.h:323
AnalysisUsage & addPreservedID(const void *ID)
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
RegisterRegAlloc class - Track the registration of register allocators.
void initializeMachineDominatorTreePass(PassRegistry &)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
void initializeSlotIndexesPass(PassRegistry &)
void initializeLiveStacksPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
Represent the analysis usage information of a pass.
void initializeLiveIntervalsPass(PassRegistry &)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, VirtRegMap *VRM, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:289
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:276
void initializeMachineSchedulerPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
MachineFunctionProperties & set(Property P)
void initializeVirtRegMapPass(PassRegistry &)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
void initializeLiveRegMatrixPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=UINT_MAX)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define DEBUG(X)
Definition: Debug.h:100
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
Properties which a MachineFunction may have at a given point in time.