blob: 9a358faea0134a33686dcb54bef950e690b317f2 [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"
Chris Lattner3c3fe462005-09-21 04:19:09 +000015#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000016#include "PhysRegTracker.h"
17#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000018#include "llvm/Function.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000019#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000022#include "llvm/CodeGen/RegAllocRegistry.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/SSARegMap.h"
24#include "llvm/Target/MRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/Target/TargetMachine.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000026#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000029#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000030#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000031#include <algorithm>
Chris Lattner2c2c6c62006-01-22 23:41:00 +000032#include <iostream>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000033#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000034#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000035#include <memory>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000036using namespace llvm;
37
38namespace {
Alkis Evlogimenosd55b2b12004-07-04 07:59:06 +000039
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000040 static Statistic<double> efficiency
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000041 ("regalloc", "Ratio of intervals processed over total intervals");
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000042 static Statistic<> NumBacktracks
43 ("regalloc", "Number of times we had to backtrack");
Alkis Evlogimenosd55b2b12004-07-04 07:59:06 +000044
Jim Laskey13ec7022006-08-01 14:21:23 +000045 static RegisterRegAlloc
46 linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
48
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000049 static unsigned numIterations = 0;
50 static unsigned numIntervals = 0;
Alkis Evlogimenosc1560952004-07-04 17:23:35 +000051
Chris Lattnerf8c68f62006-06-28 22:17:39 +000052 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
Chris Lattnercbb56252004-11-18 02:42:27 +000053 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
54 typedef std::vector<IntervalPtr> IntervalPtrs;
55 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000056 /// RelatedRegClasses - This structure is built the first time a function is
57 /// compiled, and keeps track of which register classes have registers that
58 /// belong to multiple classes or have aliases that are in other classes.
59 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
60 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
61
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000062 MachineFunction* mf_;
63 const TargetMachine* tm_;
64 const MRegisterInfo* mri_;
65 LiveIntervals* li_;
Chris Lattnerb0f31bf2005-01-23 22:45:13 +000066 bool *PhysRegsUsed;
Chris Lattnercbb56252004-11-18 02:42:27 +000067
68 /// handled_ - Intervals are added to the handled_ set in the order of their
69 /// start value. This is uses for backtracking.
70 std::vector<LiveInterval*> handled_;
71
72 /// fixed_ - Intervals that correspond to machine registers.
73 ///
74 IntervalPtrs fixed_;
75
76 /// active_ - Intervals that are currently being processed, and which have a
77 /// live range active for the current point.
78 IntervalPtrs active_;
79
80 /// inactive_ - Intervals that are currently being processed, but which have
81 /// a hold at the current point.
82 IntervalPtrs inactive_;
83
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000084 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000085 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000086 greater_ptr<LiveInterval> > IntervalHeap;
87 IntervalHeap unhandled_;
88 std::auto_ptr<PhysRegTracker> prt_;
89 std::auto_ptr<VirtRegMap> vrm_;
90 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000091
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000092 public:
93 virtual const char* getPassName() const {
94 return "Linear Scan Register Allocator";
95 }
96
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000098 AU.addRequired<LiveIntervals>();
99 MachineFunctionPass::getAnalysisUsage(AU);
100 }
101
102 /// runOnMachineFunction - register allocate the whole function
103 bool runOnMachineFunction(MachineFunction&);
104
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 private:
106 /// linearScan - the linear scan algorithm
107 void linearScan();
108
Chris Lattnercbb56252004-11-18 02:42:27 +0000109 /// initIntervalSets - initialize the interval sets.
110 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000111 void initIntervalSets();
112
Chris Lattnercbb56252004-11-18 02:42:27 +0000113 /// processActiveIntervals - expire old intervals and move non-overlapping
114 /// ones to the inactive list.
115 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116
Chris Lattnercbb56252004-11-18 02:42:27 +0000117 /// processInactiveIntervals - expire old intervals and move overlapping
118 /// ones to the active list.
119 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000120
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000121 /// assignRegOrStackSlotAtInterval - assign a register if one
122 /// is available, or spill.
123 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
124
125 ///
126 /// register handling helpers
127 ///
128
Chris Lattnercbb56252004-11-18 02:42:27 +0000129 /// getFreePhysReg - return a free physical register for this virtual
130 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 unsigned getFreePhysReg(LiveInterval* cur);
132
133 /// assignVirt2StackSlot - assigns this virtual register to a
134 /// stack slot. returns the stack slot
135 int assignVirt2StackSlot(unsigned virtReg);
136
Chris Lattnerb9805782005-08-23 22:27:31 +0000137 void ComputeRelatedRegClasses();
138
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000139 template <typename ItTy>
140 void printIntervals(const char* const str, ItTy i, ItTy e) const {
141 if (str) std::cerr << str << " intervals:\n";
142 for (; i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000143 std::cerr << "\t" << *i->first << " -> ";
144 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000145 if (MRegisterInfo::isVirtualRegister(reg)) {
146 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000147 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000148 std::cerr << mri_->getName(reg) << '\n';
149 }
150 }
151 };
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000152}
153
Chris Lattnerb9805782005-08-23 22:27:31 +0000154void RA::ComputeRelatedRegClasses() {
155 const MRegisterInfo &MRI = *mri_;
156
157 // First pass, add all reg classes to the union, and determine at least one
158 // reg class that each register is in.
159 bool HasAliases = false;
160 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
161 E = MRI.regclass_end(); RCI != E; ++RCI) {
162 RelatedRegClasses.insert(*RCI);
163 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
164 I != E; ++I) {
165 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
166
167 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
168 if (PRC) {
169 // Already processed this register. Just make sure we know that
170 // multiple register classes share a register.
171 RelatedRegClasses.unionSets(PRC, *RCI);
172 } else {
173 PRC = *RCI;
174 }
175 }
176 }
177
178 // Second pass, now that we know conservatively what register classes each reg
179 // belongs to, add info about aliases. We don't need to do this for targets
180 // without register aliases.
181 if (HasAliases)
182 for (std::map<unsigned, const TargetRegisterClass*>::iterator
183 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
184 I != E; ++I)
185 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
186 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
187}
188
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000189bool RA::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000190 mf_ = &fn;
191 tm_ = &fn.getTarget();
192 mri_ = tm_->getRegisterInfo();
193 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000194
Chris Lattnerb9805782005-08-23 22:27:31 +0000195 // If this is the first function compiled, compute the related reg classes.
196 if (RelatedRegClasses.empty())
197 ComputeRelatedRegClasses();
198
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000199 PhysRegsUsed = new bool[mri_->getNumRegs()];
200 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
201 fn.setUsedPhysRegs(PhysRegsUsed);
202
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000203 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
204 vrm_.reset(new VirtRegMap(*mf_));
205 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000206
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000207 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000208
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000209 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000210
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000211 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000212 spiller_->runOnMachineFunction(*mf_, *vrm_);
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000213
Chris Lattner510a3ea2004-09-30 02:02:33 +0000214 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000215
216
217 while (!unhandled_.empty()) unhandled_.pop();
218 fixed_.clear();
219 active_.clear();
220 inactive_.clear();
221 handled_.clear();
222
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000223 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000224}
225
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000226/// initIntervalSets - initialize the interval sets.
227///
228void RA::initIntervalSets()
229{
230 assert(unhandled_.empty() && fixed_.empty() &&
231 active_.empty() && inactive_.empty() &&
232 "interval sets should be empty on initialization");
233
234 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000235 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
236 PhysRegsUsed[i->second.reg] = true;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000237 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000238 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000239 unhandled_.push(&i->second);
240 }
241}
242
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000243void RA::linearScan()
244{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 // linear scan algorithm
246 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
247 DEBUG(std::cerr << "********** Function: "
248 << mf_->getFunction()->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000249
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
251 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
252 DEBUG(printIntervals("active", active_.begin(), active_.end()));
253 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
254
255 while (!unhandled_.empty()) {
256 // pick the interval with the earliest start point
257 LiveInterval* cur = unhandled_.top();
258 unhandled_.pop();
259 ++numIterations;
260 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
261
Chris Lattnercbb56252004-11-18 02:42:27 +0000262 processActiveIntervals(cur->beginNumber());
263 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000264
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000265 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
266 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000267
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000268 // Allocating a virtual register. try to find a free
269 // physical register or spill an interval (possibly this one) in order to
270 // assign it one.
271 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000272
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000273 DEBUG(printIntervals("active", active_.begin(), active_.end()));
274 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000275 }
276 numIntervals += li_->getNumIntervals();
277 efficiency = double(numIterations) / double(numIntervals);
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000278
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000279 // expire any remaining active intervals
280 for (IntervalPtrs::reverse_iterator
281 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000282 unsigned reg = i->first->reg;
283 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000284 assert(MRegisterInfo::isVirtualRegister(reg) &&
285 "Can only allocate virtual registers!");
286 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000287 prt_->delRegUse(reg);
288 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
289 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000290
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000291 // expire any remaining inactive intervals
292 for (IntervalPtrs::reverse_iterator
293 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000294 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000295 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
296 }
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000297
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000298 DEBUG(std::cerr << *vrm_);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000299}
300
Chris Lattnercbb56252004-11-18 02:42:27 +0000301/// processActiveIntervals - expire old intervals and move non-overlapping ones
302/// to the inactive list.
303void RA::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000304{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 DEBUG(std::cerr << "\tprocessing active intervals:\n");
Chris Lattner23b71c12004-11-18 01:29:39 +0000306
Chris Lattnercbb56252004-11-18 02:42:27 +0000307 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
308 LiveInterval *Interval = active_[i].first;
309 LiveInterval::iterator IntervalPos = active_[i].second;
310 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000311
Chris Lattnercbb56252004-11-18 02:42:27 +0000312 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
313
314 if (IntervalPos == Interval->end()) { // Remove expired intervals.
315 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000316 assert(MRegisterInfo::isVirtualRegister(reg) &&
317 "Can only allocate virtual registers!");
318 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000319 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000320
321 // Pop off the end of the list.
322 active_[i] = active_.back();
323 active_.pop_back();
324 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000325
Chris Lattnercbb56252004-11-18 02:42:27 +0000326 } else if (IntervalPos->start > CurPoint) {
327 // Move inactive intervals to inactive list.
328 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000329 assert(MRegisterInfo::isVirtualRegister(reg) &&
330 "Can only allocate virtual registers!");
331 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000332 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000333 // add to inactive.
334 inactive_.push_back(std::make_pair(Interval, IntervalPos));
335
336 // Pop off the end of the list.
337 active_[i] = active_.back();
338 active_.pop_back();
339 --i; --e;
340 } else {
341 // Otherwise, just update the iterator position.
342 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 }
344 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000345}
346
Chris Lattnercbb56252004-11-18 02:42:27 +0000347/// processInactiveIntervals - expire old intervals and move overlapping
348/// ones to the active list.
349void RA::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000350{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000351 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
Chris Lattner365b95f2004-11-18 04:13:02 +0000352
Chris Lattnercbb56252004-11-18 02:42:27 +0000353 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
354 LiveInterval *Interval = inactive_[i].first;
355 LiveInterval::iterator IntervalPos = inactive_[i].second;
356 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000357
Chris Lattnercbb56252004-11-18 02:42:27 +0000358 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000359
Chris Lattnercbb56252004-11-18 02:42:27 +0000360 if (IntervalPos == Interval->end()) { // remove expired intervals.
361 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000362
Chris Lattnercbb56252004-11-18 02:42:27 +0000363 // Pop off the end of the list.
364 inactive_[i] = inactive_.back();
365 inactive_.pop_back();
366 --i; --e;
367 } else if (IntervalPos->start <= CurPoint) {
368 // move re-activated intervals in active list
369 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000370 assert(MRegisterInfo::isVirtualRegister(reg) &&
371 "Can only allocate virtual registers!");
372 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000373 prt_->addRegUse(reg);
374 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000375 active_.push_back(std::make_pair(Interval, IntervalPos));
376
377 // Pop off the end of the list.
378 inactive_[i] = inactive_.back();
379 inactive_.pop_back();
380 --i; --e;
381 } else {
382 // Otherwise, just update the iterator position.
383 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000384 }
385 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000386}
387
Chris Lattnercbb56252004-11-18 02:42:27 +0000388/// updateSpillWeights - updates the spill weights of the specifed physical
389/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000390static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000391 unsigned reg, float weight,
392 const MRegisterInfo *MRI) {
393 Weights[reg] += weight;
394 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
395 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000396}
397
Chris Lattnercbb56252004-11-18 02:42:27 +0000398static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
399 LiveInterval *LI) {
400 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
401 if (I->first == LI) return I;
402 return IP.end();
403}
404
Chris Lattner19828d42004-11-18 03:49:30 +0000405static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
406 for (unsigned i = 0, e = V.size(); i != e; ++i) {
407 RA::IntervalPtr &IP = V[i];
408 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
409 IP.second, Point);
410 if (I != IP.first->begin()) --I;
411 IP.second = I;
412 }
413}
Chris Lattnercbb56252004-11-18 02:42:27 +0000414
Chris Lattnercbb56252004-11-18 02:42:27 +0000415/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
416/// spill.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000417void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000418{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000419 DEBUG(std::cerr << "\tallocating current interval: ");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000420
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000421 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000422
Chris Lattnera6c17502005-08-22 20:20:42 +0000423 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000424 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000425 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
426 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
427
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000428 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000429 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000430 for (IntervalPtrs::const_iterator i = inactive_.begin(),
431 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000432 unsigned Reg = i->first->reg;
433 assert(MRegisterInfo::isVirtualRegister(Reg) &&
434 "Can only allocate virtual registers!");
435 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
436 // If this is not in a related reg class to the register we're allocating,
437 // don't check it.
438 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
439 cur->overlapsFrom(*i->first, i->second-1)) {
440 Reg = vrm_->getPhys(Reg);
441 prt_->addRegUse(Reg);
442 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000443 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000444 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000445
446 // Speculatively check to see if we can get a register right now. If not,
447 // we know we won't be able to by adding more constraints. If so, we can
448 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
449 // is very bad (it contains all callee clobbered registers for any functions
450 // with a call), so we want to avoid doing that if possible.
451 unsigned physReg = getFreePhysReg(cur);
452 if (physReg) {
453 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000454 // conflict with it. Check to see if we conflict with it or any of its
455 // aliases.
456 std::set<unsigned> RegAliases;
457 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
458 RegAliases.insert(*AS);
459
Chris Lattnera411cbc2005-08-22 20:59:30 +0000460 bool ConflictsWithFixed = false;
461 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000462 IntervalPtr &IP = fixed_[i];
463 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000464 // Okay, this reg is on the fixed list. Check to see if we actually
465 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000466 LiveInterval *I = IP.first;
467 if (I->endNumber() > StartPosition) {
468 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
469 IP.second = II;
470 if (II != I->begin() && II->start > StartPosition)
471 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000472 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000473 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000474 break;
475 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000476 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000477 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000478 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000479
480 // Okay, the register picked by our speculative getFreePhysReg call turned
481 // out to be in use. Actually add all of the conflicting fixed registers to
482 // prt so we can do an accurate query.
483 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000484 // For every interval in fixed we overlap with, mark the register as not
485 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000486 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
487 IntervalPtr &IP = fixed_[i];
488 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000489
490 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
491 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
492 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000493 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
494 IP.second = II;
495 if (II != I->begin() && II->start > StartPosition)
496 --II;
497 if (cur->overlapsFrom(*I, II)) {
498 unsigned reg = I->reg;
499 prt_->addRegUse(reg);
500 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
501 }
502 }
503 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000504
Chris Lattnera411cbc2005-08-22 20:59:30 +0000505 // Using the newly updated prt_ object, which includes conflicts in the
506 // future, see if there are any registers available.
507 physReg = getFreePhysReg(cur);
508 }
509 }
510
Chris Lattnera6c17502005-08-22 20:20:42 +0000511 // Restore the physical register tracker, removing information about the
512 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000514
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000515 // if we find a free register, we are done: assign this virtual to
516 // the free physical register and add this interval to the active
517 // list.
518 if (physReg) {
519 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
520 vrm_->assignVirt2Phys(cur->reg, physReg);
521 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000522 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000523 handled_.push_back(cur);
524 return;
525 }
526 DEBUG(std::cerr << "no free registers\n");
527
Chris Lattnera6c17502005-08-22 20:20:42 +0000528 // Compile the spill weights into an array that is better for scanning.
529 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
530 for (std::vector<std::pair<unsigned, float> >::iterator
531 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
532 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
533
534 // for each interval in active, update spill weights.
535 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
536 i != e; ++i) {
537 unsigned reg = i->first->reg;
538 assert(MRegisterInfo::isVirtualRegister(reg) &&
539 "Can only allocate virtual registers!");
540 reg = vrm_->getPhys(reg);
541 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
542 }
543
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000544 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
545
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000546 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000547 float minWeight = HUGE_VALF;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000548 unsigned minReg = 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000549 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
550 e = RC->allocation_order_end(*mf_); i != e; ++i) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000551 unsigned reg = *i;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000552 if (minWeight > SpillWeights[reg]) {
553 minWeight = SpillWeights[reg];
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 minReg = reg;
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000555 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000556 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000557
558 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000559 if (!minReg) {
560 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
561 e = RC->allocation_order_end(*mf_); i != e; ++i) {
562 unsigned reg = *i;
563 // No need to worry about if the alias register size < regsize of RC.
564 // We are going to spill all registers that alias it anyway.
565 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
566 if (minWeight > SpillWeights[*as]) {
567 minWeight = SpillWeights[*as];
568 minReg = *as;
569 }
570 }
571 }
572
573 // All registers must have inf weight. Just grab one!
574 if (!minReg)
575 minReg = *RC->allocation_order_begin(*mf_);
576 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000577
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000578 DEBUG(std::cerr << "\t\tregister with min weight: "
579 << mri_->getName(minReg) << " (" << minWeight << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000580
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000581 // if the current has the minimum weight, we need to spill it and
582 // add any added intervals back to unhandled, and restart
583 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000584 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000585 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
586 int slot = vrm_->assignVirt2StackSlot(cur->reg);
587 std::vector<LiveInterval*> added =
588 li_->addIntervalsForSpills(*cur, *vrm_, slot);
589 if (added.empty())
590 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000591
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000592 // Merge added with unhandled. Note that we know that
593 // addIntervalsForSpills returns intervals sorted by their starting
594 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000595 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000596 unhandled_.push(added[i]);
597 return;
598 }
599
Chris Lattner19828d42004-11-18 03:49:30 +0000600 ++NumBacktracks;
601
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000602 // push the current interval back to unhandled since we are going
603 // to re-run at least this iteration. Since we didn't modify it it
604 // should go back right in the front of the list
605 unhandled_.push(cur);
606
607 // otherwise we spill all intervals aliasing the register with
608 // minimum weight, rollback to the interval with the earliest
609 // start point and let the linear scan algorithm run again
610 std::vector<LiveInterval*> added;
611 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
612 "did not choose a register to spill?");
613 std::vector<bool> toSpill(mri_->getNumRegs(), false);
Chris Lattner19828d42004-11-18 03:49:30 +0000614
615 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000616 toSpill[minReg] = true;
617 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
618 toSpill[*as] = true;
619
620 // the earliest start of a spilled interval indicates up to where
621 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000622 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000623
624 // set of spilled vregs (used later to rollback properly)
625 std::set<unsigned> spilled;
626
Chris Lattner19828d42004-11-18 03:49:30 +0000627 // spill live intervals of virtual regs mapped to the physical register we
628 // want to clear (and its aliases). We only spill those that overlap with the
629 // current interval as the rest do not affect its allocation. we also keep
630 // track of the earliest start of all spilled live intervals since this will
631 // mark our rollback point.
632 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000633 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000634 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000635 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000636 cur->overlapsFrom(*i->first, i->second)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000637 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
638 earliestStart = std::min(earliestStart, i->first->beginNumber());
639 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000640 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000641 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000642 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
643 spilled.insert(reg);
644 }
645 }
Chris Lattner19828d42004-11-18 03:49:30 +0000646 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000647 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000648 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000649 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000650 cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000651 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
652 earliestStart = std::min(earliestStart, i->first->beginNumber());
653 int slot = vrm_->assignVirt2StackSlot(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000654 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000655 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000656 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
657 spilled.insert(reg);
658 }
659 }
660
661 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
Chris Lattnercbb56252004-11-18 02:42:27 +0000662
663 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000664 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000665 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000666 while (!handled_.empty()) {
667 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000668 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000669 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000670 break;
671 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
672 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000673
674 // When undoing a live interval allocation we must know if it is active or
675 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000676 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000677 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000678 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000679 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
680 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000681 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000682 prt_->delRegUse(vrm_->getPhys(i->reg));
683 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000684 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000685 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000686 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
687 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000688 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000689 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000690 } else {
691 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
692 "Can only allocate virtual registers!");
693 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000694 unhandled_.push(i);
695 }
696 }
697
Chris Lattner19828d42004-11-18 03:49:30 +0000698 // Rewind the iterators in the active, inactive, and fixed lists back to the
699 // point we reverted to.
700 RevertVectorIteratorsTo(active_, earliestStart);
701 RevertVectorIteratorsTo(inactive_, earliestStart);
702 RevertVectorIteratorsTo(fixed_, earliestStart);
703
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000704 // scan the rest and undo each interval that expired after t and
705 // insert it in active (the next iteration of the algorithm will
706 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000707 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
708 LiveInterval *HI = handled_[i];
709 if (!HI->expiredAt(earliestStart) &&
710 HI->expiredAt(cur->beginNumber())) {
711 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
712 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000713 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
714 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000715 }
716 }
717
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000718 // merge added with unhandled
719 for (unsigned i = 0, e = added.size(); i != e; ++i)
720 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000721}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000722
Chris Lattnercbb56252004-11-18 02:42:27 +0000723/// getFreePhysReg - return a free physical register for this virtual register
724/// interval if we have one, otherwise return 0.
Chris Lattnerffab4222006-02-23 06:44:17 +0000725unsigned RA::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000726 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000727 unsigned MaxInactiveCount = 0;
728
Chris Lattnerb9805782005-08-23 22:27:31 +0000729 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
730 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
731
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000732 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
733 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000734 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000735 assert(MRegisterInfo::isVirtualRegister(reg) &&
736 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000737
738 // If this is not in a related reg class to the register we're allocating,
739 // don't check it.
740 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
741 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
742 reg = vrm_->getPhys(reg);
743 ++inactiveCounts[reg];
744 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
745 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000746 }
747
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000748 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
Alkis Evlogimenos26bfc082003-12-28 17:58:18 +0000749
Chris Lattnerf8355d92005-08-22 16:55:22 +0000750 unsigned FreeReg = 0;
751 unsigned FreeRegInactiveCount = 0;
752
753 // Scan for the first available register.
754 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
755 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
756 for (; I != E; ++I)
757 if (prt_->isRegAvail(*I)) {
758 FreeReg = *I;
759 FreeRegInactiveCount = inactiveCounts[FreeReg];
760 break;
761 }
762
763 // If there are no free regs, or if this reg has the max inactive count,
764 // return this register.
765 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
766
767 // Continue scanning the registers, looking for the one with the highest
768 // inactive count. Alkis found that this reduced register pressure very
769 // slightly on X86 (in rev 1.94 of this file), though this should probably be
770 // reevaluated now.
771 for (; I != E; ++I) {
772 unsigned Reg = *I;
773 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
774 FreeReg = Reg;
775 FreeRegInactiveCount = inactiveCounts[Reg];
776 if (FreeRegInactiveCount == MaxInactiveCount)
777 break; // We found the one with the max inactive count.
778 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000779 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000780
781 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000782}
783
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000784FunctionPass* llvm::createLinearScanRegisterAllocator() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000785 return new RA();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000786}