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/LiveVariables.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/MRegisterInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "Support/Debug.h"
24 #include "Support/Statistic.h"
25 #include "Support/STLExtras.h"
26 #include "LiveIntervals.h"
27 #include "PhysRegTracker.h"
28 #include "VirtRegMap.h"
38 Statistic<double> efficiency
39 ("regalloc", "Ratio of intervals processed over total intervals");
41 static unsigned numIterations = 0;
42 static unsigned numIntervals = 0;
44 class RA : public MachineFunctionPass {
47 const TargetMachine* tm_;
48 const MRegisterInfo* mri_;
50 typedef std::vector<LiveInterval*> IntervalPtrs;
51 IntervalPtrs handled_, fixed_, active_, inactive_;
52 typedef std::priority_queue<LiveInterval*,
54 greater_ptr<LiveInterval> > IntervalHeap;
55 IntervalHeap unhandled_;
56 std::auto_ptr<PhysRegTracker> prt_;
57 std::auto_ptr<VirtRegMap> vrm_;
58 std::auto_ptr<Spiller> spiller_;
60 typedef std::vector<float> SpillWeights;
61 SpillWeights spillWeights_;
64 virtual const char* getPassName() const {
65 return "Linear Scan Register Allocator";
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<LiveVariables>();
70 AU.addRequired<LiveIntervals>();
71 MachineFunctionPass::getAnalysisUsage(AU);
74 /// runOnMachineFunction - register allocate the whole function
75 bool runOnMachineFunction(MachineFunction&);
80 /// linearScan - the linear scan algorithm
83 /// initIntervalSets - initializa the four interval sets:
84 /// unhandled, fixed, active and inactive
85 void initIntervalSets(LiveIntervals::Intervals& li);
87 /// processActiveIntervals - expire old intervals and move
88 /// non-overlapping ones to the incative list
89 void processActiveIntervals(LiveInterval* cur);
91 /// processInactiveIntervals - expire old intervals and move
92 /// overlapping ones to the active list
93 void processInactiveIntervals(LiveInterval* cur);
95 /// updateSpillWeights - updates the spill weights of the
96 /// specifed physical register and its weight
97 void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
99 /// assignRegOrStackSlotAtInterval - assign a register if one
100 /// is available, or spill.
101 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
104 /// register handling helpers
107 /// getFreePhysReg - return a free physical register for this
108 /// virtual register interval if we have one, otherwise return
110 unsigned getFreePhysReg(LiveInterval* cur);
112 /// assignVirt2StackSlot - assigns this virtual register to a
113 /// stack slot. returns the stack slot
114 int assignVirt2StackSlot(unsigned virtReg);
116 template <typename ItTy>
117 void printIntervals(const char* const str, ItTy i, ItTy e) const {
118 if (str) std::cerr << str << " intervals:\n";
119 for (; i != e; ++i) {
120 std::cerr << "\t" << **i << " -> ";
121 unsigned reg = (*i)->reg;
122 if (MRegisterInfo::isVirtualRegister(reg)) {
123 reg = vrm_->getPhys(reg);
125 std::cerr << mri_->getName(reg) << '\n';
131 void RA::releaseMemory()
133 while (!unhandled_.empty()) unhandled_.pop();
140 bool RA::runOnMachineFunction(MachineFunction &fn) {
142 tm_ = &fn.getTarget();
143 mri_ = tm_->getRegisterInfo();
144 li_ = &getAnalysis<LiveIntervals>();
145 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
146 vrm_.reset(new VirtRegMap(*mf_));
147 if (!spiller_.get()) spiller_.reset(createSpiller());
149 initIntervalSets(li_->getIntervals());
153 spiller_->runOnMachineFunction(*mf_, *vrm_);
158 void RA::linearScan()
160 // linear scan algorithm
161 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
162 DEBUG(std::cerr << "********** Function: "
163 << mf_->getFunction()->getName() << '\n');
165 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
166 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
167 DEBUG(printIntervals("active", active_.begin(), active_.end()));
168 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
170 while (!unhandled_.empty()) {
171 // pick the interval with the earliest start point
172 LiveInterval* cur = unhandled_.top();
175 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
177 processActiveIntervals(cur);
178 processInactiveIntervals(cur);
180 // if this register is fixed we are done
181 if (MRegisterInfo::isPhysicalRegister(cur->reg)) {
182 prt_->addRegUse(cur->reg);
183 active_.push_back(cur);
184 handled_.push_back(cur);
186 // otherwise we are allocating a virtual register. try to find
187 // a free physical register or spill an interval in order to
188 // assign it one (we could spill the current though).
190 assignRegOrStackSlotAtInterval(cur);
193 DEBUG(printIntervals("active", active_.begin(), active_.end()));
194 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
196 numIntervals += li_->getIntervals().size();
197 efficiency = double(numIterations) / double(numIntervals);
199 // expire any remaining active intervals
200 for (IntervalPtrs::reverse_iterator
201 i = active_.rbegin(); i != active_.rend(); ) {
202 unsigned reg = (*i)->reg;
203 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
204 if (MRegisterInfo::isVirtualRegister(reg))
205 reg = vrm_->getPhys(reg);
206 prt_->delRegUse(reg);
207 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
210 // expire any remaining inactive intervals
211 for (IntervalPtrs::reverse_iterator
212 i = inactive_.rbegin(); i != inactive_.rend(); ) {
213 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
214 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
217 DEBUG(std::cerr << *vrm_);
220 void RA::initIntervalSets(LiveIntervals::Intervals& li)
222 assert(unhandled_.empty() && fixed_.empty() &&
223 active_.empty() && inactive_.empty() &&
224 "interval sets should be empty on initialization");
226 for (LiveIntervals::Intervals::iterator i = li.begin(), e = li.end();
228 unhandled_.push(&*i);
229 if (MRegisterInfo::isPhysicalRegister(i->reg))
230 fixed_.push_back(&*i);
234 void RA::processActiveIntervals(IntervalPtrs::value_type cur)
236 DEBUG(std::cerr << "\tprocessing active intervals:\n");
237 for (IntervalPtrs::reverse_iterator
238 i = active_.rbegin(); i != active_.rend();) {
239 unsigned reg = (*i)->reg;
240 // remove expired intervals
241 if ((*i)->expiredAt(cur->start())) {
242 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
243 if (MRegisterInfo::isVirtualRegister(reg))
244 reg = vrm_->getPhys(reg);
245 prt_->delRegUse(reg);
246 // remove from active
247 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
249 // move inactive intervals to inactive list
250 else if (!(*i)->liveAt(cur->start())) {
251 DEBUG(std::cerr << "\t\tinterval " << **i << " inactive\n");
252 if (MRegisterInfo::isVirtualRegister(reg))
253 reg = vrm_->getPhys(reg);
254 prt_->delRegUse(reg);
256 inactive_.push_back(*i);
257 // remove from active
258 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
266 void RA::processInactiveIntervals(IntervalPtrs::value_type cur)
268 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
269 for (IntervalPtrs::reverse_iterator
270 i = inactive_.rbegin(); i != inactive_.rend();) {
271 unsigned reg = (*i)->reg;
273 // remove expired intervals
274 if ((*i)->expiredAt(cur->start())) {
275 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
276 // remove from inactive
277 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
279 // move re-activated intervals in active list
280 else if ((*i)->liveAt(cur->start())) {
281 DEBUG(std::cerr << "\t\tinterval " << **i << " active\n");
282 if (MRegisterInfo::isVirtualRegister(reg))
283 reg = vrm_->getPhys(reg);
284 prt_->addRegUse(reg);
286 active_.push_back(*i);
287 // remove from inactive
288 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
296 void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
298 spillWeights_[reg] += weight;
299 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
300 spillWeights_[*as] += weight;
303 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
305 DEBUG(std::cerr << "\tallocating current interval: ");
307 PhysRegTracker backupPrt = *prt_;
309 spillWeights_.assign(mri_->getNumRegs(), 0.0);
311 // for each interval in active update spill weights
312 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
314 unsigned reg = (*i)->reg;
315 if (MRegisterInfo::isVirtualRegister(reg))
316 reg = vrm_->getPhys(reg);
317 updateSpillWeights(reg, (*i)->weight);
320 // for every interval in inactive we overlap with, mark the
321 // register as not free and update spill weights
322 for (IntervalPtrs::const_iterator i = inactive_.begin(),
323 e = inactive_.end(); i != e; ++i) {
324 if (cur->overlaps(**i)) {
325 unsigned reg = (*i)->reg;
326 if (MRegisterInfo::isVirtualRegister(reg))
327 reg = vrm_->getPhys(reg);
328 prt_->addRegUse(reg);
329 updateSpillWeights(reg, (*i)->weight);
333 // for every interval in fixed we overlap with,
334 // mark the register as not free and update spill weights
335 for (IntervalPtrs::const_iterator i = fixed_.begin(),
336 e = fixed_.end(); i != e; ++i) {
337 if (cur->overlaps(**i)) {
338 unsigned reg = (*i)->reg;
339 prt_->addRegUse(reg);
340 updateSpillWeights(reg, (*i)->weight);
344 unsigned physReg = getFreePhysReg(cur);
345 // restore the physical register tracker
347 // if we find a free register, we are done: assign this virtual to
348 // the free physical register and add this interval to the active
351 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
352 vrm_->assignVirt2Phys(cur->reg, physReg);
353 prt_->addRegUse(physReg);
354 active_.push_back(cur);
355 handled_.push_back(cur);
358 DEBUG(std::cerr << "no free registers\n");
360 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
362 float minWeight = HUGE_VAL;
364 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
365 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
366 i != rc->allocation_order_end(*mf_); ++i) {
368 if (minWeight > spillWeights_[reg]) {
369 minWeight = spillWeights_[reg];
373 DEBUG(std::cerr << "\t\tregister with min weight: "
374 << mri_->getName(minReg) << " (" << minWeight << ")\n");
376 // if the current has the minimum weight, we need to spill it and
377 // add any added intervals back to unhandled, and restart
379 if (cur->weight <= minWeight) {
380 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
381 int slot = vrm_->assignVirt2StackSlot(cur->reg);
382 std::vector<LiveInterval*> added =
383 li_->addIntervalsForSpills(*cur, *vrm_, slot);
385 return; // Early exit if all spills were folded.
387 // Merge added with unhandled. Note that we know that
388 // addIntervalsForSpills returns intervals sorted by their starting
390 for (unsigned i = 0, e = added.size(); i != e; ++i)
391 unhandled_.push(added[i]);
395 // push the current interval back to unhandled since we are going
396 // to re-run at least this iteration. Since we didn't modify it it
397 // should go back right in the front of the list
398 unhandled_.push(cur);
400 // otherwise we spill all intervals aliasing the register with
401 // minimum weight, rollback to the interval with the earliest
402 // start point and let the linear scan algorithm run again
403 std::vector<LiveInterval*> added;
404 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
405 "did not choose a register to spill?");
406 std::vector<bool> toSpill(mri_->getNumRegs(), false);
407 toSpill[minReg] = true;
408 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
410 unsigned earliestStart = cur->start();
412 std::set<unsigned> spilled;
414 for (IntervalPtrs::iterator
415 i = active_.begin(); i != active_.end(); ++i) {
416 unsigned reg = (*i)->reg;
417 if (MRegisterInfo::isVirtualRegister(reg) &&
418 toSpill[vrm_->getPhys(reg)] &&
419 cur->overlaps(**i)) {
420 DEBUG(std::cerr << "\t\t\tspilling(a): " << **i << '\n');
421 earliestStart = std::min(earliestStart, (*i)->start());
422 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
423 std::vector<LiveInterval*> newIs =
424 li_->addIntervalsForSpills(**i, *vrm_, slot);
425 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
429 for (IntervalPtrs::iterator
430 i = inactive_.begin(); i != inactive_.end(); ++i) {
431 unsigned reg = (*i)->reg;
432 if (MRegisterInfo::isVirtualRegister(reg) &&
433 toSpill[vrm_->getPhys(reg)] &&
434 cur->overlaps(**i)) {
435 DEBUG(std::cerr << "\t\t\tspilling(i): " << **i << '\n');
436 earliestStart = std::min(earliestStart, (*i)->start());
437 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
438 std::vector<LiveInterval*> newIs =
439 li_->addIntervalsForSpills(**i, *vrm_, slot);
440 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
445 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
446 // scan handled in reverse order and undo each one, restoring the
447 // state of unhandled
448 while (!handled_.empty()) {
449 LiveInterval* i = handled_.back();
450 // if this interval starts before t we are done
451 if (i->start() < earliestStart)
453 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
455 IntervalPtrs::iterator it;
456 if ((it = find(active_.begin(), active_.end(), i)) != active_.end()) {
458 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
459 prt_->delRegUse(i->reg);
463 if (!spilled.count(i->reg))
465 prt_->delRegUse(vrm_->getPhys(i->reg));
466 vrm_->clearVirt(i->reg);
469 else if ((it = find(inactive_.begin(), inactive_.end(), i)) != inactive_.end()) {
471 if (MRegisterInfo::isPhysicalRegister(i->reg))
474 if (!spilled.count(i->reg))
476 vrm_->clearVirt(i->reg);
480 if (MRegisterInfo::isVirtualRegister(i->reg))
481 vrm_->clearVirt(i->reg);
486 // scan the rest and undo each interval that expired after t and
487 // insert it in active (the next iteration of the algorithm will
488 // put it in inactive if required)
489 IntervalPtrs::iterator i = handled_.begin(), e = handled_.end();
490 for (; i != e; ++i) {
491 if (!(*i)->expiredAt(earliestStart) && (*i)->expiredAt(cur->start())) {
492 DEBUG(std::cerr << "\t\t\tundo changes for: " << **i << '\n');
493 active_.push_back(*i);
494 if (MRegisterInfo::isPhysicalRegister((*i)->reg))
495 prt_->addRegUse((*i)->reg);
497 prt_->addRegUse(vrm_->getPhys((*i)->reg));
501 std::sort(added.begin(), added.end(), less_ptr<LiveInterval>());
502 // merge added with unhandled
503 for (unsigned i = 0, e = added.size(); i != e; ++i)
504 unhandled_.push(added[i]);
507 unsigned RA::getFreePhysReg(LiveInterval* cur)
509 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
511 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
512 i != rc->allocation_order_end(*mf_); ++i) {
514 if (prt_->isRegAvail(reg))
520 FunctionPass* llvm::createLinearScanRegisterAllocator() {