1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "llvm/Function.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineInstr.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/Target/MRegisterInfo.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "LiveIntervalAnalysis.h"
26 #include "PhysRegTracker.h"
27 #include "VirtRegMap.h"
37 Statistic<double> efficiency
38 ("regalloc", "Ratio of intervals processed over total intervals");
40 static unsigned numIterations = 0;
41 static unsigned numIntervals = 0;
43 class RA : public MachineFunctionPass {
45 const TargetMachine* tm_;
46 const MRegisterInfo* mri_;
48 typedef std::vector<LiveInterval*> IntervalPtrs;
49 IntervalPtrs handled_, fixed_, active_, inactive_;
50 typedef std::priority_queue<LiveInterval*,
52 greater_ptr<LiveInterval> > IntervalHeap;
53 IntervalHeap unhandled_;
54 std::auto_ptr<PhysRegTracker> prt_;
55 std::auto_ptr<VirtRegMap> vrm_;
56 std::auto_ptr<Spiller> spiller_;
58 typedef std::vector<float> SpillWeights;
59 SpillWeights spillWeights_;
62 virtual const char* getPassName() const {
63 return "Linear Scan Register Allocator";
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<LiveIntervals>();
68 MachineFunctionPass::getAnalysisUsage(AU);
71 /// runOnMachineFunction - register allocate the whole function
72 bool runOnMachineFunction(MachineFunction&);
77 /// linearScan - the linear scan algorithm
80 /// initIntervalSets - initializa the four interval sets:
81 /// unhandled, fixed, active and inactive
82 void initIntervalSets();
84 /// processActiveIntervals - expire old intervals and move
85 /// non-overlapping ones to the incative list
86 void processActiveIntervals(LiveInterval* cur);
88 /// processInactiveIntervals - expire old intervals and move
89 /// overlapping ones to the active list
90 void processInactiveIntervals(LiveInterval* cur);
92 /// updateSpillWeights - updates the spill weights of the
93 /// specifed physical register and its weight
94 void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
96 /// assignRegOrStackSlotAtInterval - assign a register if one
97 /// is available, or spill.
98 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
101 /// register handling helpers
104 /// getFreePhysReg - return a free physical register for this
105 /// virtual register interval if we have one, otherwise return
107 unsigned getFreePhysReg(LiveInterval* cur);
109 /// assignVirt2StackSlot - assigns this virtual register to a
110 /// stack slot. returns the stack slot
111 int assignVirt2StackSlot(unsigned virtReg);
113 template <typename ItTy>
114 void printIntervals(const char* const str, ItTy i, ItTy e) const {
115 if (str) std::cerr << str << " intervals:\n";
116 for (; i != e; ++i) {
117 std::cerr << "\t" << **i << " -> ";
118 unsigned reg = (*i)->reg;
119 if (MRegisterInfo::isVirtualRegister(reg)) {
120 reg = vrm_->getPhys(reg);
122 std::cerr << mri_->getName(reg) << '\n';
128 void RA::releaseMemory()
130 while (!unhandled_.empty()) unhandled_.pop();
137 bool RA::runOnMachineFunction(MachineFunction &fn) {
139 tm_ = &fn.getTarget();
140 mri_ = tm_->getRegisterInfo();
141 li_ = &getAnalysis<LiveIntervals>();
142 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
143 vrm_.reset(new VirtRegMap(*mf_));
144 if (!spiller_.get()) spiller_.reset(createSpiller());
150 spiller_->runOnMachineFunction(*mf_, *vrm_);
152 vrm_.reset(); // Free the VirtRegMap
156 void RA::linearScan()
158 // linear scan algorithm
159 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
160 DEBUG(std::cerr << "********** Function: "
161 << mf_->getFunction()->getName() << '\n');
163 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
164 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
165 DEBUG(printIntervals("active", active_.begin(), active_.end()));
166 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
168 while (!unhandled_.empty()) {
169 // pick the interval with the earliest start point
170 LiveInterval* cur = unhandled_.top();
173 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
175 processActiveIntervals(cur);
176 processInactiveIntervals(cur);
178 // if this register is fixed we are done
179 if (MRegisterInfo::isPhysicalRegister(cur->reg)) {
180 prt_->addRegUse(cur->reg);
181 active_.push_back(cur);
182 handled_.push_back(cur);
184 // otherwise we are allocating a virtual register. try to find
185 // a free physical register or spill an interval in order to
186 // assign it one (we could spill the current though).
188 assignRegOrStackSlotAtInterval(cur);
191 DEBUG(printIntervals("active", active_.begin(), active_.end()));
192 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
194 numIntervals += li_->getNumIntervals();
195 efficiency = double(numIterations) / double(numIntervals);
197 // expire any remaining active intervals
198 for (IntervalPtrs::reverse_iterator
199 i = active_.rbegin(); i != active_.rend(); ) {
200 unsigned reg = (*i)->reg;
201 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
202 if (MRegisterInfo::isVirtualRegister(reg))
203 reg = vrm_->getPhys(reg);
204 prt_->delRegUse(reg);
205 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
208 // expire any remaining inactive intervals
209 for (IntervalPtrs::reverse_iterator
210 i = inactive_.rbegin(); i != inactive_.rend(); ) {
211 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
212 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
215 DEBUG(std::cerr << *vrm_);
218 void RA::initIntervalSets()
220 assert(unhandled_.empty() && fixed_.empty() &&
221 active_.empty() && inactive_.empty() &&
222 "interval sets should be empty on initialization");
224 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i){
225 unhandled_.push(&i->second);
226 if (MRegisterInfo::isPhysicalRegister(i->second.reg))
227 fixed_.push_back(&i->second);
231 void RA::processActiveIntervals(IntervalPtrs::value_type cur)
233 DEBUG(std::cerr << "\tprocessing active intervals:\n");
234 IntervalPtrs::iterator ii = active_.begin(), ie = active_.end();
236 LiveInterval* i = *ii;
237 unsigned reg = i->reg;
239 // remove expired intervals
240 if (i->expiredAt(cur->start())) {
241 DEBUG(std::cerr << "\t\tinterval " << *i << " expired\n");
242 if (MRegisterInfo::isVirtualRegister(reg))
243 reg = vrm_->getPhys(reg);
244 prt_->delRegUse(reg);
245 // swap with last element and move end iterator back one position
246 std::iter_swap(ii, --ie);
248 // move inactive intervals to inactive list
249 else if (!i->liveAt(cur->start())) {
250 DEBUG(std::cerr << "\t\tinterval " << *i << " inactive\n");
251 if (MRegisterInfo::isVirtualRegister(reg))
252 reg = vrm_->getPhys(reg);
253 prt_->delRegUse(reg);
255 inactive_.push_back(i);
256 // swap with last element and move end iterator back one postion
257 std::iter_swap(ii, --ie);
263 active_.erase(ie, active_.end());
266 void RA::processInactiveIntervals(IntervalPtrs::value_type cur)
268 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
269 IntervalPtrs::iterator ii = inactive_.begin(), ie = inactive_.end();
271 LiveInterval* i = *ii;
272 unsigned reg = i->reg;
274 // remove expired intervals
275 if (i->expiredAt(cur->start())) {
276 DEBUG(std::cerr << "\t\tinterval " << *i << " expired\n");
277 // swap with last element and move end iterator back one position
278 std::iter_swap(ii, --ie);
280 // move re-activated intervals in active list
281 else if (i->liveAt(cur->start())) {
282 DEBUG(std::cerr << "\t\tinterval " << *i << " active\n");
283 if (MRegisterInfo::isVirtualRegister(reg))
284 reg = vrm_->getPhys(reg);
285 prt_->addRegUse(reg);
287 active_.push_back(i);
288 // swap with last element and move end iterator back one position
289 std::iter_swap(ii, --ie);
295 inactive_.erase(ie, inactive_.end());
298 void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
300 spillWeights_[reg] += weight;
301 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
302 spillWeights_[*as] += weight;
305 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
307 DEBUG(std::cerr << "\tallocating current interval: ");
309 PhysRegTracker backupPrt = *prt_;
311 spillWeights_.assign(mri_->getNumRegs(), 0.0);
313 // for each interval in active update spill weights
314 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
316 unsigned reg = (*i)->reg;
317 if (MRegisterInfo::isVirtualRegister(reg))
318 reg = vrm_->getPhys(reg);
319 updateSpillWeights(reg, (*i)->weight);
322 // for every interval in inactive we overlap with, mark the
323 // register as not free and update spill weights
324 for (IntervalPtrs::const_iterator i = inactive_.begin(),
325 e = inactive_.end(); i != e; ++i) {
326 if (cur->overlaps(**i)) {
327 unsigned reg = (*i)->reg;
328 if (MRegisterInfo::isVirtualRegister(reg))
329 reg = vrm_->getPhys(reg);
330 prt_->addRegUse(reg);
331 updateSpillWeights(reg, (*i)->weight);
335 // for every interval in fixed we overlap with,
336 // mark the register as not free and update spill weights
337 for (IntervalPtrs::const_iterator i = fixed_.begin(),
338 e = fixed_.end(); i != e; ++i) {
339 if (cur->overlaps(**i)) {
340 unsigned reg = (*i)->reg;
341 prt_->addRegUse(reg);
342 updateSpillWeights(reg, (*i)->weight);
346 unsigned physReg = getFreePhysReg(cur);
347 // restore the physical register tracker
349 // if we find a free register, we are done: assign this virtual to
350 // the free physical register and add this interval to the active
353 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
354 vrm_->assignVirt2Phys(cur->reg, physReg);
355 prt_->addRegUse(physReg);
356 active_.push_back(cur);
357 handled_.push_back(cur);
360 DEBUG(std::cerr << "no free registers\n");
362 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
364 float minWeight = HUGE_VAL;
366 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
367 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
368 i != rc->allocation_order_end(*mf_); ++i) {
370 if (minWeight > spillWeights_[reg]) {
371 minWeight = spillWeights_[reg];
375 DEBUG(std::cerr << "\t\tregister with min weight: "
376 << mri_->getName(minReg) << " (" << minWeight << ")\n");
378 // if the current has the minimum weight, we need to spill it and
379 // add any added intervals back to unhandled, and restart
381 if (cur->weight <= minWeight) {
382 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
383 int slot = vrm_->assignVirt2StackSlot(cur->reg);
384 std::vector<LiveInterval*> added =
385 li_->addIntervalsForSpills(*cur, *vrm_, slot);
387 return; // Early exit if all spills were folded.
389 // Merge added with unhandled. Note that we know that
390 // addIntervalsForSpills returns intervals sorted by their starting
392 for (unsigned i = 0, e = added.size(); i != e; ++i)
393 unhandled_.push(added[i]);
397 // push the current interval back to unhandled since we are going
398 // to re-run at least this iteration. Since we didn't modify it it
399 // should go back right in the front of the list
400 unhandled_.push(cur);
402 // otherwise we spill all intervals aliasing the register with
403 // minimum weight, rollback to the interval with the earliest
404 // start point and let the linear scan algorithm run again
405 std::vector<LiveInterval*> added;
406 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
407 "did not choose a register to spill?");
408 std::vector<bool> toSpill(mri_->getNumRegs(), false);
409 // we are going to spill minReg and all its aliases
410 toSpill[minReg] = true;
411 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
414 // the earliest start of a spilled interval indicates up to where
415 // in handled we need to roll back
416 unsigned earliestStart = cur->start();
418 // set of spilled vregs (used later to rollback properly)
419 std::set<unsigned> spilled;
421 // spill live intervals of virtual regs mapped to the physical
422 // register we want to clear (and its aliases). we only spill
423 // those that overlap with the current interval as the rest do not
424 // affect its allocation. we also keep track of the earliest start
425 // of all spilled live intervals since this will mark our rollback
427 for (IntervalPtrs::iterator
428 i = active_.begin(); i != active_.end(); ++i) {
429 unsigned reg = (*i)->reg;
430 if (MRegisterInfo::isVirtualRegister(reg) &&
431 toSpill[vrm_->getPhys(reg)] &&
432 cur->overlaps(**i)) {
433 DEBUG(std::cerr << "\t\t\tspilling(a): " << **i << '\n');
434 earliestStart = std::min(earliestStart, (*i)->start());
435 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
436 std::vector<LiveInterval*> newIs =
437 li_->addIntervalsForSpills(**i, *vrm_, slot);
438 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
442 for (IntervalPtrs::iterator
443 i = inactive_.begin(); i != inactive_.end(); ++i) {
444 unsigned reg = (*i)->reg;
445 if (MRegisterInfo::isVirtualRegister(reg) &&
446 toSpill[vrm_->getPhys(reg)] &&
447 cur->overlaps(**i)) {
448 DEBUG(std::cerr << "\t\t\tspilling(i): " << **i << '\n');
449 earliestStart = std::min(earliestStart, (*i)->start());
450 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
451 std::vector<LiveInterval*> newIs =
452 li_->addIntervalsForSpills(**i, *vrm_, slot);
453 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
458 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
459 // scan handled in reverse order up to the earliaset start of a
460 // spilled live interval and undo each one, restoring the state of
462 while (!handled_.empty()) {
463 LiveInterval* i = handled_.back();
464 // if this interval starts before t we are done
465 if (i->start() < earliestStart)
467 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
469 // when undoing a live interval allocation we must know if it
470 // is active or inactive to properly update the PhysRegTracker
471 // and the VirtRegMap
472 IntervalPtrs::iterator it;
473 if ((it = std::find(active_.begin(), active_.end(), i)) != active_.end()) {
475 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
476 prt_->delRegUse(i->reg);
480 if (!spilled.count(i->reg))
482 prt_->delRegUse(vrm_->getPhys(i->reg));
483 vrm_->clearVirt(i->reg);
486 else if ((it = std::find(inactive_.begin(), inactive_.end(), i)) != inactive_.end()) {
488 if (MRegisterInfo::isPhysicalRegister(i->reg))
491 if (!spilled.count(i->reg))
493 vrm_->clearVirt(i->reg);
497 if (MRegisterInfo::isVirtualRegister(i->reg))
498 vrm_->clearVirt(i->reg);
503 // scan the rest and undo each interval that expired after t and
504 // insert it in active (the next iteration of the algorithm will
505 // put it in inactive if required)
506 IntervalPtrs::iterator i = handled_.begin(), e = handled_.end();
507 for (; i != e; ++i) {
508 if (!(*i)->expiredAt(earliestStart) && (*i)->expiredAt(cur->start())) {
509 DEBUG(std::cerr << "\t\t\tundo changes for: " << **i << '\n');
510 active_.push_back(*i);
511 if (MRegisterInfo::isPhysicalRegister((*i)->reg))
512 prt_->addRegUse((*i)->reg);
514 prt_->addRegUse(vrm_->getPhys((*i)->reg));
518 // merge added with unhandled
519 for (unsigned i = 0, e = added.size(); i != e; ++i)
520 unhandled_.push(added[i]);
523 unsigned RA::getFreePhysReg(LiveInterval* cur)
525 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
526 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
528 unsigned reg = (*i)->reg;
529 if (MRegisterInfo::isVirtualRegister(reg))
530 reg = vrm_->getPhys(reg);
531 ++inactiveCounts[reg];
534 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
536 unsigned freeReg = 0;
537 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
538 i != rc->allocation_order_end(*mf_); ++i) {
540 if (prt_->isRegAvail(reg) &&
541 (!freeReg || inactiveCounts[freeReg] < inactiveCounts[reg]))
547 FunctionPass* llvm::createLinearScanRegisterAllocator() {