blob: 2b389117e7e0385d8458e8deebcbbbfcfe18df34 [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-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 Evlogimenos0d6c5b62004-02-24 08:58:30 +000013
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000014#define DEBUG_TYPE "regalloc"
15#include "llvm/Function.h"
Alkis Evlogimenosff0cbe12003-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 Evlogimenosff0cbe12003-11-20 03:32:25 +000021#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/Debug.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/STLExtras.h"
Chris Lattnera3b8b5c2004-07-23 17:56:30 +000025#include "LiveIntervalAnalysis.h"
Alkis Evlogimenos888b1a62004-02-23 00:53:31 +000026#include "PhysRegTracker.h"
Alkis Evlogimenos34d9bc92004-02-23 23:08:11 +000027#include "VirtRegMap.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000028#include <algorithm>
Alkis Evlogimenos880e8e42004-05-08 03:50:03 +000029#include <cmath>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000030#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000031#include <queue>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000032using namespace llvm;
33
34namespace {
Alkis Evlogimenosd55b2b12004-07-04 07:59:06 +000035
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000036 Statistic<double> efficiency
37 ("regalloc", "Ratio of intervals processed over total intervals");
Chris Lattner19828d42004-11-18 03:49:30 +000038 Statistic<> NumBacktracks("regalloc", "Number of times we had to backtrack");
Alkis Evlogimenosd55b2b12004-07-04 07:59:06 +000039
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000040 static unsigned numIterations = 0;
41 static unsigned numIntervals = 0;
Alkis Evlogimenosc1560952004-07-04 17:23:35 +000042
Chris Lattnercbb56252004-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 Evlogimenos1a8ea012004-08-04 09:46:26 +000047 MachineFunction* mf_;
48 const TargetMachine* tm_;
49 const MRegisterInfo* mri_;
50 LiveIntervals* li_;
Chris Lattnercbb56252004-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 Evlogimenos1a8ea012004-08-04 09:46:26 +000068 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000069 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-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 Evlogimenosff0cbe12003-11-20 03:32:25 +000075
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 public:
77 virtual const char* getPassName() const {
78 return "Linear Scan Register Allocator";
79 }
80
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000082 AU.addRequired<LiveIntervals>();
83 MachineFunctionPass::getAnalysisUsage(AU);
84 }
85
86 /// runOnMachineFunction - register allocate the whole function
87 bool runOnMachineFunction(MachineFunction&);
88
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000089 private:
90 /// linearScan - the linear scan algorithm
91 void linearScan();
92
Chris Lattnercbb56252004-11-18 02:42:27 +000093 /// initIntervalSets - initialize the interval sets.
94 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000095 void initIntervalSets();
96
Chris Lattnercbb56252004-11-18 02:42:27 +000097 /// processActiveIntervals - expire old intervals and move non-overlapping
98 /// ones to the inactive list.
99 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000100
Chris Lattnercbb56252004-11-18 02:42:27 +0000101 /// processInactiveIntervals - expire old intervals and move overlapping
102 /// ones to the active list.
103 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 /// assignRegOrStackSlotAtInterval - assign a register if one
106 /// is available, or spill.
107 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
108
109 ///
110 /// register handling helpers
111 ///
112
Chris Lattnercbb56252004-11-18 02:42:27 +0000113 /// getFreePhysReg - return a free physical register for this virtual
114 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 unsigned getFreePhysReg(LiveInterval* cur);
116
117 /// assignVirt2StackSlot - assigns this virtual register to a
118 /// stack slot. returns the stack slot
119 int assignVirt2StackSlot(unsigned virtReg);
120
121 template <typename ItTy>
122 void printIntervals(const char* const str, ItTy i, ItTy e) const {
123 if (str) std::cerr << str << " intervals:\n";
124 for (; i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000125 std::cerr << "\t" << *i->first << " -> ";
126 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000127 if (MRegisterInfo::isVirtualRegister(reg)) {
128 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000129 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130 std::cerr << mri_->getName(reg) << '\n';
131 }
132 }
133 };
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000134}
135
136bool RA::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000137 mf_ = &fn;
138 tm_ = &fn.getTarget();
139 mri_ = tm_->getRegisterInfo();
140 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000141
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000142 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
143 vrm_.reset(new VirtRegMap(*mf_));
144 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000145
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000146 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000147
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000148 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000149
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150 spiller_->runOnMachineFunction(*mf_, *vrm_);
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000151
Chris Lattner510a3ea2004-09-30 02:02:33 +0000152 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000153
154
155 while (!unhandled_.empty()) unhandled_.pop();
156 fixed_.clear();
157 active_.clear();
158 inactive_.clear();
159 handled_.clear();
160
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000161 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000162}
163
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000164/// initIntervalSets - initialize the interval sets.
165///
166void RA::initIntervalSets()
167{
168 assert(unhandled_.empty() && fixed_.empty() &&
169 active_.empty() && inactive_.empty() &&
170 "interval sets should be empty on initialization");
171
172 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
173 if (MRegisterInfo::isPhysicalRegister(i->second.reg))
174 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
175 else
176 unhandled_.push(&i->second);
177 }
178}
179
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000180void RA::linearScan()
181{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000182 // linear scan algorithm
183 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
184 DEBUG(std::cerr << "********** Function: "
185 << mf_->getFunction()->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000186
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000187 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
188 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
189 DEBUG(printIntervals("active", active_.begin(), active_.end()));
190 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
191
192 while (!unhandled_.empty()) {
193 // pick the interval with the earliest start point
194 LiveInterval* cur = unhandled_.top();
195 unhandled_.pop();
196 ++numIterations;
197 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
198
Chris Lattnercbb56252004-11-18 02:42:27 +0000199 processActiveIntervals(cur->beginNumber());
200 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000201
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000202 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
203 "Can only allocate virtual registers!");
204
205 // Allocating a virtual register. try to find a free
206 // physical register or spill an interval (possibly this one) in order to
207 // assign it one.
208 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000209
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000210 DEBUG(printIntervals("active", active_.begin(), active_.end()));
211 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000212 }
213 numIntervals += li_->getNumIntervals();
214 efficiency = double(numIterations) / double(numIntervals);
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000215
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000216 // expire any remaining active intervals
217 for (IntervalPtrs::reverse_iterator
218 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000219 unsigned reg = i->first->reg;
220 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000221 assert(MRegisterInfo::isVirtualRegister(reg) &&
222 "Can only allocate virtual registers!");
223 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000224 prt_->delRegUse(reg);
225 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
226 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000227
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000228 // expire any remaining inactive intervals
229 for (IntervalPtrs::reverse_iterator
230 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000231 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000232 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
233 }
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000234
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000235 DEBUG(std::cerr << *vrm_);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000236}
237
Chris Lattnercbb56252004-11-18 02:42:27 +0000238/// processActiveIntervals - expire old intervals and move non-overlapping ones
239/// to the inactive list.
240void RA::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000241{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000242 DEBUG(std::cerr << "\tprocessing active intervals:\n");
Chris Lattner23b71c12004-11-18 01:29:39 +0000243
Chris Lattnercbb56252004-11-18 02:42:27 +0000244 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
245 LiveInterval *Interval = active_[i].first;
246 LiveInterval::iterator IntervalPos = active_[i].second;
247 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000248
Chris Lattnercbb56252004-11-18 02:42:27 +0000249 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
250
251 if (IntervalPos == Interval->end()) { // Remove expired intervals.
252 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000253 assert(MRegisterInfo::isVirtualRegister(reg) &&
254 "Can only allocate virtual registers!");
255 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000256 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000257
258 // Pop off the end of the list.
259 active_[i] = active_.back();
260 active_.pop_back();
261 --i; --e;
262
263 } else if (IntervalPos->start > CurPoint) {
264 // Move inactive intervals to inactive list.
265 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000266 assert(MRegisterInfo::isVirtualRegister(reg) &&
267 "Can only allocate virtual registers!");
268 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000269 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000270 // add to inactive.
271 inactive_.push_back(std::make_pair(Interval, IntervalPos));
272
273 // Pop off the end of the list.
274 active_[i] = active_.back();
275 active_.pop_back();
276 --i; --e;
277 } else {
278 // Otherwise, just update the iterator position.
279 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000280 }
281 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000282}
283
Chris Lattnercbb56252004-11-18 02:42:27 +0000284/// processInactiveIntervals - expire old intervals and move overlapping
285/// ones to the active list.
286void RA::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000287{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000288 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
Chris Lattner365b95f2004-11-18 04:13:02 +0000289
Chris Lattnercbb56252004-11-18 02:42:27 +0000290 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
291 LiveInterval *Interval = inactive_[i].first;
292 LiveInterval::iterator IntervalPos = inactive_[i].second;
293 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000294
Chris Lattnercbb56252004-11-18 02:42:27 +0000295 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
296
297 if (IntervalPos == Interval->end()) { // remove expired intervals.
298 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000299
Chris Lattnercbb56252004-11-18 02:42:27 +0000300 // Pop off the end of the list.
301 inactive_[i] = inactive_.back();
302 inactive_.pop_back();
303 --i; --e;
304 } else if (IntervalPos->start <= CurPoint) {
305 // move re-activated intervals in active list
306 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000307 assert(MRegisterInfo::isVirtualRegister(reg) &&
308 "Can only allocate virtual registers!");
309 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000310 prt_->addRegUse(reg);
311 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000312 active_.push_back(std::make_pair(Interval, IntervalPos));
313
314 // Pop off the end of the list.
315 inactive_[i] = inactive_.back();
316 inactive_.pop_back();
317 --i; --e;
318 } else {
319 // Otherwise, just update the iterator position.
320 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000321 }
322 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000323}
324
Chris Lattnercbb56252004-11-18 02:42:27 +0000325/// updateSpillWeights - updates the spill weights of the specifed physical
326/// register and its weight.
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000327static void updateSpillWeights(std::vector<float> &Weights,
328 unsigned reg, float weight,
329 const MRegisterInfo *MRI) {
330 Weights[reg] += weight;
331 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
332 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000333}
334
Chris Lattnercbb56252004-11-18 02:42:27 +0000335static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
336 LiveInterval *LI) {
337 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
338 if (I->first == LI) return I;
339 return IP.end();
340}
341
Chris Lattner19828d42004-11-18 03:49:30 +0000342static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
343 for (unsigned i = 0, e = V.size(); i != e; ++i) {
344 RA::IntervalPtr &IP = V[i];
345 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
346 IP.second, Point);
347 if (I != IP.first->begin()) --I;
348 IP.second = I;
349 }
350}
Chris Lattnercbb56252004-11-18 02:42:27 +0000351
352
353/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
354/// spill.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000355void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000356{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000357 DEBUG(std::cerr << "\tallocating current interval: ");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000358
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000360
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000361 std::vector<float> SpillWeights;
362 SpillWeights.assign(mri_->getNumRegs(), 0.0);
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000363
Chris Lattner365b95f2004-11-18 04:13:02 +0000364 unsigned StartPosition = cur->beginNumber();
365
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000366 // for each interval in active, update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000367 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
368 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000369 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000370 assert(MRegisterInfo::isVirtualRegister(reg) &&
371 "Can only allocate virtual registers!");
372 reg = vrm_->getPhys(reg);
373 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 }
375
376 // for every interval in inactive we overlap with, mark the
377 // register as not free and update spill weights
378 for (IntervalPtrs::const_iterator i = inactive_.begin(),
379 e = inactive_.end(); i != e; ++i) {
Chris Lattner19828d42004-11-18 03:49:30 +0000380 if (cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000381 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000382 assert(MRegisterInfo::isVirtualRegister(reg) &&
383 "Can only allocate virtual registers!");
384 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000385 prt_->addRegUse(reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000386 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000387 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000388 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000389
Chris Lattner19828d42004-11-18 03:49:30 +0000390 // For every interval in fixed we overlap with, mark the register as not free
391 // and update spill weights.
Chris Lattner365b95f2004-11-18 04:13:02 +0000392 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
393 IntervalPtr &IP = fixed_[i];
394 LiveInterval *I = IP.first;
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000395 if (I->endNumber() > StartPosition) {
396 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
397 IP.second = II;
398 if (II != I->begin() && II->start > StartPosition)
399 --II;
400 if (cur->overlapsFrom(*I, II)) {
401 unsigned reg = I->reg;
402 prt_->addRegUse(reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000403 updateSpillWeights(SpillWeights, reg, I->weight, mri_);
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000404 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000405 }
Chris Lattner365b95f2004-11-18 04:13:02 +0000406 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000407
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408 unsigned physReg = getFreePhysReg(cur);
409 // restore the physical register tracker
410 *prt_ = backupPrt;
411 // if we find a free register, we are done: assign this virtual to
412 // the free physical register and add this interval to the active
413 // list.
414 if (physReg) {
415 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
416 vrm_->assignVirt2Phys(cur->reg, physReg);
417 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000418 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000419 handled_.push_back(cur);
420 return;
421 }
422 DEBUG(std::cerr << "no free registers\n");
423
424 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
425
426 float minWeight = HUGE_VAL;
427 unsigned minReg = 0;
428 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
Chris Lattner5b210342004-12-15 07:04:32 +0000429 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_),
430 e = rc->allocation_order_end(*mf_); i != e; ++i) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000431 unsigned reg = *i;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000432 if (minWeight > SpillWeights[reg]) {
433 minWeight = SpillWeights[reg];
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434 minReg = reg;
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000435 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000436 }
437 DEBUG(std::cerr << "\t\tregister with min weight: "
438 << mri_->getName(minReg) << " (" << minWeight << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000439
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000440 // if the current has the minimum weight, we need to spill it and
441 // add any added intervals back to unhandled, and restart
442 // linearscan.
443 if (cur->weight <= minWeight) {
444 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
445 int slot = vrm_->assignVirt2StackSlot(cur->reg);
446 std::vector<LiveInterval*> added =
447 li_->addIntervalsForSpills(*cur, *vrm_, slot);
448 if (added.empty())
449 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000450
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000451 // Merge added with unhandled. Note that we know that
452 // addIntervalsForSpills returns intervals sorted by their starting
453 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000454 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 unhandled_.push(added[i]);
456 return;
457 }
458
Chris Lattner19828d42004-11-18 03:49:30 +0000459 ++NumBacktracks;
460
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000461 // push the current interval back to unhandled since we are going
462 // to re-run at least this iteration. Since we didn't modify it it
463 // should go back right in the front of the list
464 unhandled_.push(cur);
465
466 // otherwise we spill all intervals aliasing the register with
467 // minimum weight, rollback to the interval with the earliest
468 // start point and let the linear scan algorithm run again
469 std::vector<LiveInterval*> added;
470 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
471 "did not choose a register to spill?");
472 std::vector<bool> toSpill(mri_->getNumRegs(), false);
Chris Lattner19828d42004-11-18 03:49:30 +0000473
474 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000475 toSpill[minReg] = true;
476 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
477 toSpill[*as] = true;
478
479 // the earliest start of a spilled interval indicates up to where
480 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000481 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000482
483 // set of spilled vregs (used later to rollback properly)
484 std::set<unsigned> spilled;
485
Chris Lattner19828d42004-11-18 03:49:30 +0000486 // spill live intervals of virtual regs mapped to the physical register we
487 // want to clear (and its aliases). We only spill those that overlap with the
488 // current interval as the rest do not affect its allocation. we also keep
489 // track of the earliest start of all spilled live intervals since this will
490 // mark our rollback point.
491 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000492 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000493 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000494 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000495 cur->overlapsFrom(*i->first, i->second)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000496 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
497 earliestStart = std::min(earliestStart, i->first->beginNumber());
498 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000499 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000500 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000501 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
502 spilled.insert(reg);
503 }
504 }
Chris Lattner19828d42004-11-18 03:49:30 +0000505 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000506 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000507 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000508 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000509 cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000510 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
511 earliestStart = std::min(earliestStart, i->first->beginNumber());
512 int slot = vrm_->assignVirt2StackSlot(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000514 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000515 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
516 spilled.insert(reg);
517 }
518 }
519
520 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
Chris Lattnercbb56252004-11-18 02:42:27 +0000521
522 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000523 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000524 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000525 while (!handled_.empty()) {
526 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000527 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000528 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000529 break;
530 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
531 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000532
533 // When undoing a live interval allocation we must know if it is active or
534 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000535 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000536 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000537 active_.erase(it);
538 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000539 assert(0 && "daksjlfd");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 prt_->delRegUse(i->reg);
541 unhandled_.push(i);
Chris Lattnercbb56252004-11-18 02:42:27 +0000542 } else {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 if (!spilled.count(i->reg))
544 unhandled_.push(i);
545 prt_->delRegUse(vrm_->getPhys(i->reg));
546 vrm_->clearVirt(i->reg);
547 }
Chris Lattnercbb56252004-11-18 02:42:27 +0000548 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000549 inactive_.erase(it);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000550 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
551 assert(0 && "daksjlfd");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552 unhandled_.push(i);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000553 } else {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 if (!spilled.count(i->reg))
555 unhandled_.push(i);
556 vrm_->clearVirt(i->reg);
557 }
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000558 } else {
559 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
560 "Can only allocate virtual registers!");
561 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000562 unhandled_.push(i);
563 }
564 }
565
Chris Lattner19828d42004-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 Evlogimenos1a8ea012004-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 Lattnercbb56252004-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()));
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000581 if (MRegisterInfo::isPhysicalRegister(HI->reg)) {
582 assert(0 &&"sdflkajsdf");
Chris Lattnercbb56252004-11-18 02:42:27 +0000583 prt_->addRegUse(HI->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000584 } else
Chris Lattnercbb56252004-11-18 02:42:27 +0000585 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000586 }
587 }
588
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000589 // merge added with unhandled
590 for (unsigned i = 0, e = added.size(); i != e; ++i)
591 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000592}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000593
Chris Lattnercbb56252004-11-18 02:42:27 +0000594/// getFreePhysReg - return a free physical register for this virtual register
595/// interval if we have one, otherwise return 0.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000596unsigned RA::getFreePhysReg(LiveInterval* cur)
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000597{
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000598 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
599 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
600 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000601 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000602 assert(MRegisterInfo::isVirtualRegister(reg) &&
603 "Can only allocate virtual registers!");
604 reg = vrm_->getPhys(reg);
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000605 ++inactiveCounts[reg];
606 }
607
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000608 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
Alkis Evlogimenos26bfc082003-12-28 17:58:18 +0000609
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000610 unsigned freeReg = 0;
Nate Begeman80ad87d2004-12-07 05:25:53 +0000611 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_),
612 e = rc->allocation_order_end(*mf_); i != e; ++i) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 unsigned reg = *i;
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000614 if (prt_->isRegAvail(reg) &&
615 (!freeReg || inactiveCounts[freeReg] < inactiveCounts[reg]))
616 freeReg = reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000617 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000618 return freeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000619}
620
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000621FunctionPass* llvm::createLinearScanRegisterAllocator() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000622 return new RA();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000623}