LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
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 #define DEBUG_TYPE "regalloc"
16 #include "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "LiveDebugVariables.h"
19 #include "RegAllocBase.h"
20 #include "Spiller.h"
35 #include "llvm/Support/Debug.h"
39 #include <cstdlib>
40 #include <queue>
41 
42 using namespace llvm;
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  OwningPtr<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  virtual const char* getPassName() const {
80  return "Basic Register Allocator";
81  }
82 
83  /// RABasic analysis usage.
84  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
85 
86  virtual void releaseMemory();
87 
88  virtual Spiller &spiller() { return *SpillerInstance; }
89 
90  virtual float getPriority(LiveInterval *LI) { return LI->weight; }
91 
92  virtual void enqueue(LiveInterval *LI) {
93  Queue.push(LI);
94  }
95 
96  virtual LiveInterval *dequeue() {
97  if (Queue.empty())
98  return 0;
99  LiveInterval *LI = Queue.top();
100  Queue.pop();
101  return LI;
102  }
103 
104  virtual unsigned selectOrSplit(LiveInterval &VirtReg,
105  SmallVectorImpl<unsigned> &SplitVRegs);
106 
107  /// Perform register allocation.
108  virtual bool runOnMachineFunction(MachineFunction &mf);
109 
110  // Helper for spilling all live virtual registers currently unified under preg
111  // that interfere with the most recently queried lvr. Return true if spilling
112  // was successful, and append any new spilled/split intervals to splitLVRs.
113  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
114  SmallVectorImpl<unsigned> &SplitVRegs);
115 
116  static char ID;
117 };
118 
119 char RABasic::ID = 0;
120 
121 } // end anonymous namespace
122 
123 RABasic::RABasic(): MachineFunctionPass(ID) {
124  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
125  initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
126  initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
127  initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
128  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
129  initializeLiveStacksPass(*PassRegistry::getPassRegistry());
130  initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
131  initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
132  initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
133  initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
134 }
135 
136 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
137  AU.setPreservesCFG();
145  AU.addRequired<LiveStacks>();
146  AU.addPreserved<LiveStacks>();
153  AU.addRequired<VirtRegMap>();
154  AU.addPreserved<VirtRegMap>();
157  MachineFunctionPass::getAnalysisUsage(AU);
158 }
159 
160 void RABasic::releaseMemory() {
161  SpillerInstance.reset(0);
162 }
163 
164 
165 // Spill or split all live virtual registers currently unified under PhysReg
166 // that interfere with VirtReg. The newly spilled or split live intervals are
167 // returned by appending them to SplitVRegs.
168 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
169  SmallVectorImpl<unsigned> &SplitVRegs) {
170  // Record each interference and determine if all are spillable before mutating
171  // either the union or live intervals.
173 
174  // Collect interferences assigned to any alias of the physical register.
175  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
176  LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
178  if (Q.seenUnspillableVReg())
179  return false;
180  for (unsigned i = Q.interferingVRegs().size(); i; --i) {
181  LiveInterval *Intf = Q.interferingVRegs()[i - 1];
182  if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
183  return false;
184  Intfs.push_back(Intf);
185  }
186  }
187  DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
188  " interferences with " << VirtReg << "\n");
189  assert(!Intfs.empty() && "expected interference");
190 
191  // Spill each interfering vreg allocated to PhysReg or an alias.
192  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
193  LiveInterval &Spill = *Intfs[i];
194 
195  // Skip duplicates.
196  if (!VRM->hasPhys(Spill.reg))
197  continue;
198 
199  // Deallocate the interfering vreg by removing it from the union.
200  // A LiveInterval instance may not be in a union during modification!
201  Matrix->unassign(Spill);
202 
203  // Spill the extracted interval.
204  LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
205  spiller().spill(LRE);
206  }
207  return true;
208 }
209 
210 // Driver for the register assignment and splitting heuristics.
211 // Manages iteration over the LiveIntervalUnions.
212 //
213 // This is a minimal implementation of register assignment and splitting that
214 // spills whenever we run out of registers.
215 //
216 // selectOrSplit can only be called once per live virtual register. We then do a
217 // single interference test for each register the correct class until we find an
218 // available register. So, the number of interference tests in the worst case is
219 // |vregs| * |machineregs|. And since the number of interference tests is
220 // minimal, there is no value in caching them outside the scope of
221 // selectOrSplit().
222 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
223  SmallVectorImpl<unsigned> &SplitVRegs) {
224  // Populate a list of physical register spill candidates.
225  SmallVector<unsigned, 8> PhysRegSpillCands;
226 
227  // Check for an available register in this class.
228  AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
229  while (unsigned PhysReg = Order.next()) {
230  // Check for interference in PhysReg
231  switch (Matrix->checkInterference(VirtReg, PhysReg)) {
232  case LiveRegMatrix::IK_Free:
233  // PhysReg is available, allocate it.
234  return PhysReg;
235 
236  case LiveRegMatrix::IK_VirtReg:
237  // Only virtual registers in the way, we may be able to spill them.
238  PhysRegSpillCands.push_back(PhysReg);
239  continue;
240 
241  default:
242  // RegMask or RegUnit interference.
243  continue;
244  }
245  }
246 
247  // Try to spill another interfering reg with less spill weight.
248  for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
249  PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
250  if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
251  continue;
252 
253  assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
254  "Interference after spill.");
255  // Tell the caller to allocate to this newly freed physical register.
256  return *PhysRegI;
257  }
258 
259  // No other spill candidates were found, so spill the current VirtReg.
260  DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
261  if (!VirtReg.isSpillable())
262  return ~0u;
263  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
264  spiller().spill(LRE);
265 
266  // The live virtual register requesting allocation was spilled, so tell
267  // the caller not to allocate anything during this round.
268  return 0;
269 }
270 
271 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
272  DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
273  << "********** Function: "
274  << mf.getName() << '\n');
275 
276  MF = &mf;
277  RegAllocBase::init(getAnalysis<VirtRegMap>(),
278  getAnalysis<LiveIntervals>(),
279  getAnalysis<LiveRegMatrix>());
280 
282  getAnalysis<MachineLoopInfo>(),
283  getAnalysis<MachineBlockFrequencyInfo>());
284 
285  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
286 
287  allocatePhysRegs();
288 
289  // Diagnostic output before rewriting
290  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
291 
292  releaseMemory();
293  return true;
294 }
295 
297 {
298  return new RABasic();
299 }
AnalysisUsage & addPreserved()
const unsigned reg
Definition: LiveInterval.h:532
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.
void initializeLiveDebugVariablesPass(PassRegistry &)
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:543
void initializeMachineLoopInfoPass(PassRegistry &)
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
void initializeRegisterCoalescerPass(PassRegistry &)
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
Live Register Matrix
AnalysisUsage & addRequired()
static RegisterRegAlloc basicRegAlloc("basic","basic register allocator", createBasicRegisterAllocator)
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
AnalysisUsage & addPreservedID(const void *ID)
void initializeMachineDominatorTreePass(PassRegistry &)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:314
void initializeSlotIndexesPass(PassRegistry &)
void initializeLiveStacksPass(PassRegistry &)
void initializeLiveIntervalsPass(PassRegistry &)
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:262
FunctionPass * createBasicRegisterAllocator()
void setPreservesCFG()
Definition: Pass.cpp:249
void initializeMachineSchedulerPass(PassRegistry &)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
void initializeVirtRegMapPass(PassRegistry &)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
void initializeLiveRegMatrixPass(PassRegistry &)
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=UINT_MAX)
#define DEBUG(X)
Definition: Debug.h:97
StringRef getName() const