blob: 550d2a4e0c1a17f7e87e26088b9623a1965ad8f1 [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"
22#include "llvm/CodeGen/SSARegMap.h"
23#include "llvm/Target/MRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/Target/TargetMachine.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000025#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000028#include "llvm/Support/Debug.h"
Chris Lattnerf8c68f62006-06-28 22:17:39 +000029#include "llvm/Support/Visibility.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000030#include <algorithm>
Alkis Evlogimenos880e8e42004-05-08 03:50:03 +000031#include <cmath>
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
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000045 static unsigned numIterations = 0;
46 static unsigned numIntervals = 0;
Alkis Evlogimenosc1560952004-07-04 17:23:35 +000047
Chris Lattnerf8c68f62006-06-28 22:17:39 +000048 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
Chris Lattnercbb56252004-11-18 02:42:27 +000049 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
50 typedef std::vector<IntervalPtr> IntervalPtrs;
51 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000052 /// RelatedRegClasses - This structure is built the first time a function is
53 /// compiled, and keeps track of which register classes have registers that
54 /// belong to multiple classes or have aliases that are in other classes.
55 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
56 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
57
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000058 MachineFunction* mf_;
59 const TargetMachine* tm_;
60 const MRegisterInfo* mri_;
61 LiveIntervals* li_;
Chris Lattnerb0f31bf2005-01-23 22:45:13 +000062 bool *PhysRegsUsed;
Chris Lattnercbb56252004-11-18 02:42:27 +000063
64 /// handled_ - Intervals are added to the handled_ set in the order of their
65 /// start value. This is uses for backtracking.
66 std::vector<LiveInterval*> handled_;
67
68 /// fixed_ - Intervals that correspond to machine registers.
69 ///
70 IntervalPtrs fixed_;
71
72 /// active_ - Intervals that are currently being processed, and which have a
73 /// live range active for the current point.
74 IntervalPtrs active_;
75
76 /// inactive_ - Intervals that are currently being processed, but which have
77 /// a hold at the current point.
78 IntervalPtrs inactive_;
79
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000080 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000081 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000082 greater_ptr<LiveInterval> > IntervalHeap;
83 IntervalHeap unhandled_;
84 std::auto_ptr<PhysRegTracker> prt_;
85 std::auto_ptr<VirtRegMap> vrm_;
86 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000087
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 public:
89 virtual const char* getPassName() const {
90 return "Linear Scan Register Allocator";
91 }
92
93 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000094 AU.addRequired<LiveIntervals>();
95 MachineFunctionPass::getAnalysisUsage(AU);
96 }
97
98 /// runOnMachineFunction - register allocate the whole function
99 bool runOnMachineFunction(MachineFunction&);
100
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000101 private:
102 /// linearScan - the linear scan algorithm
103 void linearScan();
104
Chris Lattnercbb56252004-11-18 02:42:27 +0000105 /// initIntervalSets - initialize the interval sets.
106 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000107 void initIntervalSets();
108
Chris Lattnercbb56252004-11-18 02:42:27 +0000109 /// processActiveIntervals - expire old intervals and move non-overlapping
110 /// ones to the inactive list.
111 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000112
Chris Lattnercbb56252004-11-18 02:42:27 +0000113 /// processInactiveIntervals - expire old intervals and move overlapping
114 /// ones to the active list.
115 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000117 /// assignRegOrStackSlotAtInterval - assign a register if one
118 /// is available, or spill.
119 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
120
121 ///
122 /// register handling helpers
123 ///
124
Chris Lattnercbb56252004-11-18 02:42:27 +0000125 /// getFreePhysReg - return a free physical register for this virtual
126 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000127 unsigned getFreePhysReg(LiveInterval* cur);
128
129 /// assignVirt2StackSlot - assigns this virtual register to a
130 /// stack slot. returns the stack slot
131 int assignVirt2StackSlot(unsigned virtReg);
132
Chris Lattnerb9805782005-08-23 22:27:31 +0000133 void ComputeRelatedRegClasses();
134
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000135 template <typename ItTy>
136 void printIntervals(const char* const str, ItTy i, ItTy e) const {
137 if (str) std::cerr << str << " intervals:\n";
138 for (; i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000139 std::cerr << "\t" << *i->first << " -> ";
140 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000141 if (MRegisterInfo::isVirtualRegister(reg)) {
142 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000143 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000144 std::cerr << mri_->getName(reg) << '\n';
145 }
146 }
147 };
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000148}
149
Chris Lattnerb9805782005-08-23 22:27:31 +0000150void RA::ComputeRelatedRegClasses() {
151 const MRegisterInfo &MRI = *mri_;
152
153 // First pass, add all reg classes to the union, and determine at least one
154 // reg class that each register is in.
155 bool HasAliases = false;
156 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
157 E = MRI.regclass_end(); RCI != E; ++RCI) {
158 RelatedRegClasses.insert(*RCI);
159 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
160 I != E; ++I) {
161 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
162
163 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
164 if (PRC) {
165 // Already processed this register. Just make sure we know that
166 // multiple register classes share a register.
167 RelatedRegClasses.unionSets(PRC, *RCI);
168 } else {
169 PRC = *RCI;
170 }
171 }
172 }
173
174 // Second pass, now that we know conservatively what register classes each reg
175 // belongs to, add info about aliases. We don't need to do this for targets
176 // without register aliases.
177 if (HasAliases)
178 for (std::map<unsigned, const TargetRegisterClass*>::iterator
179 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
180 I != E; ++I)
181 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
182 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
183}
184
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000185bool RA::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000186 mf_ = &fn;
187 tm_ = &fn.getTarget();
188 mri_ = tm_->getRegisterInfo();
189 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000190
Chris Lattnerb9805782005-08-23 22:27:31 +0000191 // If this is the first function compiled, compute the related reg classes.
192 if (RelatedRegClasses.empty())
193 ComputeRelatedRegClasses();
194
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000195 PhysRegsUsed = new bool[mri_->getNumRegs()];
196 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
197 fn.setUsedPhysRegs(PhysRegsUsed);
198
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000199 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
200 vrm_.reset(new VirtRegMap(*mf_));
201 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000202
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000203 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000204
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000205 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000206
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000207 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000208 spiller_->runOnMachineFunction(*mf_, *vrm_);
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000209
Chris Lattner510a3ea2004-09-30 02:02:33 +0000210 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000211
212
213 while (!unhandled_.empty()) unhandled_.pop();
214 fixed_.clear();
215 active_.clear();
216 inactive_.clear();
217 handled_.clear();
218
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000219 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000220}
221
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000222/// initIntervalSets - initialize the interval sets.
223///
224void RA::initIntervalSets()
225{
226 assert(unhandled_.empty() && fixed_.empty() &&
227 active_.empty() && inactive_.empty() &&
228 "interval sets should be empty on initialization");
229
230 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000231 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
232 PhysRegsUsed[i->second.reg] = true;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000233 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000234 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000235 unhandled_.push(&i->second);
236 }
237}
238
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000239void RA::linearScan()
240{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000241 // linear scan algorithm
242 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
243 DEBUG(std::cerr << "********** Function: "
244 << mf_->getFunction()->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000245
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000246 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
247 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
248 DEBUG(printIntervals("active", active_.begin(), active_.end()));
249 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
250
251 while (!unhandled_.empty()) {
252 // pick the interval with the earliest start point
253 LiveInterval* cur = unhandled_.top();
254 unhandled_.pop();
255 ++numIterations;
256 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
257
Chris Lattnercbb56252004-11-18 02:42:27 +0000258 processActiveIntervals(cur->beginNumber());
259 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000260
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000261 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
262 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000263
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000264 // Allocating a virtual register. try to find a free
265 // physical register or spill an interval (possibly this one) in order to
266 // assign it one.
267 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000269 DEBUG(printIntervals("active", active_.begin(), active_.end()));
270 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000271 }
272 numIntervals += li_->getNumIntervals();
273 efficiency = double(numIterations) / double(numIntervals);
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000274
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000275 // expire any remaining active intervals
276 for (IntervalPtrs::reverse_iterator
277 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000278 unsigned reg = i->first->reg;
279 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000280 assert(MRegisterInfo::isVirtualRegister(reg) &&
281 "Can only allocate virtual registers!");
282 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000283 prt_->delRegUse(reg);
284 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
285 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000286
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000287 // expire any remaining inactive intervals
288 for (IntervalPtrs::reverse_iterator
289 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000290 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000291 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
292 }
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000293
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000294 DEBUG(std::cerr << *vrm_);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000295}
296
Chris Lattnercbb56252004-11-18 02:42:27 +0000297/// processActiveIntervals - expire old intervals and move non-overlapping ones
298/// to the inactive list.
299void RA::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000300{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000301 DEBUG(std::cerr << "\tprocessing active intervals:\n");
Chris Lattner23b71c12004-11-18 01:29:39 +0000302
Chris Lattnercbb56252004-11-18 02:42:27 +0000303 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
304 LiveInterval *Interval = active_[i].first;
305 LiveInterval::iterator IntervalPos = active_[i].second;
306 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000307
Chris Lattnercbb56252004-11-18 02:42:27 +0000308 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
309
310 if (IntervalPos == Interval->end()) { // Remove expired intervals.
311 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000312 assert(MRegisterInfo::isVirtualRegister(reg) &&
313 "Can only allocate virtual registers!");
314 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000316
317 // Pop off the end of the list.
318 active_[i] = active_.back();
319 active_.pop_back();
320 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000321
Chris Lattnercbb56252004-11-18 02:42:27 +0000322 } else if (IntervalPos->start > CurPoint) {
323 // Move inactive intervals to inactive list.
324 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000325 assert(MRegisterInfo::isVirtualRegister(reg) &&
326 "Can only allocate virtual registers!");
327 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000328 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000329 // add to inactive.
330 inactive_.push_back(std::make_pair(Interval, IntervalPos));
331
332 // Pop off the end of the list.
333 active_[i] = active_.back();
334 active_.pop_back();
335 --i; --e;
336 } else {
337 // Otherwise, just update the iterator position.
338 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000339 }
340 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000341}
342
Chris Lattnercbb56252004-11-18 02:42:27 +0000343/// processInactiveIntervals - expire old intervals and move overlapping
344/// ones to the active list.
345void RA::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000346{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000347 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
Chris Lattner365b95f2004-11-18 04:13:02 +0000348
Chris Lattnercbb56252004-11-18 02:42:27 +0000349 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
350 LiveInterval *Interval = inactive_[i].first;
351 LiveInterval::iterator IntervalPos = inactive_[i].second;
352 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000353
Chris Lattnercbb56252004-11-18 02:42:27 +0000354 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000355
Chris Lattnercbb56252004-11-18 02:42:27 +0000356 if (IntervalPos == Interval->end()) { // remove expired intervals.
357 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000358
Chris Lattnercbb56252004-11-18 02:42:27 +0000359 // Pop off the end of the list.
360 inactive_[i] = inactive_.back();
361 inactive_.pop_back();
362 --i; --e;
363 } else if (IntervalPos->start <= CurPoint) {
364 // move re-activated intervals in active list
365 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000366 assert(MRegisterInfo::isVirtualRegister(reg) &&
367 "Can only allocate virtual registers!");
368 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 prt_->addRegUse(reg);
370 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000371 active_.push_back(std::make_pair(Interval, IntervalPos));
372
373 // Pop off the end of the list.
374 inactive_[i] = inactive_.back();
375 inactive_.pop_back();
376 --i; --e;
377 } else {
378 // Otherwise, just update the iterator position.
379 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000380 }
381 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000382}
383
Chris Lattnercbb56252004-11-18 02:42:27 +0000384/// updateSpillWeights - updates the spill weights of the specifed physical
385/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000386static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000387 unsigned reg, float weight,
388 const MRegisterInfo *MRI) {
389 Weights[reg] += weight;
390 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
391 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000392}
393
Chris Lattnercbb56252004-11-18 02:42:27 +0000394static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
395 LiveInterval *LI) {
396 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
397 if (I->first == LI) return I;
398 return IP.end();
399}
400
Chris Lattner19828d42004-11-18 03:49:30 +0000401static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
402 for (unsigned i = 0, e = V.size(); i != e; ++i) {
403 RA::IntervalPtr &IP = V[i];
404 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
405 IP.second, Point);
406 if (I != IP.first->begin()) --I;
407 IP.second = I;
408 }
409}
Chris Lattnercbb56252004-11-18 02:42:27 +0000410
Chris Lattnercbb56252004-11-18 02:42:27 +0000411/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
412/// spill.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000413void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000414{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000415 DEBUG(std::cerr << "\tallocating current interval: ");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000416
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000417 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000418
Chris Lattnera6c17502005-08-22 20:20:42 +0000419 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000420 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000421 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
422 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
423
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000424 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000425 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000426 for (IntervalPtrs::const_iterator i = inactive_.begin(),
427 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000428 unsigned Reg = i->first->reg;
429 assert(MRegisterInfo::isVirtualRegister(Reg) &&
430 "Can only allocate virtual registers!");
431 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
432 // If this is not in a related reg class to the register we're allocating,
433 // don't check it.
434 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
435 cur->overlapsFrom(*i->first, i->second-1)) {
436 Reg = vrm_->getPhys(Reg);
437 prt_->addRegUse(Reg);
438 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000439 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000440 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000441
442 // Speculatively check to see if we can get a register right now. If not,
443 // we know we won't be able to by adding more constraints. If so, we can
444 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
445 // is very bad (it contains all callee clobbered registers for any functions
446 // with a call), so we want to avoid doing that if possible.
447 unsigned physReg = getFreePhysReg(cur);
448 if (physReg) {
449 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000450 // conflict with it. Check to see if we conflict with it or any of its
451 // aliases.
452 std::set<unsigned> RegAliases;
453 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
454 RegAliases.insert(*AS);
455
Chris Lattnera411cbc2005-08-22 20:59:30 +0000456 bool ConflictsWithFixed = false;
457 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Chris Lattnere836ad62005-08-30 21:03:36 +0000458 if (physReg == fixed_[i].first->reg ||
459 RegAliases.count(fixed_[i].first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000460 // Okay, this reg is on the fixed list. Check to see if we actually
461 // conflict.
462 IntervalPtr &IP = fixed_[i];
463 LiveInterval *I = IP.first;
464 if (I->endNumber() > StartPosition) {
465 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
466 IP.second = II;
467 if (II != I->begin() && II->start > StartPosition)
468 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000469 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000470 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000471 break;
472 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000473 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000474 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000475 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000476
477 // Okay, the register picked by our speculative getFreePhysReg call turned
478 // out to be in use. Actually add all of the conflicting fixed registers to
479 // prt so we can do an accurate query.
480 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000481 // For every interval in fixed we overlap with, mark the register as not
482 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000483 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
484 IntervalPtr &IP = fixed_[i];
485 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000486
487 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
488 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
489 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000490 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
491 IP.second = II;
492 if (II != I->begin() && II->start > StartPosition)
493 --II;
494 if (cur->overlapsFrom(*I, II)) {
495 unsigned reg = I->reg;
496 prt_->addRegUse(reg);
497 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
498 }
499 }
500 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000501
Chris Lattnera411cbc2005-08-22 20:59:30 +0000502 // Using the newly updated prt_ object, which includes conflicts in the
503 // future, see if there are any registers available.
504 physReg = getFreePhysReg(cur);
505 }
506 }
507
Chris Lattnera6c17502005-08-22 20:20:42 +0000508 // Restore the physical register tracker, removing information about the
509 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000511
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000512 // if we find a free register, we are done: assign this virtual to
513 // the free physical register and add this interval to the active
514 // list.
515 if (physReg) {
516 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
517 vrm_->assignVirt2Phys(cur->reg, physReg);
518 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000519 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000520 handled_.push_back(cur);
521 return;
522 }
523 DEBUG(std::cerr << "no free registers\n");
524
Chris Lattnera6c17502005-08-22 20:20:42 +0000525 // Compile the spill weights into an array that is better for scanning.
526 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
527 for (std::vector<std::pair<unsigned, float> >::iterator
528 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
529 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
530
531 // for each interval in active, update spill weights.
532 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
533 i != e; ++i) {
534 unsigned reg = i->first->reg;
535 assert(MRegisterInfo::isVirtualRegister(reg) &&
536 "Can only allocate virtual registers!");
537 reg = vrm_->getPhys(reg);
538 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
539 }
540
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000541 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
542
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000543 // Find a register to spill.
Chris Lattner5e5fb942005-01-08 19:53:50 +0000544 float minWeight = float(HUGE_VAL);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545 unsigned minReg = 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000546 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
547 e = RC->allocation_order_end(*mf_); i != e; ++i) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000548 unsigned reg = *i;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000549 if (minWeight > SpillWeights[reg]) {
550 minWeight = SpillWeights[reg];
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000551 minReg = reg;
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000552 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000553 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000554
555 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000556 if (!minReg) {
557 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
558 e = RC->allocation_order_end(*mf_); i != e; ++i) {
559 unsigned reg = *i;
560 // No need to worry about if the alias register size < regsize of RC.
561 // We are going to spill all registers that alias it anyway.
562 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
563 if (minWeight > SpillWeights[*as]) {
564 minWeight = SpillWeights[*as];
565 minReg = *as;
566 }
567 }
568 }
569
570 // All registers must have inf weight. Just grab one!
571 if (!minReg)
572 minReg = *RC->allocation_order_begin(*mf_);
573 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000574
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000575 DEBUG(std::cerr << "\t\tregister with min weight: "
576 << mri_->getName(minReg) << " (" << minWeight << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000577
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000578 // if the current has the minimum weight, we need to spill it and
579 // add any added intervals back to unhandled, and restart
580 // linearscan.
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000581 if (cur->weight != float(HUGE_VAL) && cur->weight <= minWeight) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000582 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
583 int slot = vrm_->assignVirt2StackSlot(cur->reg);
584 std::vector<LiveInterval*> added =
585 li_->addIntervalsForSpills(*cur, *vrm_, slot);
586 if (added.empty())
587 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000588
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000589 // Merge added with unhandled. Note that we know that
590 // addIntervalsForSpills returns intervals sorted by their starting
591 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000592 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000593 unhandled_.push(added[i]);
594 return;
595 }
596
Chris Lattner19828d42004-11-18 03:49:30 +0000597 ++NumBacktracks;
598
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000599 // push the current interval back to unhandled since we are going
600 // to re-run at least this iteration. Since we didn't modify it it
601 // should go back right in the front of the list
602 unhandled_.push(cur);
603
604 // otherwise we spill all intervals aliasing the register with
605 // minimum weight, rollback to the interval with the earliest
606 // start point and let the linear scan algorithm run again
607 std::vector<LiveInterval*> added;
608 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
609 "did not choose a register to spill?");
610 std::vector<bool> toSpill(mri_->getNumRegs(), false);
Chris Lattner19828d42004-11-18 03:49:30 +0000611
612 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 toSpill[minReg] = true;
614 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
615 toSpill[*as] = true;
616
617 // the earliest start of a spilled interval indicates up to where
618 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000619 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000620
621 // set of spilled vregs (used later to rollback properly)
622 std::set<unsigned> spilled;
623
Chris Lattner19828d42004-11-18 03:49:30 +0000624 // spill live intervals of virtual regs mapped to the physical register we
625 // want to clear (and its aliases). We only spill those that overlap with the
626 // current interval as the rest do not affect its allocation. we also keep
627 // track of the earliest start of all spilled live intervals since this will
628 // mark our rollback point.
629 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000630 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000631 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000632 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000633 cur->overlapsFrom(*i->first, i->second)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000634 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
635 earliestStart = std::min(earliestStart, i->first->beginNumber());
636 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000637 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000638 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000639 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
640 spilled.insert(reg);
641 }
642 }
Chris Lattner19828d42004-11-18 03:49:30 +0000643 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000644 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000645 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000646 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000647 cur->overlapsFrom(*i->first, i->second-1)) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000648 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
649 earliestStart = std::min(earliestStart, i->first->beginNumber());
650 int slot = vrm_->assignVirt2StackSlot(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000651 std::vector<LiveInterval*> newIs =
Chris Lattnercbb56252004-11-18 02:42:27 +0000652 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000653 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
654 spilled.insert(reg);
655 }
656 }
657
658 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
Chris Lattnercbb56252004-11-18 02:42:27 +0000659
660 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000661 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000662 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000663 while (!handled_.empty()) {
664 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000665 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000666 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000667 break;
668 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
669 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000670
671 // When undoing a live interval allocation we must know if it is active or
672 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000673 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000674 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000675 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000676 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
677 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000678 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000679 prt_->delRegUse(vrm_->getPhys(i->reg));
680 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000681 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000682 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000683 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
684 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000685 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000686 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000687 } else {
688 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
689 "Can only allocate virtual registers!");
690 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000691 unhandled_.push(i);
692 }
693 }
694
Chris Lattner19828d42004-11-18 03:49:30 +0000695 // Rewind the iterators in the active, inactive, and fixed lists back to the
696 // point we reverted to.
697 RevertVectorIteratorsTo(active_, earliestStart);
698 RevertVectorIteratorsTo(inactive_, earliestStart);
699 RevertVectorIteratorsTo(fixed_, earliestStart);
700
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000701 // scan the rest and undo each interval that expired after t and
702 // insert it in active (the next iteration of the algorithm will
703 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000704 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
705 LiveInterval *HI = handled_[i];
706 if (!HI->expiredAt(earliestStart) &&
707 HI->expiredAt(cur->beginNumber())) {
708 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
709 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000710 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
711 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000712 }
713 }
714
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000715 // merge added with unhandled
716 for (unsigned i = 0, e = added.size(); i != e; ++i)
717 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000718}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000719
Chris Lattnercbb56252004-11-18 02:42:27 +0000720/// getFreePhysReg - return a free physical register for this virtual register
721/// interval if we have one, otherwise return 0.
Chris Lattnerffab4222006-02-23 06:44:17 +0000722unsigned RA::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000723 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000724 unsigned MaxInactiveCount = 0;
725
Chris Lattnerb9805782005-08-23 22:27:31 +0000726 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
727 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
728
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000729 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
730 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000731 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000732 assert(MRegisterInfo::isVirtualRegister(reg) &&
733 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000734
735 // If this is not in a related reg class to the register we're allocating,
736 // don't check it.
737 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
738 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
739 reg = vrm_->getPhys(reg);
740 ++inactiveCounts[reg];
741 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
742 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000743 }
744
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000745 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
Alkis Evlogimenos26bfc082003-12-28 17:58:18 +0000746
Chris Lattnerf8355d92005-08-22 16:55:22 +0000747 unsigned FreeReg = 0;
748 unsigned FreeRegInactiveCount = 0;
749
750 // Scan for the first available register.
751 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
752 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
753 for (; I != E; ++I)
754 if (prt_->isRegAvail(*I)) {
755 FreeReg = *I;
756 FreeRegInactiveCount = inactiveCounts[FreeReg];
757 break;
758 }
759
760 // If there are no free regs, or if this reg has the max inactive count,
761 // return this register.
762 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
763
764 // Continue scanning the registers, looking for the one with the highest
765 // inactive count. Alkis found that this reduced register pressure very
766 // slightly on X86 (in rev 1.94 of this file), though this should probably be
767 // reevaluated now.
768 for (; I != E; ++I) {
769 unsigned Reg = *I;
770 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
771 FreeReg = Reg;
772 FreeRegInactiveCount = inactiveCounts[Reg];
773 if (FreeRegInactiveCount == MaxInactiveCount)
774 break; // We found the one with the max inactive count.
775 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000776 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000777
778 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000779}
780
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000781FunctionPass* llvm::createLinearScanRegisterAllocator() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000782 return new RA();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000783}