blob: 6929b91645f9fee23e26522c932ab6fa07e5361b [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"
Evan Cheng2638e1a2007-03-20 08:13:50 +000015#include "llvm/CodeGen/LiveVariables.h"
Chris Lattner3c3fe462005-09-21 04:19:09 +000016#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000017#include "PhysRegTracker.h"
18#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000019#include "llvm/Function.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
22#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000023#include "llvm/CodeGen/RegAllocRegistry.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/SSARegMap.h"
25#include "llvm/Target/MRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000026#include "llvm/Target/TargetMachine.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000027#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000030#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000031#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000032#include <algorithm>
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>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Chris Lattnercd3245a2006-12-19 22:41:21 +000039STATISTIC(NumIters , "Number of iterations performed");
40STATISTIC(NumBacktracks, "Number of times we had to backtrack");
41
42static RegisterRegAlloc
43linearscanRegAlloc("linearscan", " linear scan register allocator",
44 createLinearScanRegisterAllocator);
45
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000046namespace {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000047 static unsigned numIterations = 0;
48 static unsigned numIntervals = 0;
Alkis Evlogimenosc1560952004-07-04 17:23:35 +000049
Bill Wendlinge23e00d2007-05-08 19:02:46 +000050 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000051 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000052 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000053
Chris Lattnercbb56252004-11-18 02:42:27 +000054 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
56 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000057 /// RelatedRegClasses - This structure is built the first time a function is
58 /// compiled, and keeps track of which register classes have registers that
59 /// belong to multiple classes or have aliases that are in other classes.
60 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
61 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
62
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000063 MachineFunction* mf_;
64 const TargetMachine* tm_;
65 const MRegisterInfo* mri_;
66 LiveIntervals* li_;
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>();
David Greene25133302007-06-08 17:18:56 +000099 AU.addRequiredID(SimpleRegisterCoalescingID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000100 MachineFunctionPass::getAnalysisUsage(AU);
101 }
102
103 /// runOnMachineFunction - register allocate the whole function
104 bool runOnMachineFunction(MachineFunction&);
105
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000106 private:
107 /// linearScan - the linear scan algorithm
108 void linearScan();
109
Chris Lattnercbb56252004-11-18 02:42:27 +0000110 /// initIntervalSets - initialize the interval sets.
111 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000112 void initIntervalSets();
113
Chris Lattnercbb56252004-11-18 02:42:27 +0000114 /// processActiveIntervals - expire old intervals and move non-overlapping
115 /// ones to the inactive list.
116 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000117
Chris Lattnercbb56252004-11-18 02:42:27 +0000118 /// processInactiveIntervals - expire old intervals and move overlapping
119 /// ones to the active list.
120 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000121
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000122 /// assignRegOrStackSlotAtInterval - assign a register if one
123 /// is available, or spill.
124 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
125
126 ///
127 /// register handling helpers
128 ///
129
Chris Lattnercbb56252004-11-18 02:42:27 +0000130 /// getFreePhysReg - return a free physical register for this virtual
131 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000132 unsigned getFreePhysReg(LiveInterval* cur);
133
134 /// assignVirt2StackSlot - assigns this virtual register to a
135 /// stack slot. returns the stack slot
136 int assignVirt2StackSlot(unsigned virtReg);
137
Chris Lattnerb9805782005-08-23 22:27:31 +0000138 void ComputeRelatedRegClasses();
139
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140 template <typename ItTy>
141 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000142 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000143 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000144 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000145 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000146 if (MRegisterInfo::isVirtualRegister(reg)) {
147 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000148 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000149 DOUT << mri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150 }
151 }
152 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000153 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000154}
155
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000156void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000157 const MRegisterInfo &MRI = *mri_;
158
159 // First pass, add all reg classes to the union, and determine at least one
160 // reg class that each register is in.
161 bool HasAliases = false;
162 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
163 E = MRI.regclass_end(); RCI != E; ++RCI) {
164 RelatedRegClasses.insert(*RCI);
165 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
166 I != E; ++I) {
167 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
168
169 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
170 if (PRC) {
171 // Already processed this register. Just make sure we know that
172 // multiple register classes share a register.
173 RelatedRegClasses.unionSets(PRC, *RCI);
174 } else {
175 PRC = *RCI;
176 }
177 }
178 }
179
180 // Second pass, now that we know conservatively what register classes each reg
181 // belongs to, add info about aliases. We don't need to do this for targets
182 // without register aliases.
183 if (HasAliases)
184 for (std::map<unsigned, const TargetRegisterClass*>::iterator
185 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
186 I != E; ++I)
187 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
188 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
189}
190
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000191bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000192 mf_ = &fn;
193 tm_ = &fn.getTarget();
194 mri_ = tm_->getRegisterInfo();
195 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000196
Chris Lattnerb9805782005-08-23 22:27:31 +0000197 // If this is the first function compiled, compute the related reg classes.
198 if (RelatedRegClasses.empty())
199 ComputeRelatedRegClasses();
200
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000201 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
202 vrm_.reset(new VirtRegMap(*mf_));
203 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000204
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000205 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000206
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000207 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000208
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000209 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000210 spiller_->runOnMachineFunction(*mf_, *vrm_);
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000211
Chris Lattner510a3ea2004-09-30 02:02:33 +0000212 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000213
214
215 while (!unhandled_.empty()) unhandled_.pop();
216 fixed_.clear();
217 active_.clear();
218 inactive_.clear();
219 handled_.clear();
220
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000221 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000222}
223
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000224/// initIntervalSets - initialize the interval sets.
225///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000226void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000227{
228 assert(unhandled_.empty() && fixed_.empty() &&
229 active_.empty() && inactive_.empty() &&
230 "interval sets should be empty on initialization");
231
232 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000233 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
Evan Cheng6c087e52007-04-25 22:13:27 +0000234 mf_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000235 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000236 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000237 unhandled_.push(&i->second);
238 }
239}
240
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000241void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000242{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000243 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000244 DOUT << "********** LINEAR SCAN **********\n";
245 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000246
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000247 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
248 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
249 DEBUG(printIntervals("active", active_.begin(), active_.end()));
250 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
251
252 while (!unhandled_.empty()) {
253 // pick the interval with the earliest start point
254 LiveInterval* cur = unhandled_.top();
255 unhandled_.pop();
256 ++numIterations;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000257 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000258
Chris Lattnercbb56252004-11-18 02:42:27 +0000259 processActiveIntervals(cur->beginNumber());
260 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000261
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000262 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
263 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000264
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000265 // Allocating a virtual register. try to find a free
266 // physical register or spill an interval (possibly this one) in order to
267 // assign it one.
268 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000269
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000270 DEBUG(printIntervals("active", active_.begin(), active_.end()));
271 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000272 }
273 numIntervals += li_->getNumIntervals();
Chris Lattner4c7e2272006-12-06 01:48:55 +0000274 NumIters += numIterations;
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000275
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000276 // expire any remaining active intervals
277 for (IntervalPtrs::reverse_iterator
278 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000279 unsigned reg = i->first->reg;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000280 DOUT << "\tinterval " << *i->first << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000281 assert(MRegisterInfo::isVirtualRegister(reg) &&
282 "Can only allocate virtual registers!");
283 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000284 prt_->delRegUse(reg);
285 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
286 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000287
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000288 // expire any remaining inactive intervals
289 for (IntervalPtrs::reverse_iterator
290 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000291 DOUT << "\tinterval " << *i->first << " expired\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000292 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
293 }
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000294
Evan Cheng9fc508f2007-02-16 09:05:02 +0000295 // A brute force way of adding live-ins to every BB.
Evan Chengb371f452007-02-19 21:49:54 +0000296 MachineFunction::iterator MBB = mf_->begin();
297 ++MBB; // Skip entry MBB.
298 for (MachineFunction::iterator E = mf_->end(); MBB != E; ++MBB) {
Evan Cheng9fc508f2007-02-16 09:05:02 +0000299 unsigned StartIdx = li_->getMBBStartIdx(MBB->getNumber());
300 for (IntervalPtrs::iterator i = fixed_.begin(), e = fixed_.end();
301 i != e; ++i)
302 if (i->first->liveAt(StartIdx))
303 MBB->addLiveIn(i->first->reg);
304
305 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
306 LiveInterval *HI = handled_[i];
Evan Chengbc025fb2007-02-25 09:39:02 +0000307 unsigned Reg = HI->reg;
Evan Cheng549f27d32007-08-13 23:45:17 +0000308 if (vrm_->isAssignedReg(Reg) && HI->liveAt(StartIdx)) {
Evan Chengbc025fb2007-02-25 09:39:02 +0000309 assert(MRegisterInfo::isVirtualRegister(Reg));
310 Reg = vrm_->getPhys(Reg);
Evan Cheng9fc508f2007-02-16 09:05:02 +0000311 MBB->addLiveIn(Reg);
312 }
313 }
314 }
315
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000316 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000317}
318
Chris Lattnercbb56252004-11-18 02:42:27 +0000319/// processActiveIntervals - expire old intervals and move non-overlapping ones
320/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000321void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000322{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000323 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000324
Chris Lattnercbb56252004-11-18 02:42:27 +0000325 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
326 LiveInterval *Interval = active_[i].first;
327 LiveInterval::iterator IntervalPos = active_[i].second;
328 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000329
Chris Lattnercbb56252004-11-18 02:42:27 +0000330 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
331
332 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000333 DOUT << "\t\tinterval " << *Interval << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000334 assert(MRegisterInfo::isVirtualRegister(reg) &&
335 "Can only allocate virtual registers!");
336 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000337 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000338
339 // Pop off the end of the list.
340 active_[i] = active_.back();
341 active_.pop_back();
342 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000343
Chris Lattnercbb56252004-11-18 02:42:27 +0000344 } else if (IntervalPos->start > CurPoint) {
345 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000346 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000347 assert(MRegisterInfo::isVirtualRegister(reg) &&
348 "Can only allocate virtual registers!");
349 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000351 // add to inactive.
352 inactive_.push_back(std::make_pair(Interval, IntervalPos));
353
354 // Pop off the end of the list.
355 active_[i] = active_.back();
356 active_.pop_back();
357 --i; --e;
358 } else {
359 // Otherwise, just update the iterator position.
360 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361 }
362 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000363}
364
Chris Lattnercbb56252004-11-18 02:42:27 +0000365/// processInactiveIntervals - expire old intervals and move overlapping
366/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000367void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000368{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000369 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000370
Chris Lattnercbb56252004-11-18 02:42:27 +0000371 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
372 LiveInterval *Interval = inactive_[i].first;
373 LiveInterval::iterator IntervalPos = inactive_[i].second;
374 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000375
Chris Lattnercbb56252004-11-18 02:42:27 +0000376 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000377
Chris Lattnercbb56252004-11-18 02:42:27 +0000378 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000379 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000380
Chris Lattnercbb56252004-11-18 02:42:27 +0000381 // Pop off the end of the list.
382 inactive_[i] = inactive_.back();
383 inactive_.pop_back();
384 --i; --e;
385 } else if (IntervalPos->start <= CurPoint) {
386 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000387 DOUT << "\t\tinterval " << *Interval << " active\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000388 assert(MRegisterInfo::isVirtualRegister(reg) &&
389 "Can only allocate virtual registers!");
390 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000391 prt_->addRegUse(reg);
392 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000393 active_.push_back(std::make_pair(Interval, IntervalPos));
394
395 // Pop off the end of the list.
396 inactive_[i] = inactive_.back();
397 inactive_.pop_back();
398 --i; --e;
399 } else {
400 // Otherwise, just update the iterator position.
401 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000402 }
403 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000404}
405
Chris Lattnercbb56252004-11-18 02:42:27 +0000406/// updateSpillWeights - updates the spill weights of the specifed physical
407/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000408static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000409 unsigned reg, float weight,
410 const MRegisterInfo *MRI) {
411 Weights[reg] += weight;
412 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
413 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000414}
415
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000416static
417RALinScan::IntervalPtrs::iterator
418FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
419 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
420 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000421 if (I->first == LI) return I;
422 return IP.end();
423}
424
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000425static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000426 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000427 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000428 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
429 IP.second, Point);
430 if (I != IP.first->begin()) --I;
431 IP.second = I;
432 }
433}
Chris Lattnercbb56252004-11-18 02:42:27 +0000434
Chris Lattnercbb56252004-11-18 02:42:27 +0000435/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
436/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000437void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000438{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000439 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000440
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000442
Chris Lattnera6c17502005-08-22 20:20:42 +0000443 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000444 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000445 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
446 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
447
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000449 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000450 for (IntervalPtrs::const_iterator i = inactive_.begin(),
451 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000452 unsigned Reg = i->first->reg;
453 assert(MRegisterInfo::isVirtualRegister(Reg) &&
454 "Can only allocate virtual registers!");
455 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
456 // If this is not in a related reg class to the register we're allocating,
457 // don't check it.
458 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
459 cur->overlapsFrom(*i->first, i->second-1)) {
460 Reg = vrm_->getPhys(Reg);
461 prt_->addRegUse(Reg);
462 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000463 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000464 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000465
466 // Speculatively check to see if we can get a register right now. If not,
467 // we know we won't be able to by adding more constraints. If so, we can
468 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
469 // is very bad (it contains all callee clobbered registers for any functions
470 // with a call), so we want to avoid doing that if possible.
471 unsigned physReg = getFreePhysReg(cur);
472 if (physReg) {
473 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000474 // conflict with it. Check to see if we conflict with it or any of its
475 // aliases.
476 std::set<unsigned> RegAliases;
477 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
478 RegAliases.insert(*AS);
479
Chris Lattnera411cbc2005-08-22 20:59:30 +0000480 bool ConflictsWithFixed = false;
481 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000482 IntervalPtr &IP = fixed_[i];
483 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000484 // Okay, this reg is on the fixed list. Check to see if we actually
485 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000486 LiveInterval *I = IP.first;
487 if (I->endNumber() > StartPosition) {
488 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
489 IP.second = II;
490 if (II != I->begin() && II->start > StartPosition)
491 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000492 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000493 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000494 break;
495 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000496 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000497 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000498 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000499
500 // Okay, the register picked by our speculative getFreePhysReg call turned
501 // out to be in use. Actually add all of the conflicting fixed registers to
502 // prt so we can do an accurate query.
503 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000504 // For every interval in fixed we overlap with, mark the register as not
505 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000506 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
507 IntervalPtr &IP = fixed_[i];
508 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000509
510 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
511 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
512 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000513 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
514 IP.second = II;
515 if (II != I->begin() && II->start > StartPosition)
516 --II;
517 if (cur->overlapsFrom(*I, II)) {
518 unsigned reg = I->reg;
519 prt_->addRegUse(reg);
520 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
521 }
522 }
523 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000524
Chris Lattnera411cbc2005-08-22 20:59:30 +0000525 // Using the newly updated prt_ object, which includes conflicts in the
526 // future, see if there are any registers available.
527 physReg = getFreePhysReg(cur);
528 }
529 }
530
Chris Lattnera6c17502005-08-22 20:20:42 +0000531 // Restore the physical register tracker, removing information about the
532 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000533 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000534
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000535 // if we find a free register, we are done: assign this virtual to
536 // the free physical register and add this interval to the active
537 // list.
538 if (physReg) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000539 DOUT << mri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 vrm_->assignVirt2Phys(cur->reg, physReg);
541 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000542 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 handled_.push_back(cur);
544 return;
545 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000546 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000547
Chris Lattnera6c17502005-08-22 20:20:42 +0000548 // Compile the spill weights into an array that is better for scanning.
549 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
550 for (std::vector<std::pair<unsigned, float> >::iterator
551 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
552 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
553
554 // for each interval in active, update spill weights.
555 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
556 i != e; ++i) {
557 unsigned reg = i->first->reg;
558 assert(MRegisterInfo::isVirtualRegister(reg) &&
559 "Can only allocate virtual registers!");
560 reg = vrm_->getPhys(reg);
561 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
562 }
563
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000564 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000565
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000566 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000567 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000568 unsigned minReg = cur->preference; // Try the preferred register first.
569
570 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
571 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
572 e = RC->allocation_order_end(*mf_); i != e; ++i) {
573 unsigned reg = *i;
574 if (minWeight > SpillWeights[reg]) {
575 minWeight = SpillWeights[reg];
576 minReg = reg;
577 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000578 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000579
580 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000581 if (!minReg) {
582 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
583 e = RC->allocation_order_end(*mf_); i != e; ++i) {
584 unsigned reg = *i;
585 // No need to worry about if the alias register size < regsize of RC.
586 // We are going to spill all registers that alias it anyway.
587 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
588 if (minWeight > SpillWeights[*as]) {
589 minWeight = SpillWeights[*as];
590 minReg = *as;
591 }
592 }
593 }
594
595 // All registers must have inf weight. Just grab one!
596 if (!minReg)
597 minReg = *RC->allocation_order_begin(*mf_);
598 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000599
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000600 DOUT << "\t\tregister with min weight: "
601 << mri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000602
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000603 // if the current has the minimum weight, we need to spill it and
604 // add any added intervals back to unhandled, and restart
605 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000606 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000607 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000608 std::vector<LiveInterval*> added =
Evan Cheng549f27d32007-08-13 23:45:17 +0000609 li_->addIntervalsForSpills(*cur, *vrm_, cur->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000610 if (added.empty())
611 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000612
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 // Merge added with unhandled. Note that we know that
614 // addIntervalsForSpills returns intervals sorted by their starting
615 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000616 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000617 unhandled_.push(added[i]);
618 return;
619 }
620
Chris Lattner19828d42004-11-18 03:49:30 +0000621 ++NumBacktracks;
622
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000623 // push the current interval back to unhandled since we are going
624 // to re-run at least this iteration. Since we didn't modify it it
625 // should go back right in the front of the list
626 unhandled_.push(cur);
627
628 // otherwise we spill all intervals aliasing the register with
629 // minimum weight, rollback to the interval with the earliest
630 // start point and let the linear scan algorithm run again
631 std::vector<LiveInterval*> added;
632 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
633 "did not choose a register to spill?");
Evan Cheng2638e1a2007-03-20 08:13:50 +0000634 BitVector toSpill(mri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000635
636 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000637 toSpill[minReg] = true;
638 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
639 toSpill[*as] = true;
640
641 // the earliest start of a spilled interval indicates up to where
642 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000643 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000644
645 // set of spilled vregs (used later to rollback properly)
646 std::set<unsigned> spilled;
647
Chris Lattner19828d42004-11-18 03:49:30 +0000648 // spill live intervals of virtual regs mapped to the physical register we
649 // want to clear (and its aliases). We only spill those that overlap with the
650 // current interval as the rest do not affect its allocation. we also keep
651 // track of the earliest start of all spilled live intervals since this will
652 // mark our rollback point.
653 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000654 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000655 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000656 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000657 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000658 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000659 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000660 std::vector<LiveInterval*> newIs =
Evan Cheng549f27d32007-08-13 23:45:17 +0000661 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000662 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
663 spilled.insert(reg);
664 }
665 }
Chris Lattner19828d42004-11-18 03:49:30 +0000666 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000667 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000668 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000669 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000670 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000671 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000672 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000673 std::vector<LiveInterval*> newIs =
Evan Cheng549f27d32007-08-13 23:45:17 +0000674 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000675 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
676 spilled.insert(reg);
677 }
678 }
679
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000680 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000681
682 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000683 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000684 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000685 while (!handled_.empty()) {
686 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000687 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000688 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000689 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000690 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000691 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000692
693 // When undoing a live interval allocation we must know if it is active or
694 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000695 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000696 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000697 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000698 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
699 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000700 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000701 prt_->delRegUse(vrm_->getPhys(i->reg));
702 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000703 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000704 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000705 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
706 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000707 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000708 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000709 } else {
710 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
711 "Can only allocate virtual registers!");
712 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000713 unhandled_.push(i);
714 }
715 }
716
Chris Lattner19828d42004-11-18 03:49:30 +0000717 // Rewind the iterators in the active, inactive, and fixed lists back to the
718 // point we reverted to.
719 RevertVectorIteratorsTo(active_, earliestStart);
720 RevertVectorIteratorsTo(inactive_, earliestStart);
721 RevertVectorIteratorsTo(fixed_, earliestStart);
722
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000723 // scan the rest and undo each interval that expired after t and
724 // insert it in active (the next iteration of the algorithm will
725 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000726 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
727 LiveInterval *HI = handled_[i];
728 if (!HI->expiredAt(earliestStart) &&
729 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000730 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000731 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000732 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
733 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000734 }
735 }
736
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000737 // merge added with unhandled
738 for (unsigned i = 0, e = added.size(); i != e; ++i)
739 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000740}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000741
Chris Lattnercbb56252004-11-18 02:42:27 +0000742/// getFreePhysReg - return a free physical register for this virtual register
743/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000744unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000745 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000746 unsigned MaxInactiveCount = 0;
747
Chris Lattnerb9805782005-08-23 22:27:31 +0000748 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
749 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
750
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000751 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
752 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000753 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000754 assert(MRegisterInfo::isVirtualRegister(reg) &&
755 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000756
757 // If this is not in a related reg class to the register we're allocating,
758 // don't check it.
759 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
760 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
761 reg = vrm_->getPhys(reg);
762 ++inactiveCounts[reg];
763 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
764 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000765 }
766
Chris Lattnerf8355d92005-08-22 16:55:22 +0000767 unsigned FreeReg = 0;
768 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000769
770 // If copy coalescer has assigned a "preferred" register, check if it's
771 // available first.
772 if (cur->preference)
773 if (prt_->isRegAvail(cur->preference)) {
774 DOUT << "\t\tassigned the preferred register: "
775 << mri_->getName(cur->preference) << "\n";
776 return cur->preference;
777 } else
778 DOUT << "\t\tunable to assign the preferred register: "
779 << mri_->getName(cur->preference) << "\n";
780
Chris Lattnerf8355d92005-08-22 16:55:22 +0000781 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000782 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
783 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000784 for (; I != E; ++I)
785 if (prt_->isRegAvail(*I)) {
786 FreeReg = *I;
787 FreeRegInactiveCount = inactiveCounts[FreeReg];
788 break;
789 }
790
791 // If there are no free regs, or if this reg has the max inactive count,
792 // return this register.
793 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
794
795 // Continue scanning the registers, looking for the one with the highest
796 // inactive count. Alkis found that this reduced register pressure very
797 // slightly on X86 (in rev 1.94 of this file), though this should probably be
798 // reevaluated now.
799 for (; I != E; ++I) {
800 unsigned Reg = *I;
801 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
802 FreeReg = Reg;
803 FreeRegInactiveCount = inactiveCounts[Reg];
804 if (FreeRegInactiveCount == MaxInactiveCount)
805 break; // We found the one with the max inactive count.
806 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000807 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000808
809 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000810}
811
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000812FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000813 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000814}