blob: c63a0c18aec2be55e7e857d5ad44301010a37e63 [file] [log] [blame]
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +00001//===-- 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//===----------------------------------------------------------------------===//
Alkis Evlogimenos1dd872c2004-02-24 08:58:30 +000013
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000014#define DEBUG_TYPE "regalloc"
15#include "llvm/Function.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000016#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"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000021#include "llvm/Target/TargetMachine.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000022#include "llvm/Support/Debug.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/STLExtras.h"
Chris Lattner85638332004-07-23 17:56:30 +000025#include "LiveIntervalAnalysis.h"
Alkis Evlogimenos14108592004-02-23 00:53:31 +000026#include "PhysRegTracker.h"
Alkis Evlogimenosc794a902004-02-23 23:08:11 +000027#include "VirtRegMap.h"
Alkis Evlogimenos2c5ddd22004-02-15 10:24:21 +000028#include <algorithm>
Alkis Evlogimenos2a54b5d2004-05-08 03:50:03 +000029#include <cmath>
Alkis Evlogimenosa5268e82004-05-30 07:24:39 +000030#include <set>
Alkis Evlogimenos1a876fa2004-07-22 08:14:44 +000031#include <queue>
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000032using namespace llvm;
33
34namespace {
Alkis Evlogimenos8f3cc032004-07-04 07:59:06 +000035
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000036 Statistic<double> efficiency
37 ("regalloc", "Ratio of intervals processed over total intervals");
Chris Lattner850852c2004-11-18 03:49:30 +000038 Statistic<> NumBacktracks("regalloc", "Number of times we had to backtrack");
Alkis Evlogimenos8f3cc032004-07-04 07:59:06 +000039
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000040 static unsigned numIterations = 0;
41 static unsigned numIntervals = 0;
Alkis Evlogimenos21b3a5b2004-07-04 17:23:35 +000042
Chris Lattnera1f77792004-11-18 02:42:27 +000043 struct RA : public MachineFunctionPass {
44 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
45 typedef std::vector<IntervalPtr> IntervalPtrs;
46 private:
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000047 MachineFunction* mf_;
48 const TargetMachine* tm_;
49 const MRegisterInfo* mri_;
50 LiveIntervals* li_;
Chris Lattnera1f77792004-11-18 02:42:27 +000051
52 /// handled_ - Intervals are added to the handled_ set in the order of their
53 /// start value. This is uses for backtracking.
54 std::vector<LiveInterval*> handled_;
55
56 /// fixed_ - Intervals that correspond to machine registers.
57 ///
58 IntervalPtrs fixed_;
59
60 /// active_ - Intervals that are currently being processed, and which have a
61 /// live range active for the current point.
62 IntervalPtrs active_;
63
64 /// inactive_ - Intervals that are currently being processed, but which have
65 /// a hold at the current point.
66 IntervalPtrs inactive_;
67
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000068 typedef std::priority_queue<LiveInterval*,
Chris Lattnera1f77792004-11-18 02:42:27 +000069 std::vector<LiveInterval*>,
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000070 greater_ptr<LiveInterval> > IntervalHeap;
71 IntervalHeap unhandled_;
72 std::auto_ptr<PhysRegTracker> prt_;
73 std::auto_ptr<VirtRegMap> vrm_;
74 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000075
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000076 typedef std::vector<float> SpillWeights;
77 SpillWeights spillWeights_;
Alkis Evlogimenose82a7072004-02-06 18:08:18 +000078
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000079 public:
80 virtual const char* getPassName() const {
81 return "Linear Scan Register Allocator";
82 }
83
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000085 AU.addRequired<LiveIntervals>();
86 MachineFunctionPass::getAnalysisUsage(AU);
87 }
88
89 /// runOnMachineFunction - register allocate the whole function
90 bool runOnMachineFunction(MachineFunction&);
91
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000092 private:
93 /// linearScan - the linear scan algorithm
94 void linearScan();
95
Chris Lattnera1f77792004-11-18 02:42:27 +000096 /// initIntervalSets - initialize the interval sets.
97 ///
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000098 void initIntervalSets();
99
Chris Lattnera1f77792004-11-18 02:42:27 +0000100 /// processActiveIntervals - expire old intervals and move non-overlapping
101 /// ones to the inactive list.
102 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000103
Chris Lattnera1f77792004-11-18 02:42:27 +0000104 /// processInactiveIntervals - expire old intervals and move overlapping
105 /// ones to the active list.
106 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000107
108 /// updateSpillWeights - updates the spill weights of the
Chris Lattnera1f77792004-11-18 02:42:27 +0000109 /// specifed physical register and its weight.
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000110 void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
111
112 /// assignRegOrStackSlotAtInterval - assign a register if one
113 /// is available, or spill.
114 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
115
116 ///
117 /// register handling helpers
118 ///
119
Chris Lattnera1f77792004-11-18 02:42:27 +0000120 /// getFreePhysReg - return a free physical register for this virtual
121 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000122 unsigned getFreePhysReg(LiveInterval* cur);
123
124 /// assignVirt2StackSlot - assigns this virtual register to a
125 /// stack slot. returns the stack slot
126 int assignVirt2StackSlot(unsigned virtReg);
127
128 template <typename ItTy>
129 void printIntervals(const char* const str, ItTy i, ItTy e) const {
130 if (str) std::cerr << str << " intervals:\n";
131 for (; i != e; ++i) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000132 std::cerr << "\t" << *i->first << " -> ";
133 unsigned reg = i->first->reg;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000134 if (MRegisterInfo::isVirtualRegister(reg)) {
135 reg = vrm_->getPhys(reg);
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000136 }
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000137 std::cerr << mri_->getName(reg) << '\n';
138 }
139 }
140 };
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000141}
142
143bool RA::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000144 mf_ = &fn;
145 tm_ = &fn.getTarget();
146 mri_ = tm_->getRegisterInfo();
147 li_ = &getAnalysis<LiveIntervals>();
Chris Lattner08ec6032004-11-18 04:33:31 +0000148
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000149 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
150 vrm_.reset(new VirtRegMap(*mf_));
151 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000152
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000153 initIntervalSets();
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000154
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000155 linearScan();
Alkis Evlogimenos1dd872c2004-02-24 08:58:30 +0000156
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000157 spiller_->runOnMachineFunction(*mf_, *vrm_);
Alkis Evlogimenos1dd872c2004-02-24 08:58:30 +0000158
Chris Lattnerddd52292004-09-30 02:02:33 +0000159 vrm_.reset(); // Free the VirtRegMap
Chris Lattnera1f77792004-11-18 02:42:27 +0000160
161
162 while (!unhandled_.empty()) unhandled_.pop();
163 fixed_.clear();
164 active_.clear();
165 inactive_.clear();
166 handled_.clear();
167
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000168 return true;
Alkis Evlogimenos1dd872c2004-02-24 08:58:30 +0000169}
170
171void RA::linearScan()
172{
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000173 // linear scan algorithm
174 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
175 DEBUG(std::cerr << "********** Function: "
176 << mf_->getFunction()->getName() << '\n');
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000177
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000178 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
179 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
180 DEBUG(printIntervals("active", active_.begin(), active_.end()));
181 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
182
183 while (!unhandled_.empty()) {
184 // pick the interval with the earliest start point
185 LiveInterval* cur = unhandled_.top();
186 unhandled_.pop();
187 ++numIterations;
188 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
189
Chris Lattnera1f77792004-11-18 02:42:27 +0000190 processActiveIntervals(cur->beginNumber());
191 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000192
193 // if this register is fixed we are done
194 if (MRegisterInfo::isPhysicalRegister(cur->reg)) {
195 prt_->addRegUse(cur->reg);
Chris Lattnera1f77792004-11-18 02:42:27 +0000196 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000197 handled_.push_back(cur);
Chris Lattnera1f77792004-11-18 02:42:27 +0000198 } else {
199 // otherwise we are allocating a virtual register. try to find a free
Chris Lattner850852c2004-11-18 03:49:30 +0000200 // physical register or spill an interval (possibly this one) in order to
201 // assign it one.
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000202 assignRegOrStackSlotAtInterval(cur);
203 }
204
Alkis Evlogimenos76eca062004-02-20 06:15:40 +0000205 DEBUG(printIntervals("active", active_.begin(), active_.end()));
206 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000207 }
208 numIntervals += li_->getNumIntervals();
209 efficiency = double(numIterations) / double(numIntervals);
Alkis Evlogimenosae5b3d42004-01-07 09:20:58 +0000210
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000211 // expire any remaining active intervals
212 for (IntervalPtrs::reverse_iterator
213 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000214 unsigned reg = i->first->reg;
215 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000216 if (MRegisterInfo::isVirtualRegister(reg))
217 reg = vrm_->getPhys(reg);
218 prt_->delRegUse(reg);
219 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
220 }
Alkis Evlogimenosae5b3d42004-01-07 09:20:58 +0000221
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000222 // expire any remaining inactive intervals
223 for (IntervalPtrs::reverse_iterator
224 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000225 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000226 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
227 }
Alkis Evlogimenos65bc9902004-01-13 20:42:08 +0000228
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000229 DEBUG(std::cerr << *vrm_);
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000230}
231
Chris Lattnera1f77792004-11-18 02:42:27 +0000232/// initIntervalSets - initialize the interval sets.
233///
Chris Lattnerc51866a2004-07-24 03:32:06 +0000234void RA::initIntervalSets()
Alkis Evlogimenosae5b3d42004-01-07 09:20:58 +0000235{
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000236 assert(unhandled_.empty() && fixed_.empty() &&
237 active_.empty() && inactive_.empty() &&
238 "interval sets should be empty on initialization");
Alkis Evlogimenosae5b3d42004-01-07 09:20:58 +0000239
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000240 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i){
241 unhandled_.push(&i->second);
242 if (MRegisterInfo::isPhysicalRegister(i->second.reg))
Chris Lattnera1f77792004-11-18 02:42:27 +0000243 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000244 }
Alkis Evlogimenosae5b3d42004-01-07 09:20:58 +0000245}
246
Chris Lattnera1f77792004-11-18 02:42:27 +0000247/// processActiveIntervals - expire old intervals and move non-overlapping ones
248/// to the inactive list.
249void RA::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000250{
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000251 DEBUG(std::cerr << "\tprocessing active intervals:\n");
Chris Lattnera51f5ee2004-11-18 01:29:39 +0000252
Chris Lattnera1f77792004-11-18 02:42:27 +0000253 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
254 LiveInterval *Interval = active_[i].first;
255 LiveInterval::iterator IntervalPos = active_[i].second;
256 unsigned reg = Interval->reg;
Alkis Evlogimenosfae8f6a2004-09-01 22:52:29 +0000257
Chris Lattnera1f77792004-11-18 02:42:27 +0000258 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
259
260 if (IntervalPos == Interval->end()) { // Remove expired intervals.
261 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000262 if (MRegisterInfo::isVirtualRegister(reg))
263 reg = vrm_->getPhys(reg);
264 prt_->delRegUse(reg);
Chris Lattnera1f77792004-11-18 02:42:27 +0000265
266 // Pop off the end of the list.
267 active_[i] = active_.back();
268 active_.pop_back();
269 --i; --e;
270
271 } else if (IntervalPos->start > CurPoint) {
272 // Move inactive intervals to inactive list.
273 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000274 if (MRegisterInfo::isVirtualRegister(reg))
275 reg = vrm_->getPhys(reg);
276 prt_->delRegUse(reg);
Chris Lattnera1f77792004-11-18 02:42:27 +0000277 // add to inactive.
278 inactive_.push_back(std::make_pair(Interval, IntervalPos));
279
280 // Pop off the end of the list.
281 active_[i] = active_.back();
282 active_.pop_back();
283 --i; --e;
284 } else {
285 // Otherwise, just update the iterator position.
286 active_[i].second = IntervalPos;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000287 }
288 }
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000289}
290
Chris Lattnera1f77792004-11-18 02:42:27 +0000291/// processInactiveIntervals - expire old intervals and move overlapping
292/// ones to the active list.
293void RA::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000294{
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000295 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
Chris Lattner49ff5f02004-11-18 04:13:02 +0000296
Chris Lattnera1f77792004-11-18 02:42:27 +0000297 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
298 LiveInterval *Interval = inactive_[i].first;
299 LiveInterval::iterator IntervalPos = inactive_[i].second;
300 unsigned reg = Interval->reg;
Chris Lattnera51f5ee2004-11-18 01:29:39 +0000301
Chris Lattnera1f77792004-11-18 02:42:27 +0000302 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
303
304 if (IntervalPos == Interval->end()) { // remove expired intervals.
305 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000306
Chris Lattnera1f77792004-11-18 02:42:27 +0000307 // Pop off the end of the list.
308 inactive_[i] = inactive_.back();
309 inactive_.pop_back();
310 --i; --e;
311 } else if (IntervalPos->start <= CurPoint) {
312 // move re-activated intervals in active list
313 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000314 if (MRegisterInfo::isVirtualRegister(reg))
315 reg = vrm_->getPhys(reg);
316 prt_->addRegUse(reg);
317 // add to active
Chris Lattnera1f77792004-11-18 02:42:27 +0000318 active_.push_back(std::make_pair(Interval, IntervalPos));
319
320 // Pop off the end of the list.
321 inactive_[i] = inactive_.back();
322 inactive_.pop_back();
323 --i; --e;
324 } else {
325 // Otherwise, just update the iterator position.
326 inactive_[i].second = IntervalPos;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000327 }
328 }
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000329}
330
Chris Lattnera1f77792004-11-18 02:42:27 +0000331/// updateSpillWeights - updates the spill weights of the specifed physical
332/// register and its weight.
Alkis Evlogimenose82a7072004-02-06 18:08:18 +0000333void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
334{
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000335 spillWeights_[reg] += weight;
336 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
337 spillWeights_[*as] += weight;
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000338}
339
Chris Lattnera1f77792004-11-18 02:42:27 +0000340static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
341 LiveInterval *LI) {
342 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
343 if (I->first == LI) return I;
344 return IP.end();
345}
346
Chris Lattner850852c2004-11-18 03:49:30 +0000347static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
348 for (unsigned i = 0, e = V.size(); i != e; ++i) {
349 RA::IntervalPtr &IP = V[i];
350 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
351 IP.second, Point);
352 if (I != IP.first->begin()) --I;
353 IP.second = I;
354 }
355}
Chris Lattnera1f77792004-11-18 02:42:27 +0000356
357
358/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
359/// spill.
Alkis Evlogimenos1a876fa2004-07-22 08:14:44 +0000360void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000361{
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000362 DEBUG(std::cerr << "\tallocating current interval: ");
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000363
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000364 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000365
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000366 spillWeights_.assign(mri_->getNumRegs(), 0.0);
Alkis Evlogimenose82a7072004-02-06 18:08:18 +0000367
Chris Lattner49ff5f02004-11-18 04:13:02 +0000368 unsigned StartPosition = cur->beginNumber();
369
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000370 // for each interval in active update spill weights
371 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
372 i != e; ++i) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000373 unsigned reg = i->first->reg;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000374 if (MRegisterInfo::isVirtualRegister(reg))
375 reg = vrm_->getPhys(reg);
Chris Lattnera1f77792004-11-18 02:42:27 +0000376 updateSpillWeights(reg, i->first->weight);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000377 }
378
379 // for every interval in inactive we overlap with, mark the
380 // register as not free and update spill weights
381 for (IntervalPtrs::const_iterator i = inactive_.begin(),
382 e = inactive_.end(); i != e; ++i) {
Chris Lattner850852c2004-11-18 03:49:30 +0000383 if (cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000384 unsigned reg = i->first->reg;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000385 if (MRegisterInfo::isVirtualRegister(reg))
386 reg = vrm_->getPhys(reg);
387 prt_->addRegUse(reg);
Chris Lattnera1f77792004-11-18 02:42:27 +0000388 updateSpillWeights(reg, i->first->weight);
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000389 }
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000390 }
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000391
Chris Lattner850852c2004-11-18 03:49:30 +0000392 // For every interval in fixed we overlap with, mark the register as not free
393 // and update spill weights.
Chris Lattner49ff5f02004-11-18 04:13:02 +0000394 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
395 IntervalPtr &IP = fixed_[i];
396 LiveInterval *I = IP.first;
Chris Lattner08ec6032004-11-18 04:33:31 +0000397 if (I->endNumber() > StartPosition) {
398 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
399 IP.second = II;
400 if (II != I->begin() && II->start > StartPosition)
401 --II;
402 if (cur->overlapsFrom(*I, II)) {
403 unsigned reg = I->reg;
404 prt_->addRegUse(reg);
405 updateSpillWeights(reg, I->weight);
406 }
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000407 }
Chris Lattner49ff5f02004-11-18 04:13:02 +0000408 }
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000409
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000410 unsigned physReg = getFreePhysReg(cur);
411 // restore the physical register tracker
412 *prt_ = backupPrt;
413 // if we find a free register, we are done: assign this virtual to
414 // the free physical register and add this interval to the active
415 // list.
416 if (physReg) {
417 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
418 vrm_->assignVirt2Phys(cur->reg, physReg);
419 prt_->addRegUse(physReg);
Chris Lattnera1f77792004-11-18 02:42:27 +0000420 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000421 handled_.push_back(cur);
422 return;
423 }
424 DEBUG(std::cerr << "no free registers\n");
425
426 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
427
428 float minWeight = HUGE_VAL;
429 unsigned minReg = 0;
430 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
431 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
432 i != rc->allocation_order_end(*mf_); ++i) {
433 unsigned reg = *i;
434 if (minWeight > spillWeights_[reg]) {
435 minWeight = spillWeights_[reg];
436 minReg = reg;
Alkis Evlogimenos7d7d7e82003-12-23 18:00:33 +0000437 }
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000438 }
439 DEBUG(std::cerr << "\t\tregister with min weight: "
440 << mri_->getName(minReg) << " (" << minWeight << ")\n");
Alkis Evlogimenos7d7d7e82003-12-23 18:00:33 +0000441
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000442 // if the current has the minimum weight, we need to spill it and
443 // add any added intervals back to unhandled, and restart
444 // linearscan.
445 if (cur->weight <= minWeight) {
446 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
447 int slot = vrm_->assignVirt2StackSlot(cur->reg);
448 std::vector<LiveInterval*> added =
449 li_->addIntervalsForSpills(*cur, *vrm_, slot);
450 if (added.empty())
451 return; // Early exit if all spills were folded.
Alkis Evlogimenose82a7072004-02-06 18:08:18 +0000452
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000453 // Merge added with unhandled. Note that we know that
454 // addIntervalsForSpills returns intervals sorted by their starting
455 // point.
Alkis Evlogimenos1a876fa2004-07-22 08:14:44 +0000456 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000457 unhandled_.push(added[i]);
458 return;
459 }
460
Chris Lattner850852c2004-11-18 03:49:30 +0000461 ++NumBacktracks;
462
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000463 // push the current interval back to unhandled since we are going
464 // to re-run at least this iteration. Since we didn't modify it it
465 // should go back right in the front of the list
466 unhandled_.push(cur);
467
468 // otherwise we spill all intervals aliasing the register with
469 // minimum weight, rollback to the interval with the earliest
470 // start point and let the linear scan algorithm run again
471 std::vector<LiveInterval*> added;
472 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
473 "did not choose a register to spill?");
474 std::vector<bool> toSpill(mri_->getNumRegs(), false);
Chris Lattner850852c2004-11-18 03:49:30 +0000475
476 // We are going to spill minReg and all its aliases.
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000477 toSpill[minReg] = true;
478 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
479 toSpill[*as] = true;
480
481 // the earliest start of a spilled interval indicates up to where
482 // in handled we need to roll back
Chris Lattnera51f5ee2004-11-18 01:29:39 +0000483 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000484
485 // set of spilled vregs (used later to rollback properly)
486 std::set<unsigned> spilled;
487
Chris Lattner850852c2004-11-18 03:49:30 +0000488 // spill live intervals of virtual regs mapped to the physical register we
489 // want to clear (and its aliases). We only spill those that overlap with the
490 // current interval as the rest do not affect its allocation. we also keep
491 // track of the earliest start of all spilled live intervals since this will
492 // mark our rollback point.
493 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000494 unsigned reg = i->first->reg;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000495 if (MRegisterInfo::isVirtualRegister(reg) &&
496 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner850852c2004-11-18 03:49:30 +0000497 cur->overlapsFrom(*i->first, i->second)) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000498 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
499 earliestStart = std::min(earliestStart, i->first->beginNumber());
500 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000501 std::vector<LiveInterval*> newIs =
Chris Lattnera1f77792004-11-18 02:42:27 +0000502 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000503 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
504 spilled.insert(reg);
505 }
506 }
Chris Lattner850852c2004-11-18 03:49:30 +0000507 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnera1f77792004-11-18 02:42:27 +0000508 unsigned reg = i->first->reg;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000509 if (MRegisterInfo::isVirtualRegister(reg) &&
510 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner850852c2004-11-18 03:49:30 +0000511 cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000512 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
513 earliestStart = std::min(earliestStart, i->first->beginNumber());
514 int slot = vrm_->assignVirt2StackSlot(reg);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000515 std::vector<LiveInterval*> newIs =
Chris Lattnera1f77792004-11-18 02:42:27 +0000516 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000517 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
518 spilled.insert(reg);
519 }
520 }
521
522 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
Chris Lattnera1f77792004-11-18 02:42:27 +0000523
524 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000525 // spilled live interval and undo each one, restoring the state of
Chris Lattnera1f77792004-11-18 02:42:27 +0000526 // unhandled.
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000527 while (!handled_.empty()) {
528 LiveInterval* i = handled_.back();
Chris Lattnera1f77792004-11-18 02:42:27 +0000529 // If this interval starts before t we are done.
Chris Lattnera51f5ee2004-11-18 01:29:39 +0000530 if (i->beginNumber() < earliestStart)
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000531 break;
532 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
533 handled_.pop_back();
Chris Lattnera1f77792004-11-18 02:42:27 +0000534
535 // When undoing a live interval allocation we must know if it is active or
536 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000537 IntervalPtrs::iterator it;
Chris Lattnera1f77792004-11-18 02:42:27 +0000538 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000539 active_.erase(it);
540 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
541 prt_->delRegUse(i->reg);
542 unhandled_.push(i);
Chris Lattnera1f77792004-11-18 02:42:27 +0000543 } else {
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000544 if (!spilled.count(i->reg))
545 unhandled_.push(i);
546 prt_->delRegUse(vrm_->getPhys(i->reg));
547 vrm_->clearVirt(i->reg);
548 }
Chris Lattnera1f77792004-11-18 02:42:27 +0000549 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000550 inactive_.erase(it);
551 if (MRegisterInfo::isPhysicalRegister(i->reg))
552 unhandled_.push(i);
553 else {
554 if (!spilled.count(i->reg))
555 unhandled_.push(i);
556 vrm_->clearVirt(i->reg);
557 }
558 }
559 else {
560 if (MRegisterInfo::isVirtualRegister(i->reg))
561 vrm_->clearVirt(i->reg);
562 unhandled_.push(i);
563 }
564 }
565
Chris Lattner850852c2004-11-18 03:49:30 +0000566 // Rewind the iterators in the active, inactive, and fixed lists back to the
567 // point we reverted to.
568 RevertVectorIteratorsTo(active_, earliestStart);
569 RevertVectorIteratorsTo(inactive_, earliestStart);
570 RevertVectorIteratorsTo(fixed_, earliestStart);
571
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000572 // scan the rest and undo each interval that expired after t and
573 // insert it in active (the next iteration of the algorithm will
574 // put it in inactive if required)
Chris Lattnera1f77792004-11-18 02:42:27 +0000575 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
576 LiveInterval *HI = handled_[i];
577 if (!HI->expiredAt(earliestStart) &&
578 HI->expiredAt(cur->beginNumber())) {
579 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
580 active_.push_back(std::make_pair(HI, HI->begin()));
581 if (MRegisterInfo::isPhysicalRegister(HI->reg))
582 prt_->addRegUse(HI->reg);
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000583 else
Chris Lattnera1f77792004-11-18 02:42:27 +0000584 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000585 }
586 }
587
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000588 // merge added with unhandled
589 for (unsigned i = 0, e = added.size(); i != e; ++i)
590 unhandled_.push(added[i]);
Alkis Evlogimenos2c5ddd22004-02-15 10:24:21 +0000591}
Alkis Evlogimenose82a7072004-02-06 18:08:18 +0000592
Chris Lattnera1f77792004-11-18 02:42:27 +0000593/// getFreePhysReg - return a free physical register for this virtual register
594/// interval if we have one, otherwise return 0.
Alkis Evlogimenos1a876fa2004-07-22 08:14:44 +0000595unsigned RA::getFreePhysReg(LiveInterval* cur)
Alkis Evlogimenosc09b77e2003-12-21 05:43:40 +0000596{
Alkis Evlogimenos095c3a82004-09-02 21:23:32 +0000597 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
598 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
599 i != e; ++i) {
Chris Lattnera1f77792004-11-18 02:42:27 +0000600 unsigned reg = i->first->reg;
Alkis Evlogimenos095c3a82004-09-02 21:23:32 +0000601 if (MRegisterInfo::isVirtualRegister(reg))
602 reg = vrm_->getPhys(reg);
603 ++inactiveCounts[reg];
604 }
605
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000606 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
Alkis Evlogimenos43b587d2003-12-28 17:58:18 +0000607
Alkis Evlogimenos095c3a82004-09-02 21:23:32 +0000608 unsigned freeReg = 0;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000609 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
610 i != rc->allocation_order_end(*mf_); ++i) {
611 unsigned reg = *i;
Alkis Evlogimenos095c3a82004-09-02 21:23:32 +0000612 if (prt_->isRegAvail(reg) &&
613 (!freeReg || inactiveCounts[freeReg] < inactiveCounts[reg]))
614 freeReg = reg;
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000615 }
Alkis Evlogimenos095c3a82004-09-02 21:23:32 +0000616 return freeReg;
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000617}
618
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000619FunctionPass* llvm::createLinearScanRegisterAllocator() {
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000620 return new RA();
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000621}