blob: a2f9ea274b91383cbdbcfc964eadc9dd58c6388f [file] [log] [blame]
Andrew Trick14e8d712010-10-22 23:09:15 +00001//===-- 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"
Andrew Tricke16eecc2010-10-26 18:34:01 +000016#include "LiveIntervalUnion.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000017#include "RegAllocBase.h"
18#include "RenderMachineFunction.h"
19#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000020#include "VirtRegMap.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000021#include "VirtRegRewriter.h"
22#include "llvm/Function.h"
23#include "llvm/PassAnalysisSupport.h"
24#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000025#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000026#include "llvm/CodeGen/LiveStackAnalysis.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineInstr.h"
29#include "llvm/CodeGen/MachineLoopInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/CodeGen/RegAllocRegistry.h"
33#include "llvm/CodeGen/RegisterCoalescer.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000036#include "llvm/Target/TargetRegisterInfo.h"
Andrew Tricke141a492010-11-08 18:02:08 +000037#include "llvm/Support/Debug.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000040
41#include <vector>
42#include <queue>
43
Andrew Trick14e8d712010-10-22 23:09:15 +000044using namespace llvm;
45
46static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
47 createBasicRegisterAllocator);
48
49namespace {
50
51/// RABasic provides a minimal implementation of the basic register allocation
52/// algorithm. It prioritizes live virtual registers by spill weight and spills
53/// whenever a register is unavailable. This is not practical in production but
54/// provides a useful baseline both for measuring other allocators and comparing
55/// the speed of the basic algorithm against other styles of allocators.
56class RABasic : public MachineFunctionPass, public RegAllocBase
57{
58 // context
59 MachineFunction *mf_;
60 const TargetMachine *tm_;
61 MachineRegisterInfo *mri_;
62
63 // analyses
64 LiveStacks *ls_;
65 RenderMachineFunction *rmf_;
66
67 // state
68 std::auto_ptr<Spiller> spiller_;
69
70public:
71 RABasic();
72
73 /// Return the pass name.
74 virtual const char* getPassName() const {
75 return "Basic Register Allocator";
76 }
77
78 /// RABasic analysis usage.
79 virtual void getAnalysisUsage(AnalysisUsage &au) const;
80
81 virtual void releaseMemory();
82
Andrew Tricke16eecc2010-10-26 18:34:01 +000083 virtual unsigned selectOrSplit(LiveInterval &lvr,
84 SmallVectorImpl<LiveInterval*> &splitLVRs);
Andrew Trick14e8d712010-10-22 23:09:15 +000085
Andrew Tricke141a492010-11-08 18:02:08 +000086 void spillInterferences(unsigned preg,
87 SmallVectorImpl<LiveInterval*> &splitLVRs);
88
Andrew Trick14e8d712010-10-22 23:09:15 +000089 /// Perform register allocation.
90 virtual bool runOnMachineFunction(MachineFunction &mf);
91
92 static char ID;
93};
94
95char RABasic::ID = 0;
96
97} // end anonymous namespace
98
99// We should not need to publish the initializer as long as no other passes
100// require RABasic.
101#if 0 // disable INITIALIZE_PASS
102INITIALIZE_PASS_BEGIN(RABasic, "basic-regalloc",
103 "Basic Register Allocator", false, false)
104INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
105INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
106INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
107INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
108INITIALIZE_PASS_DEPENDENCY(LiveStacks)
109INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
110INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
111#ifndef NDEBUG
112INITIALIZE_PASS_DEPENDENCY(RenderMachineFunction)
113#endif
114INITIALIZE_PASS_END(RABasic, "basic-regalloc",
115 "Basic Register Allocator", false, false)
Andrew Tricke16eecc2010-10-26 18:34:01 +0000116#endif // disable INITIALIZE_PASS
Andrew Trick14e8d712010-10-22 23:09:15 +0000117
118RABasic::RABasic(): MachineFunctionPass(ID) {
119 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
120 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
121 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
122 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
123 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
124 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000125 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000126 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
127 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
128 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
129}
130
131void RABasic::getAnalysisUsage(AnalysisUsage &au) const {
132 au.setPreservesCFG();
133 au.addRequired<LiveIntervals>();
134 au.addPreserved<SlotIndexes>();
135 if (StrongPHIElim)
136 au.addRequiredID(StrongPHIEliminationID);
137 au.addRequiredTransitive<RegisterCoalescer>();
138 au.addRequired<CalculateSpillWeights>();
139 au.addRequired<LiveStacks>();
140 au.addPreserved<LiveStacks>();
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000141 au.addRequiredID(MachineDominatorsID);
142 au.addPreservedID(MachineDominatorsID);
Andrew Trick14e8d712010-10-22 23:09:15 +0000143 au.addRequired<MachineLoopInfo>();
144 au.addPreserved<MachineLoopInfo>();
145 au.addRequired<VirtRegMap>();
146 au.addPreserved<VirtRegMap>();
147 DEBUG(au.addRequired<RenderMachineFunction>());
148 MachineFunctionPass::getAnalysisUsage(au);
149}
150
151void RABasic::releaseMemory() {
152 spiller_.reset(0);
153 RegAllocBase::releaseMemory();
154}
155
156//===----------------------------------------------------------------------===//
157// RegAllocBase Implementation
158//===----------------------------------------------------------------------===//
159
160// Instantiate a LiveIntervalUnion for each physical register.
161void RegAllocBase::LIUArray::init(unsigned nRegs) {
162 array_.reset(new LiveIntervalUnion[nRegs]);
163 nRegs_ = nRegs;
164 for (unsigned pr = 0; pr < nRegs; ++pr) {
165 array_[pr].init(pr);
166 }
167}
168
169void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
170 LiveIntervals &lis) {
171 tri_ = &tri;
172 vrm_ = &vrm;
173 lis_ = &lis;
174 physReg2liu_.init(tri_->getNumRegs());
Andrew Tricke141a492010-11-08 18:02:08 +0000175 // Cache an interferece query for each physical reg
176 queries_.reset(new LiveIntervalUnion::Query[physReg2liu_.numRegs()]);
Andrew Trick14e8d712010-10-22 23:09:15 +0000177}
178
179void RegAllocBase::LIUArray::clear() {
180 nRegs_ = 0;
181 array_.reset(0);
182}
183
184void RegAllocBase::releaseMemory() {
185 physReg2liu_.clear();
186}
187
Andrew Tricke16eecc2010-10-26 18:34:01 +0000188namespace llvm {
189/// This class defines a queue of live virtual registers prioritized by spill
190/// weight. The heaviest vreg is popped first.
191///
192/// Currently, this is trivial wrapper that gives us an opaque type in the
193/// header, but we may later give it a virtual interface for register allocators
194/// to override the priority queue comparator.
195class LiveVirtRegQueue {
196 typedef std::priority_queue
197 <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority> PQ;
198 PQ pq_;
199
200public:
201 // Is the queue empty?
202 bool empty() { return pq_.empty(); }
203
204 // Get the highest priority lvr (top + pop)
205 LiveInterval *get() {
206 LiveInterval *lvr = pq_.top();
207 pq_.pop();
208 return lvr;
209 }
210 // Add this lvr to the queue
211 void push(LiveInterval *lvr) {
212 pq_.push(lvr);
213 }
214};
215} // end namespace llvm
216
217// Visit all the live virtual registers. If they are already assigned to a
218// physical register, unify them with the corresponding LiveIntervalUnion,
219// otherwise push them on the priority queue for later assignment.
220void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &lvrQ) {
221 for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
222 liItr != liEnd; ++liItr) {
223 unsigned reg = liItr->first;
224 LiveInterval &li = *liItr->second;
225 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
226 physReg2liu_[reg].unify(li);
227 }
228 else {
229 lvrQ.push(&li);
230 }
231 }
232}
233
234// Top-level driver to manage the queue of unassigned LiveVirtRegs and call the
235// selectOrSplit implementation.
236void RegAllocBase::allocatePhysRegs() {
237 LiveVirtRegQueue lvrQ;
238 seedLiveVirtRegs(lvrQ);
239 while (!lvrQ.empty()) {
240 LiveInterval *lvr = lvrQ.get();
241 typedef SmallVector<LiveInterval*, 4> LVRVec;
242 LVRVec splitLVRs;
243 unsigned availablePhysReg = selectOrSplit(*lvr, splitLVRs);
244 if (availablePhysReg) {
Andrew Tricke141a492010-11-08 18:02:08 +0000245 DEBUG(dbgs() << "allocating: " << tri_->getName(availablePhysReg) <<
Andrew Trick32d9aeb2010-11-09 19:47:51 +0000246 " " << lvr << '\n');
Andrew Tricke16eecc2010-10-26 18:34:01 +0000247 assert(!vrm_->hasPhys(lvr->reg) && "duplicate vreg in interval unions");
248 vrm_->assignVirt2Phys(lvr->reg, availablePhysReg);
249 physReg2liu_[availablePhysReg].unify(*lvr);
250 }
Andrew Tricke141a492010-11-08 18:02:08 +0000251 for (LVRVec::iterator lvrI = splitLVRs.begin(), lvrEnd = splitLVRs.end();
252 lvrI != lvrEnd; ++lvrI) {
253 DEBUG(dbgs() << "queuing new interval: " << **lvrI << "\n");
254 assert(TargetRegisterInfo::isVirtualRegister((*lvrI)->reg) &&
255 "expect split value in virtual register");
256 lvrQ.push(*lvrI);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000257 }
258 }
259}
260
Andrew Trick14e8d712010-10-22 23:09:15 +0000261// Check if this live virtual reg interferes with a physical register. If not,
262// then check for interference on each register that aliases with the physical
Andrew Tricke141a492010-11-08 18:02:08 +0000263// register. Return the interfering register.
264unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &lvr,
265 unsigned preg) {
266 queries_[preg].init(&lvr, &physReg2liu_[preg]);
267 if (queries_[preg].checkInterference())
268 return preg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000269 for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
Andrew Tricke141a492010-11-08 18:02:08 +0000270 queries_[*asI].init(&lvr, &physReg2liu_[*asI]);
271 if (queries_[*asI].checkInterference())
272 return *asI;
Andrew Trick14e8d712010-10-22 23:09:15 +0000273 }
Andrew Tricke141a492010-11-08 18:02:08 +0000274 return 0;
275}
276
Andrew Trick32d9aeb2010-11-09 19:47:51 +0000277// Spill all live virtual registers currently unified under preg that interfere
278// with lvr.
Andrew Tricke141a492010-11-08 18:02:08 +0000279void RABasic::spillInterferences(unsigned preg,
280 SmallVectorImpl<LiveInterval*> &splitLVRs) {
281 SmallPtrSet<LiveInterval*, 8> spilledLVRs;
282 LiveIntervalUnion::Query &query = queries_[preg];
283 LiveIntervalUnion::InterferenceResult ir = query.firstInterference();
284 assert(query.isInterference(ir) && "expect interference");
285 do {
Andrew Trick32d9aeb2010-11-09 19:47:51 +0000286 LiveInterval *lvr = ir.liuSegPos()->liveVirtReg;
287 if (!spilledLVRs.insert(lvr)) continue;
288 // Spill the previously allocated lvr.
289 SmallVector<LiveInterval*, 1> spillIs; // ignored
290 spiller_->spill(lvr, splitLVRs, spillIs);
Andrew Tricke141a492010-11-08 18:02:08 +0000291 } while (query.nextInterference(ir));
292 for (SmallPtrSetIterator<LiveInterval*> lvrI = spilledLVRs.begin(),
293 lvrEnd = spilledLVRs.end();
294 lvrI != lvrEnd; ++lvrI ) {
295 // Deallocate the interfering lvr by removing it from the preg union.
Andrew Trick32d9aeb2010-11-09 19:47:51 +0000296 physReg2liu_[preg].extract(**lvrI);
Andrew Tricke141a492010-11-08 18:02:08 +0000297 }
298 // After extracting segments, the query's results are invalid.
299 query.clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000300}
301
302//===----------------------------------------------------------------------===//
303// RABasic Implementation
304//===----------------------------------------------------------------------===//
305
306// Driver for the register assignment and splitting heuristics.
307// Manages iteration over the LiveIntervalUnions.
308//
309// Minimal implementation of register assignment and splitting--spills whenever
310// we run out of registers.
311//
312// selectOrSplit can only be called once per live virtual register. We then do a
313// single interference test for each register the correct class until we find an
314// available register. So, the number of interference tests in the worst case is
315// |vregs| * |machineregs|. And since the number of interference tests is
316// minimal, there is no value in caching them.
Andrew Tricke16eecc2010-10-26 18:34:01 +0000317unsigned RABasic::selectOrSplit(LiveInterval &lvr,
318 SmallVectorImpl<LiveInterval*> &splitLVRs) {
Andrew Tricke141a492010-11-08 18:02:08 +0000319 // Accumulate the min spill cost among the interferences, in case we spill.
320 unsigned minSpillReg = 0;
321 unsigned minSpillAlias = 0;
322 float minSpillWeight = lvr.weight;
323
Andrew Trick14e8d712010-10-22 23:09:15 +0000324 // Check for an available reg in this class.
325 const TargetRegisterClass *trc = mri_->getRegClass(lvr.reg);
326 for (TargetRegisterClass::iterator trcI = trc->allocation_order_begin(*mf_),
327 trcEnd = trc->allocation_order_end(*mf_);
328 trcI != trcEnd; ++trcI) {
329 unsigned preg = *trcI;
Andrew Tricke141a492010-11-08 18:02:08 +0000330 unsigned interfReg = checkPhysRegInterference(lvr, preg);
331 if (interfReg == 0) {
Andrew Trick14e8d712010-10-22 23:09:15 +0000332 return preg;
333 }
Andrew Tricke141a492010-11-08 18:02:08 +0000334 LiveIntervalUnion::InterferenceResult interf =
335 queries_[interfReg].firstInterference();
336 float interfWeight = interf.liuSegPos()->liveVirtReg->weight;
337 if (interfWeight < minSpillWeight ) {
338 minSpillReg = interfReg;
339 minSpillAlias = preg;
340 minSpillWeight = interfWeight;
341 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000342 }
Andrew Tricke141a492010-11-08 18:02:08 +0000343 if (minSpillReg == 0) {
344 DEBUG(dbgs() << "spilling: " << lvr << '\n');
345 SmallVector<LiveInterval*, 1> spillIs; // ignored
346 spiller_->spill(&lvr, splitLVRs, spillIs);
347 // The live virtual register requesting to be allocated was spilled. So tell
348 // the caller not to allocate anything for this round.
349 return 0;
350 }
351 // Free the cheapest physical register.
352 spillInterferences(minSpillReg, splitLVRs);
353 // Tell the caller to allocate to this newly freed physical register.
354 assert(minSpillAlias != 0 && "need a free register after spilling");
355 // We just spilled the first register that interferes with minSpillAlias. We
356 // now assume minSpillAlias is free because only one register alias may
357 // interfere at a time. e.g. we ignore predication.
358 unsigned interfReg = checkPhysRegInterference(lvr, minSpillAlias);
359 if (interfReg != 0) {
360 dbgs() << "spilling cannot free " << tri_->getName(minSpillAlias) <<
361 " for " << lvr.reg << " with interference " <<
362 *queries_[interfReg].firstInterference().liuSegPos()->liveVirtReg << "\n";
363 llvm_unreachable("Interference after spill.");
364 }
365 return minSpillAlias;
366}
Andrew Trick14e8d712010-10-22 23:09:15 +0000367
Andrew Tricke141a492010-11-08 18:02:08 +0000368namespace llvm {
369Spiller *createInlineSpiller(MachineFunctionPass &pass,
370 MachineFunction &mf,
371 VirtRegMap &vrm);
Andrew Trick14e8d712010-10-22 23:09:15 +0000372}
373
374bool RABasic::runOnMachineFunction(MachineFunction &mf) {
375 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
376 << "********** Function: "
377 << ((Value*)mf.getFunction())->getName() << '\n');
378
379 mf_ = &mf;
380 tm_ = &mf.getTarget();
381 mri_ = &mf.getRegInfo();
382
383 DEBUG(rmf_ = &getAnalysis<RenderMachineFunction>());
384
385 RegAllocBase::init(*tm_->getRegisterInfo(), getAnalysis<VirtRegMap>(),
386 getAnalysis<LiveIntervals>());
387
Andrew Tricke141a492010-11-08 18:02:08 +0000388 // We may want to force InlineSpiller for this register allocator. For
389 // now we're also experimenting with the standard spiller.
390 //
391 //spiller_.reset(createInlineSpiller(*this, *mf_, *vrm_));
Andrew Trick14e8d712010-10-22 23:09:15 +0000392 spiller_.reset(createSpiller(*this, *mf_, *vrm_));
393
Andrew Tricke16eecc2010-10-26 18:34:01 +0000394 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000395
396 // Diagnostic output before rewriting
397 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm_ << "\n");
398
399 // optional HTML output
400 DEBUG(rmf_->renderMachineFunction("After basic register allocation.", vrm_));
401
402 // Run rewriter
403 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
404 rewriter->runOnMachineFunction(*mf_, *vrm_, lis_);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000405
406 // The pass output is in VirtRegMap. Release all the transient data.
407 releaseMemory();
Andrew Trick14e8d712010-10-22 23:09:15 +0000408
409 return true;
410}
411
412FunctionPass* llvm::createBasicRegisterAllocator()
413{
414 return new RABasic();
415}