blob: 7f7b2818ffd2902d80b5e542ceb9b0b9882a78b4 [file] [log] [blame]
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +00001//===-- RegAllocIterativeScan.cpp - Iterative 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//
Alkis Evlogimenos3b1af0b2004-07-21 08:28:39 +000010// This file implements an iterative scan register
11// allocator. Iterative scan is a linear scan variant with the
12// following difference:
13//
14// It performs linear scan and keeps a list of the registers it cannot
15// allocate. It then spills all those registers and repeats the
16// process until allocation succeeds.
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +000017//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "regalloc"
21#include "llvm/Function.h"
22#include "llvm/CodeGen/LiveVariables.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineInstr.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/SSARegMap.h"
27#include "llvm/Target/MRegisterInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "Support/Debug.h"
30#include "Support/Statistic.h"
31#include "Support/STLExtras.h"
32#include "LiveIntervals.h"
33#include "PhysRegTracker.h"
34#include "VirtRegMap.h"
35#include <algorithm>
36#include <cmath>
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +000037#include <set>
38
39using namespace llvm;
40
41namespace {
42
43 Statistic<double> efficiency
44 ("regalloc", "Ratio of intervals processed over total intervals");
45
46 static unsigned numIterations = 0;
47 static unsigned numIntervals = 0;
48
49 class RA : public MachineFunctionPass {
50 private:
51 MachineFunction* mf_;
52 const TargetMachine* tm_;
53 const MRegisterInfo* mri_;
54 LiveIntervals* li_;
Alkis Evlogimenos2d547052004-07-21 09:46:55 +000055 typedef std::vector<LiveInterval*> IntervalPtrs;
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +000056 IntervalPtrs unhandled_, fixed_, active_, inactive_, handled_, spilled_;
57
58 std::auto_ptr<PhysRegTracker> prt_;
59 std::auto_ptr<VirtRegMap> vrm_;
60 std::auto_ptr<Spiller> spiller_;
61
62 typedef std::vector<float> SpillWeights;
63 SpillWeights spillWeights_;
64
65 public:
66 virtual const char* getPassName() const {
Alkis Evlogimenosd03451e2004-07-21 17:23:44 +000067 return "Iterative Scan Register Allocator";
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +000068 }
69
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<LiveVariables>();
72 AU.addRequired<LiveIntervals>();
73 MachineFunctionPass::getAnalysisUsage(AU);
74 }
75
76 /// runOnMachineFunction - register allocate the whole function
77 bool runOnMachineFunction(MachineFunction&);
78
79 void releaseMemory();
80
81 private:
82 /// linearScan - the linear scan algorithm. Returns a boolean
83 /// indicating if there were any spills
84 bool linearScan();
85
86 /// initIntervalSets - initializes the four interval sets:
87 /// unhandled, fixed, active and inactive
88 void initIntervalSets(LiveIntervals::Intervals& li);
89
90 /// processActiveIntervals - expire old intervals and move
91 /// non-overlapping ones to the incative list
92 void processActiveIntervals(IntervalPtrs::value_type cur);
93
94 /// processInactiveIntervals - expire old intervals and move
95 /// overlapping ones to the active list
96 void processInactiveIntervals(IntervalPtrs::value_type cur);
97
98 /// updateSpillWeights - updates the spill weights of the
99 /// specifed physical register and its weight
100 void updateSpillWeights(unsigned reg, SpillWeights::value_type weight);
101
102 /// assignRegOrStackSlotAtInterval - assign a register if one
103 /// is available, or spill.
104 void assignRegOrSpillAtInterval(IntervalPtrs::value_type cur);
105
106 ///
107 /// register handling helpers
108 ///
109
110 /// getFreePhysReg - return a free physical register for this
111 /// virtual register interval if we have one, otherwise return
112 /// 0
113 unsigned getFreePhysReg(IntervalPtrs::value_type cur);
114
115 /// assignVirt2StackSlot - assigns this virtual register to a
116 /// stack slot. returns the stack slot
117 int assignVirt2StackSlot(unsigned virtReg);
118
119 void printIntervals(const char* const str,
120 RA::IntervalPtrs::const_iterator i,
121 RA::IntervalPtrs::const_iterator e) const {
122 if (str) std::cerr << str << " intervals:\n";
123 for (; i != e; ++i) {
124 std::cerr << "\t" << **i << " -> ";
125 unsigned reg = (*i)->reg;
126 if (MRegisterInfo::isVirtualRegister(reg)) {
127 reg = vrm_->getPhys(reg);
128 }
129 std::cerr << mri_->getName(reg) << '\n';
130 }
131 }
132 };
133}
134
135void RA::releaseMemory()
136{
137 unhandled_.clear();
138 fixed_.clear();
139 active_.clear();
140 inactive_.clear();
141 handled_.clear();
142 spilled_.clear();
143}
144
145bool RA::runOnMachineFunction(MachineFunction &fn) {
146 mf_ = &fn;
147 tm_ = &fn.getTarget();
148 mri_ = tm_->getRegisterInfo();
149 li_ = &getAnalysis<LiveIntervals>();
150 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
151 vrm_.reset(new VirtRegMap(*mf_));
152 if (!spiller_.get()) spiller_.reset(createSpiller());
153
154 initIntervalSets(li_->getIntervals());
155
156 numIntervals += li_->getIntervals().size();
157
158 while (linearScan()) {
159 // we spilled some registers, so we need to add intervals for
160 // the spill code and restart the algorithm
161 std::set<unsigned> spilledRegs;
162 for (IntervalPtrs::iterator
Alkis Evlogimenosfc29e632004-07-21 12:00:10 +0000163 i = spilled_.begin(); i != spilled_.end(); ++i) {
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +0000164 int slot = vrm_->assignVirt2StackSlot((*i)->reg);
165 std::vector<LiveInterval*> added =
166 li_->addIntervalsForSpills(**i, *vrm_, slot);
167 std::copy(added.begin(), added.end(), std::back_inserter(handled_));
168 spilledRegs.insert((*i)->reg);
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +0000169 }
Alkis Evlogimenosfc29e632004-07-21 12:00:10 +0000170 spilled_.clear();
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +0000171 for (IntervalPtrs::iterator
172 i = handled_.begin(); i != handled_.end(); )
173 if (spilledRegs.count((*i)->reg))
174 i = handled_.erase(i);
175 else
176 ++i;
177 handled_.swap(unhandled_);
178 vrm_->clearAllVirt();
179 }
180
181 efficiency = double(numIterations) / double(numIntervals);
182
183 DEBUG(std::cerr << *vrm_);
184
185 spiller_->runOnMachineFunction(*mf_, *vrm_);
186
187 return true;
188}
189
190bool RA::linearScan()
191{
192 // linear scan algorithm
193 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
194 DEBUG(std::cerr << "********** Function: "
195 << mf_->getFunction()->getName() << '\n');
196
197
Alkis Evlogimenos2d547052004-07-21 09:46:55 +0000198 std::sort(unhandled_.begin(), unhandled_.end(),
199 greater_ptr<LiveInterval>());
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +0000200 DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
201 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
202 DEBUG(printIntervals("active", active_.begin(), active_.end()));
203 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
204
205 while (!unhandled_.empty()) {
206 // pick the interval with the earliest start point
Alkis Evlogimenos2d547052004-07-21 09:46:55 +0000207 IntervalPtrs::value_type cur = unhandled_.back();
208 unhandled_.pop_back();
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +0000209 ++numIterations;
210 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
211
212 processActiveIntervals(cur);
213 processInactiveIntervals(cur);
214
215 // if this register is fixed we are done
216 if (MRegisterInfo::isPhysicalRegister(cur->reg)) {
217 prt_->addRegUse(cur->reg);
218 active_.push_back(cur);
219 handled_.push_back(cur);
220 }
221 // otherwise we are allocating a virtual register. try to find
222 // a free physical register or spill an interval in order to
223 // assign it one (we could spill the current though).
224 else {
225 assignRegOrSpillAtInterval(cur);
226 }
227
228 DEBUG(printIntervals("active", active_.begin(), active_.end()));
229 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
230 }
231
232 // expire any remaining active intervals
233 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ) {
234 unsigned reg = (*i)->reg;
235 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
236 if (MRegisterInfo::isVirtualRegister(reg))
237 reg = vrm_->getPhys(reg);
238 prt_->delRegUse(reg);
239 i = active_.erase(i);
240 }
241
242 // expire any remaining inactive intervals
243 for (IntervalPtrs::iterator
244 i = inactive_.begin(); i != inactive_.end(); ) {
245 DEBUG(std::cerr << "\tinterval " << **i << " expired\n");
246 i = inactive_.erase(i);
247 }
248
249 // return true if we spilled anything
250 return !spilled_.empty();
251}
252
253void RA::initIntervalSets(LiveIntervals::Intervals& li)
254{
255 assert(unhandled_.empty() && fixed_.empty() &&
256 active_.empty() && inactive_.empty() &&
257 "interval sets should be empty on initialization");
258
259 for (LiveIntervals::Intervals::iterator i = li.begin(), e = li.end();
260 i != e; ++i) {
261 unhandled_.push_back(&*i);
262 if (MRegisterInfo::isPhysicalRegister(i->reg))
263 fixed_.push_back(&*i);
264 }
265}
266
267void RA::processActiveIntervals(IntervalPtrs::value_type cur)
268{
269 DEBUG(std::cerr << "\tprocessing active intervals:\n");
270 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end();) {
271 unsigned reg = (*i)->reg;
272 // remove expired intervals
273 if ((*i)->expiredAt(cur->start())) {
274 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
275 if (MRegisterInfo::isVirtualRegister(reg))
276 reg = vrm_->getPhys(reg);
277 prt_->delRegUse(reg);
278 // remove from active
279 i = active_.erase(i);
280 }
281 // move inactive intervals to inactive list
282 else if (!(*i)->liveAt(cur->start())) {
283 DEBUG(std::cerr << "\t\tinterval " << **i << " inactive\n");
284 if (MRegisterInfo::isVirtualRegister(reg))
285 reg = vrm_->getPhys(reg);
286 prt_->delRegUse(reg);
287 // add to inactive
288 inactive_.push_back(*i);
289 // remove from active
290 i = active_.erase(i);
291 }
292 else {
293 ++i;
294 }
295 }
296}
297
298void RA::processInactiveIntervals(IntervalPtrs::value_type cur)
299{
300 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
301 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end();) {
302 unsigned reg = (*i)->reg;
303
304 // remove expired intervals
305 if ((*i)->expiredAt(cur->start())) {
306 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
307 // remove from inactive
308 i = inactive_.erase(i);
309 }
310 // move re-activated intervals in active list
311 else if ((*i)->liveAt(cur->start())) {
312 DEBUG(std::cerr << "\t\tinterval " << **i << " active\n");
313 if (MRegisterInfo::isVirtualRegister(reg))
314 reg = vrm_->getPhys(reg);
315 prt_->addRegUse(reg);
316 // add to active
317 active_.push_back(*i);
318 // remove from inactive
319 i = inactive_.erase(i);
320 }
321 else {
322 ++i;
323 }
324 }
325}
326
327void RA::updateSpillWeights(unsigned reg, SpillWeights::value_type weight)
328{
329 spillWeights_[reg] += weight;
330 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
331 spillWeights_[*as] += weight;
332}
333
334void RA::assignRegOrSpillAtInterval(IntervalPtrs::value_type cur)
335{
336 DEBUG(std::cerr << "\tallocating current interval: ");
337
338 PhysRegTracker backupPrt = *prt_;
339
340 spillWeights_.assign(mri_->getNumRegs(), 0.0);
341
342 // for each interval in active update spill weights
343 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
344 i != e; ++i) {
345 unsigned reg = (*i)->reg;
346 if (MRegisterInfo::isVirtualRegister(reg))
347 reg = vrm_->getPhys(reg);
348 updateSpillWeights(reg, (*i)->weight);
349 }
350
351 // for every interval in inactive we overlap with, mark the
352 // register as not free and update spill weights
353 for (IntervalPtrs::const_iterator i = inactive_.begin(),
354 e = inactive_.end(); i != e; ++i) {
355 if (cur->overlaps(**i)) {
356 unsigned reg = (*i)->reg;
357 if (MRegisterInfo::isVirtualRegister(reg))
358 reg = vrm_->getPhys(reg);
359 prt_->addRegUse(reg);
360 updateSpillWeights(reg, (*i)->weight);
361 }
362 }
363
364 // for every interval in fixed we overlap with,
365 // mark the register as not free and update spill weights
366 for (IntervalPtrs::const_iterator i = fixed_.begin(),
367 e = fixed_.end(); i != e; ++i) {
368 if (cur->overlaps(**i)) {
369 unsigned reg = (*i)->reg;
370 prt_->addRegUse(reg);
371 updateSpillWeights(reg, (*i)->weight);
372 }
373 }
374
375 unsigned physReg = getFreePhysReg(cur);
376 // restore the physical register tracker
377 *prt_ = backupPrt;
378 // if we find a free register, we are done: assign this virtual to
379 // the free physical register and add this interval to the active
380 // list.
381 if (physReg) {
382 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
383 vrm_->assignVirt2Phys(cur->reg, physReg);
384 prt_->addRegUse(physReg);
385 active_.push_back(cur);
386 handled_.push_back(cur);
387 return;
388 }
389 DEBUG(std::cerr << "no free registers\n");
390
391 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
392
393 float minWeight = HUGE_VAL;
394 unsigned minReg = 0;
395 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
396 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
397 i != rc->allocation_order_end(*mf_); ++i) {
398 unsigned reg = *i;
399 if (minWeight > spillWeights_[reg]) {
400 minWeight = spillWeights_[reg];
401 minReg = reg;
402 }
403 }
404 DEBUG(std::cerr << "\t\tregister with min weight: "
405 << mri_->getName(minReg) << " (" << minWeight << ")\n");
406
407 // if the current has the minimum weight, we spill it and move on
408 if (cur->weight <= minWeight) {
409 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n');
410 spilled_.push_back(cur);
411 return;
412 }
413
414 // otherwise we spill all intervals aliasing the register with
415 // minimum weight, assigned the newly cleared register to the
416 // current interval and continue
Alkis Evlogimenos910d0d62004-07-21 08:24:35 +0000417 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
418 "did not choose a register to spill?");
419 std::vector<bool> toSpill(mri_->getNumRegs(), false);
420 toSpill[minReg] = true;
421 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
422 toSpill[*as] = true;
423 unsigned earliestStart = cur->start();
424
425 std::set<unsigned> spilled;
426
427 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ) {
428 unsigned reg = (*i)->reg;
429 if (MRegisterInfo::isVirtualRegister(reg) &&
430 toSpill[vrm_->getPhys(reg)] &&
431 cur->overlaps(**i)) {
432 DEBUG(std::cerr << "\t\t\tspilling(a): " << **i << '\n');
433 spilled_.push_back(*i);
434 prt_->delRegUse(vrm_->getPhys(reg));
435 vrm_->clearVirt(reg);
436 i = active_.erase(i);
437 }
438 else
439 ++i;
440 }
441 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ) {
442 unsigned reg = (*i)->reg;
443 if (MRegisterInfo::isVirtualRegister(reg) &&
444 toSpill[vrm_->getPhys(reg)] &&
445 cur->overlaps(**i)) {
446 DEBUG(std::cerr << "\t\t\tspilling(i): " << **i << '\n');
447 spilled_.push_back(*i);
448 vrm_->clearVirt(reg);
449 i = inactive_.erase(i);
450 }
451 else
452 ++i;
453 }
454
455 vrm_->assignVirt2Phys(cur->reg, minReg);
456 prt_->addRegUse(minReg);
457 active_.push_back(cur);
458 handled_.push_back(cur);
459
460}
461
462unsigned RA::getFreePhysReg(IntervalPtrs::value_type cur)
463{
464 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
465
466 for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_);
467 i != rc->allocation_order_end(*mf_); ++i) {
468 unsigned reg = *i;
469 if (prt_->isRegAvail(reg))
470 return reg;
471 }
472 return 0;
473}
474
475FunctionPass* llvm::createIterativeScanRegisterAllocator() {
476 return new RA();
477}