f43dc4010d7668b4b7c855a7aa97643072ab2236
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a linear scan register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
29 #include <algorithm>
30 #include <cmath>
31 #include <set>
32 #include <queue>
33
34 using namespace llvm;
35
36 namespace {
37
38     Statistic<double> efficiency
39     ("regalloc", "Ratio of intervals processed over total intervals");
40
41     static unsigned numIterations = 0;
42     static unsigned numIntervals = 0;
43
44     class RA : public MachineFunctionPass {
45     private:
46         MachineFunction* mf_;
47         const TargetMachine* tm_;
48         const MRegisterInfo* mri_;
49         LiveIntervals* li_;
50         typedef std::vector<LiveInterval*> IntervalPtrs;
51         IntervalPtrs handled_, fixed_, active_, inactive_;
52         typedef std::priority_queue<LiveInterval*,
53                                     IntervalPtrs,
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_;
59
60         typedef std::vector<float> SpillWeights;
61         SpillWeights spillWeights_;
62
63     public:
64         virtual const char* getPassName() const {
65             return "Linear Scan Register Allocator";
66         }
67
68         virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69             AU.addRequired<LiveVariables>();
70             AU.addRequired<LiveIntervals>();
71             MachineFunctionPass::getAnalysisUsage(AU);
72         }
73
74         /// runOnMachineFunction - register allocate the whole function
75         bool runOnMachineFunction(MachineFunction&);
76
77         void releaseMemory();
78
79     private:
80         /// linearScan - the linear scan algorithm
81         void linearScan();
82
83         /// initIntervalSets - initializa the four interval sets:
84         /// unhandled, fixed, active and inactive
85         void initIntervalSets(LiveIntervals::Intervals& li);
86
87         /// processActiveIntervals - expire old intervals and move
88         /// non-overlapping ones to the incative list
89         void processActiveIntervals(LiveInterval* cur);
90
91         /// processInactiveIntervals - expire old intervals and move
92         /// overlapping ones to the active list
93         void processInactiveIntervals(LiveInterval* cur);
94
95         /// updateSpillWeights - updates the spill weights of the
96         /// specifed physical register and its weight
97         void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
98
99         /// assignRegOrStackSlotAtInterval - assign a register if one
100         /// is available, or spill.
101         void assignRegOrStackSlotAtInterval(LiveInterval* cur);
102
103         ///
104         /// register handling helpers
105         ///
106
107         /// getFreePhysReg - return a free physical register for this
108         /// virtual register interval if we have one, otherwise return
109         /// 0
110         unsigned getFreePhysReg(LiveInterval* cur);
111
112         /// assignVirt2StackSlot - assigns this virtual register to a
113         /// stack slot. returns the stack slot
114         int assignVirt2StackSlot(unsigned virtReg);
115
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);
124                 }
125                 std::cerr << mri_->getName(reg) << '\n';
126             }
127         }
128     };
129 }
130
131 void RA::releaseMemory()
132 {
133     while (!unhandled_.empty()) unhandled_.pop();
134     fixed_.clear();
135     active_.clear();
136     inactive_.clear();
137     handled_.clear();
138 }
139
140 bool RA::runOnMachineFunction(MachineFunction &fn) {
141     mf_ = &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());
148
149     initIntervalSets(li_->getIntervals());
150
151     linearScan();
152
153     spiller_->runOnMachineFunction(*mf_, *vrm_);
154
155     return true;
156 }
157
158 void RA::linearScan()
159 {
160     // linear scan algorithm
161     DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
162     DEBUG(std::cerr << "********** Function: "
163           << mf_->getFunction()->getName() << '\n');
164
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()));
169
170     while (!unhandled_.empty()) {
171         // pick the interval with the earliest start point
172         LiveInterval* cur = unhandled_.top();
173         unhandled_.pop();
174         ++numIterations;
175         DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
176
177         processActiveIntervals(cur);
178         processInactiveIntervals(cur);
179
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);
185         }
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).
189         else {
190             assignRegOrStackSlotAtInterval(cur);
191         }
192
193         DEBUG(printIntervals("active", active_.begin(), active_.end()));
194         DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
195     }
196     numIntervals += li_->getIntervals().size();
197     efficiency = double(numIterations) / double(numIntervals);
198
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));
208     }
209
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));
215     }
216
217     DEBUG(std::cerr << *vrm_);
218 }
219
220 void RA::initIntervalSets(LiveIntervals::Intervals& li)
221 {
222     assert(unhandled_.empty() && fixed_.empty() &&
223            active_.empty() && inactive_.empty() &&
224            "interval sets should be empty on initialization");
225
226     for (LiveIntervals::Intervals::iterator i = li.begin(), e = li.end();
227          i != e; ++i) {
228         unhandled_.push(&*i);
229         if (MRegisterInfo::isPhysicalRegister(i->reg))
230             fixed_.push_back(&*i);
231     }
232 }
233
234 void RA::processActiveIntervals(IntervalPtrs::value_type cur)
235 {
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));
248         }
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);
255             // add to inactive
256             inactive_.push_back(*i);
257             // remove from active
258             i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
259         }
260         else {
261             ++i;
262         }
263     }
264 }
265
266 void RA::processInactiveIntervals(IntervalPtrs::value_type cur)
267 {
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;
272
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));
278         }
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);
285             // add to active
286             active_.push_back(*i);
287             // remove from inactive
288             i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
289         }
290         else {
291             ++i;
292         }
293     }
294 }
295
296 void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
297 {
298     spillWeights_[reg] += weight;
299     for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
300         spillWeights_[*as] += weight;
301 }
302
303 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
304 {
305     DEBUG(std::cerr << "\tallocating current interval: ");
306
307     PhysRegTracker backupPrt = *prt_;
308
309     spillWeights_.assign(mri_->getNumRegs(), 0.0);
310
311     // for each interval in active update spill weights
312     for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
313          i != e; ++i) {
314         unsigned reg = (*i)->reg;
315         if (MRegisterInfo::isVirtualRegister(reg))
316             reg = vrm_->getPhys(reg);
317         updateSpillWeights(reg, (*i)->weight);
318     }
319
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);
330         }
331     }
332
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);
341         }
342     }
343
344     unsigned physReg = getFreePhysReg(cur);
345     // restore the physical register tracker
346     *prt_ = backupPrt;
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
349     // list.
350     if (physReg) {
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);
356         return;
357     }
358     DEBUG(std::cerr << "no free registers\n");
359
360     DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
361
362     float minWeight = HUGE_VAL;
363     unsigned minReg = 0;
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) {
367         unsigned reg = *i;
368         if (minWeight > spillWeights_[reg]) {
369             minWeight = spillWeights_[reg];
370             minReg = reg;
371         }
372     }
373     DEBUG(std::cerr << "\t\tregister with min weight: "
374           << mri_->getName(minReg) << " (" << minWeight << ")\n");
375
376     // if the current has the minimum weight, we need to spill it and
377     // add any added intervals back to unhandled, and restart
378     // linearscan.
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);
384         if (added.empty())
385           return;  // Early exit if all spills were folded.
386
387         // Merge added with unhandled.  Note that we know that 
388         // addIntervalsForSpills returns intervals sorted by their starting
389         // point.
390         for (unsigned i = 0, e = added.size(); i != e; ++i)
391             unhandled_.push(added[i]);
392         return;
393     }
394
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);
399
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)
409         toSpill[*as] = true;
410     unsigned earliestStart = cur->start();
411
412     std::set<unsigned> spilled;
413
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));
426             spilled.insert(reg);
427         }
428     }
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));
441             spilled.insert(reg);
442         }
443     }
444
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)
452             break;
453         DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
454         handled_.pop_back();
455         IntervalPtrs::iterator it;
456         if ((it = find(active_.begin(), active_.end(), i)) != active_.end()) {
457             active_.erase(it);
458             if (MRegisterInfo::isPhysicalRegister(i->reg)) {
459                 prt_->delRegUse(i->reg);
460                 unhandled_.push(i);
461             }
462             else {
463                 if (!spilled.count(i->reg))
464                     unhandled_.push(i);
465                 prt_->delRegUse(vrm_->getPhys(i->reg));
466                 vrm_->clearVirt(i->reg);
467             }
468         }
469         else if ((it = find(inactive_.begin(), inactive_.end(), i)) != inactive_.end()) {
470             inactive_.erase(it);
471             if (MRegisterInfo::isPhysicalRegister(i->reg))
472                 unhandled_.push(i);
473             else {
474                 if (!spilled.count(i->reg))
475                     unhandled_.push(i);
476                 vrm_->clearVirt(i->reg);
477             }
478         }
479         else {
480             if (MRegisterInfo::isVirtualRegister(i->reg))
481                 vrm_->clearVirt(i->reg);
482             unhandled_.push(i);
483         }
484     }
485
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);
496             else
497                 prt_->addRegUse(vrm_->getPhys((*i)->reg));
498         }
499     }
500
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]);
505 }
506
507 unsigned RA::getFreePhysReg(LiveInterval* cur)
508 {
509     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
510
511     for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
512          i != rc->allocation_order_end(*mf_); ++i) {
513         unsigned reg = *i;
514         if (prt_->isRegAvail(reg))
515             return reg;
516     }
517     return 0;
518 }
519
520 FunctionPass* llvm::createLinearScanRegisterAllocator() {
521     return new RA();
522 }