blob: 025de81aa934a7e1f22f8315cbb67f886542f2fd [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"
David Greene2c17c4d2007-09-06 16:18:45 +000023#include "llvm/CodeGen/RegisterCoalescer.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 Greene2c17c4d2007-09-06 16:18:45 +000099 // Make sure PassManager knows which analyses to make available
100 // to coalescing and which analyses coalescing invalidates.
101 AU.addRequiredTransitive<RegisterCoalescer>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000102 MachineFunctionPass::getAnalysisUsage(AU);
103 }
104
105 /// runOnMachineFunction - register allocate the whole function
106 bool runOnMachineFunction(MachineFunction&);
107
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000108 private:
109 /// linearScan - the linear scan algorithm
110 void linearScan();
111
Chris Lattnercbb56252004-11-18 02:42:27 +0000112 /// initIntervalSets - initialize the interval sets.
113 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000114 void initIntervalSets();
115
Chris Lattnercbb56252004-11-18 02:42:27 +0000116 /// processActiveIntervals - expire old intervals and move non-overlapping
117 /// ones to the inactive list.
118 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119
Chris Lattnercbb56252004-11-18 02:42:27 +0000120 /// processInactiveIntervals - expire old intervals and move overlapping
121 /// ones to the active list.
122 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000123
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000124 /// assignRegOrStackSlotAtInterval - assign a register if one
125 /// is available, or spill.
126 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
127
128 ///
129 /// register handling helpers
130 ///
131
Chris Lattnercbb56252004-11-18 02:42:27 +0000132 /// getFreePhysReg - return a free physical register for this virtual
133 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000134 unsigned getFreePhysReg(LiveInterval* cur);
135
136 /// assignVirt2StackSlot - assigns this virtual register to a
137 /// stack slot. returns the stack slot
138 int assignVirt2StackSlot(unsigned virtReg);
139
Chris Lattnerb9805782005-08-23 22:27:31 +0000140 void ComputeRelatedRegClasses();
141
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000142 template <typename ItTy>
143 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000144 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000145 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000146 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000147 unsigned reg = i->first->reg;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000148 if (MRegisterInfo::isVirtualRegister(reg)) {
149 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000150 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000151 DOUT << mri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000152 }
153 }
154 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000155 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000156}
157
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000158void RALinScan::ComputeRelatedRegClasses() {
Chris Lattnerb9805782005-08-23 22:27:31 +0000159 const MRegisterInfo &MRI = *mri_;
160
161 // First pass, add all reg classes to the union, and determine at least one
162 // reg class that each register is in.
163 bool HasAliases = false;
164 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
165 E = MRI.regclass_end(); RCI != E; ++RCI) {
166 RelatedRegClasses.insert(*RCI);
167 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
168 I != E; ++I) {
169 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
170
171 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
172 if (PRC) {
173 // Already processed this register. Just make sure we know that
174 // multiple register classes share a register.
175 RelatedRegClasses.unionSets(PRC, *RCI);
176 } else {
177 PRC = *RCI;
178 }
179 }
180 }
181
182 // Second pass, now that we know conservatively what register classes each reg
183 // belongs to, add info about aliases. We don't need to do this for targets
184 // without register aliases.
185 if (HasAliases)
186 for (std::map<unsigned, const TargetRegisterClass*>::iterator
187 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
188 I != E; ++I)
189 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
190 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
191}
192
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000193bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000194 mf_ = &fn;
195 tm_ = &fn.getTarget();
196 mri_ = tm_->getRegisterInfo();
197 li_ = &getAnalysis<LiveIntervals>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000198
David Greene2c17c4d2007-09-06 16:18:45 +0000199 // We don't run the coalescer here because we have no reason to
200 // interact with it. If the coalescer requires interaction, it
201 // won't do anything. If it doesn't require interaction, we assume
202 // it was run as a separate pass.
203
Chris Lattnerb9805782005-08-23 22:27:31 +0000204 // If this is the first function compiled, compute the related reg classes.
205 if (RelatedRegClasses.empty())
206 ComputeRelatedRegClasses();
207
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000208 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
209 vrm_.reset(new VirtRegMap(*mf_));
210 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000211
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000212 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000213
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000214 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000215
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000216 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000217 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000218 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000219
Chris Lattnercbb56252004-11-18 02:42:27 +0000220 while (!unhandled_.empty()) unhandled_.pop();
221 fixed_.clear();
222 active_.clear();
223 inactive_.clear();
224 handled_.clear();
225
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000226 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000227}
228
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000229/// initIntervalSets - initialize the interval sets.
230///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000231void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000232{
233 assert(unhandled_.empty() && fixed_.empty() &&
234 active_.empty() && inactive_.empty() &&
235 "interval sets should be empty on initialization");
236
237 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000238 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
Evan Cheng6c087e52007-04-25 22:13:27 +0000239 mf_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000240 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000241 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000242 unhandled_.push(&i->second);
243 }
244}
245
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000246void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000247{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000248 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000249 DOUT << "********** LINEAR SCAN **********\n";
250 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000251
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
253 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
254 DEBUG(printIntervals("active", active_.begin(), active_.end()));
255 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
256
257 while (!unhandled_.empty()) {
258 // pick the interval with the earliest start point
259 LiveInterval* cur = unhandled_.top();
260 unhandled_.pop();
261 ++numIterations;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000262 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000263
Chris Lattnercbb56252004-11-18 02:42:27 +0000264 processActiveIntervals(cur->beginNumber());
265 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000266
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000267 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
268 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000269
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000270 // Allocating a virtual register. try to find a free
271 // physical register or spill an interval (possibly this one) in order to
272 // assign it one.
273 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000274
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000275 DEBUG(printIntervals("active", active_.begin(), active_.end()));
276 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000277 }
278 numIntervals += li_->getNumIntervals();
Chris Lattner4c7e2272006-12-06 01:48:55 +0000279 NumIters += numIterations;
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000280
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 // expire any remaining active intervals
282 for (IntervalPtrs::reverse_iterator
283 i = active_.rbegin(); i != active_.rend(); ) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000284 unsigned reg = i->first->reg;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000285 DOUT << "\tinterval " << *i->first << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000286 assert(MRegisterInfo::isVirtualRegister(reg) &&
287 "Can only allocate virtual registers!");
288 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000289 prt_->delRegUse(reg);
290 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
291 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000292
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000293 // expire any remaining inactive intervals
294 for (IntervalPtrs::reverse_iterator
295 i = inactive_.rbegin(); i != inactive_.rend(); ) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000296 DOUT << "\tinterval " << *i->first << " expired\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000297 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
298 }
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000299
Evan Cheng9fc508f2007-02-16 09:05:02 +0000300 // A brute force way of adding live-ins to every BB.
Evan Chengb371f452007-02-19 21:49:54 +0000301 MachineFunction::iterator MBB = mf_->begin();
302 ++MBB; // Skip entry MBB.
303 for (MachineFunction::iterator E = mf_->end(); MBB != E; ++MBB) {
Evan Cheng9fc508f2007-02-16 09:05:02 +0000304 unsigned StartIdx = li_->getMBBStartIdx(MBB->getNumber());
305 for (IntervalPtrs::iterator i = fixed_.begin(), e = fixed_.end();
306 i != e; ++i)
307 if (i->first->liveAt(StartIdx))
308 MBB->addLiveIn(i->first->reg);
309
310 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
311 LiveInterval *HI = handled_[i];
Evan Chengbc025fb2007-02-25 09:39:02 +0000312 unsigned Reg = HI->reg;
Evan Cheng549f27d32007-08-13 23:45:17 +0000313 if (vrm_->isAssignedReg(Reg) && HI->liveAt(StartIdx)) {
Evan Chengbc025fb2007-02-25 09:39:02 +0000314 assert(MRegisterInfo::isVirtualRegister(Reg));
315 Reg = vrm_->getPhys(Reg);
Evan Cheng9fc508f2007-02-16 09:05:02 +0000316 MBB->addLiveIn(Reg);
317 }
318 }
319 }
320
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000321 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000322}
323
Chris Lattnercbb56252004-11-18 02:42:27 +0000324/// processActiveIntervals - expire old intervals and move non-overlapping ones
325/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000326void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000327{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000328 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000329
Chris Lattnercbb56252004-11-18 02:42:27 +0000330 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
331 LiveInterval *Interval = active_[i].first;
332 LiveInterval::iterator IntervalPos = active_[i].second;
333 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000334
Chris Lattnercbb56252004-11-18 02:42:27 +0000335 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
336
337 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000338 DOUT << "\t\tinterval " << *Interval << " expired\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000339 assert(MRegisterInfo::isVirtualRegister(reg) &&
340 "Can only allocate virtual registers!");
341 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000342 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000343
344 // Pop off the end of the list.
345 active_[i] = active_.back();
346 active_.pop_back();
347 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000348
Chris Lattnercbb56252004-11-18 02:42:27 +0000349 } else if (IntervalPos->start > CurPoint) {
350 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000351 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000352 assert(MRegisterInfo::isVirtualRegister(reg) &&
353 "Can only allocate virtual registers!");
354 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000355 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000356 // add to inactive.
357 inactive_.push_back(std::make_pair(Interval, IntervalPos));
358
359 // Pop off the end of the list.
360 active_[i] = active_.back();
361 active_.pop_back();
362 --i; --e;
363 } else {
364 // Otherwise, just update the iterator position.
365 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366 }
367 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000368}
369
Chris Lattnercbb56252004-11-18 02:42:27 +0000370/// processInactiveIntervals - expire old intervals and move overlapping
371/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000372void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000373{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000374 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000375
Chris Lattnercbb56252004-11-18 02:42:27 +0000376 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
377 LiveInterval *Interval = inactive_[i].first;
378 LiveInterval::iterator IntervalPos = inactive_[i].second;
379 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000380
Chris Lattnercbb56252004-11-18 02:42:27 +0000381 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000382
Chris Lattnercbb56252004-11-18 02:42:27 +0000383 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000384 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000385
Chris Lattnercbb56252004-11-18 02:42:27 +0000386 // Pop off the end of the list.
387 inactive_[i] = inactive_.back();
388 inactive_.pop_back();
389 --i; --e;
390 } else if (IntervalPos->start <= CurPoint) {
391 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000392 DOUT << "\t\tinterval " << *Interval << " active\n";
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000393 assert(MRegisterInfo::isVirtualRegister(reg) &&
394 "Can only allocate virtual registers!");
395 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 prt_->addRegUse(reg);
397 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000398 active_.push_back(std::make_pair(Interval, IntervalPos));
399
400 // Pop off the end of the list.
401 inactive_[i] = inactive_.back();
402 inactive_.pop_back();
403 --i; --e;
404 } else {
405 // Otherwise, just update the iterator position.
406 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000407 }
408 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000409}
410
Chris Lattnercbb56252004-11-18 02:42:27 +0000411/// updateSpillWeights - updates the spill weights of the specifed physical
412/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000413static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000414 unsigned reg, float weight,
415 const MRegisterInfo *MRI) {
416 Weights[reg] += weight;
417 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
418 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000419}
420
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000421static
422RALinScan::IntervalPtrs::iterator
423FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
424 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
425 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000426 if (I->first == LI) return I;
427 return IP.end();
428}
429
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000430static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000431 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000432 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000433 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
434 IP.second, Point);
435 if (I != IP.first->begin()) --I;
436 IP.second = I;
437 }
438}
Chris Lattnercbb56252004-11-18 02:42:27 +0000439
Chris Lattnercbb56252004-11-18 02:42:27 +0000440/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
441/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000442void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000443{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000444 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000445
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000447
Chris Lattnera6c17502005-08-22 20:20:42 +0000448 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000449 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000450 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
451 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
452
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000454 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 for (IntervalPtrs::const_iterator i = inactive_.begin(),
456 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000457 unsigned Reg = i->first->reg;
458 assert(MRegisterInfo::isVirtualRegister(Reg) &&
459 "Can only allocate virtual registers!");
460 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
461 // If this is not in a related reg class to the register we're allocating,
462 // don't check it.
463 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
464 cur->overlapsFrom(*i->first, i->second-1)) {
465 Reg = vrm_->getPhys(Reg);
466 prt_->addRegUse(Reg);
467 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000468 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000469 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000470
471 // Speculatively check to see if we can get a register right now. If not,
472 // we know we won't be able to by adding more constraints. If so, we can
473 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
474 // is very bad (it contains all callee clobbered registers for any functions
475 // with a call), so we want to avoid doing that if possible.
476 unsigned physReg = getFreePhysReg(cur);
477 if (physReg) {
478 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000479 // conflict with it. Check to see if we conflict with it or any of its
480 // aliases.
481 std::set<unsigned> RegAliases;
482 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
483 RegAliases.insert(*AS);
484
Chris Lattnera411cbc2005-08-22 20:59:30 +0000485 bool ConflictsWithFixed = false;
486 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000487 IntervalPtr &IP = fixed_[i];
488 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000489 // Okay, this reg is on the fixed list. Check to see if we actually
490 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000491 LiveInterval *I = IP.first;
492 if (I->endNumber() > StartPosition) {
493 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
494 IP.second = II;
495 if (II != I->begin() && II->start > StartPosition)
496 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000497 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000498 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000499 break;
500 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000501 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000502 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000503 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000504
505 // Okay, the register picked by our speculative getFreePhysReg call turned
506 // out to be in use. Actually add all of the conflicting fixed registers to
507 // prt so we can do an accurate query.
508 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000509 // For every interval in fixed we overlap with, mark the register as not
510 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000511 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
512 IntervalPtr &IP = fixed_[i];
513 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000514
515 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
516 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
517 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000518 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
519 IP.second = II;
520 if (II != I->begin() && II->start > StartPosition)
521 --II;
522 if (cur->overlapsFrom(*I, II)) {
523 unsigned reg = I->reg;
524 prt_->addRegUse(reg);
525 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
526 }
527 }
528 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000529
Chris Lattnera411cbc2005-08-22 20:59:30 +0000530 // Using the newly updated prt_ object, which includes conflicts in the
531 // future, see if there are any registers available.
532 physReg = getFreePhysReg(cur);
533 }
534 }
535
Chris Lattnera6c17502005-08-22 20:20:42 +0000536 // Restore the physical register tracker, removing information about the
537 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000538 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000539
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 // if we find a free register, we are done: assign this virtual to
541 // the free physical register and add this interval to the active
542 // list.
543 if (physReg) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000544 DOUT << mri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545 vrm_->assignVirt2Phys(cur->reg, physReg);
546 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000547 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000548 handled_.push_back(cur);
549 return;
550 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000551 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552
Chris Lattnera6c17502005-08-22 20:20:42 +0000553 // Compile the spill weights into an array that is better for scanning.
554 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
555 for (std::vector<std::pair<unsigned, float> >::iterator
556 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
557 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
558
559 // for each interval in active, update spill weights.
560 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
561 i != e; ++i) {
562 unsigned reg = i->first->reg;
563 assert(MRegisterInfo::isVirtualRegister(reg) &&
564 "Can only allocate virtual registers!");
565 reg = vrm_->getPhys(reg);
566 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
567 }
568
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000569 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000570
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000571 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000572 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000573 unsigned minReg = cur->preference; // Try the preferred register first.
574
575 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
576 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
577 e = RC->allocation_order_end(*mf_); i != e; ++i) {
578 unsigned reg = *i;
579 if (minWeight > SpillWeights[reg]) {
580 minWeight = SpillWeights[reg];
581 minReg = reg;
582 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000583 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000584
585 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000586 if (!minReg) {
587 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
588 e = RC->allocation_order_end(*mf_); i != e; ++i) {
589 unsigned reg = *i;
590 // No need to worry about if the alias register size < regsize of RC.
591 // We are going to spill all registers that alias it anyway.
592 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
593 if (minWeight > SpillWeights[*as]) {
594 minWeight = SpillWeights[*as];
595 minReg = *as;
596 }
597 }
598 }
599
600 // All registers must have inf weight. Just grab one!
601 if (!minReg)
602 minReg = *RC->allocation_order_begin(*mf_);
603 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000604
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000605 DOUT << "\t\tregister with min weight: "
606 << mri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000607
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000608 // if the current has the minimum weight, we need to spill it and
609 // add any added intervals back to unhandled, and restart
610 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000611 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000612 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 std::vector<LiveInterval*> added =
Evan Cheng549f27d32007-08-13 23:45:17 +0000614 li_->addIntervalsForSpills(*cur, *vrm_, cur->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000615 if (added.empty())
616 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000617
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000618 // Merge added with unhandled. Note that we know that
619 // addIntervalsForSpills returns intervals sorted by their starting
620 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000621 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000622 unhandled_.push(added[i]);
623 return;
624 }
625
Chris Lattner19828d42004-11-18 03:49:30 +0000626 ++NumBacktracks;
627
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000628 // push the current interval back to unhandled since we are going
629 // to re-run at least this iteration. Since we didn't modify it it
630 // should go back right in the front of the list
631 unhandled_.push(cur);
632
633 // otherwise we spill all intervals aliasing the register with
634 // minimum weight, rollback to the interval with the earliest
635 // start point and let the linear scan algorithm run again
636 std::vector<LiveInterval*> added;
637 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
638 "did not choose a register to spill?");
Evan Cheng2638e1a2007-03-20 08:13:50 +0000639 BitVector toSpill(mri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000640
641 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000642 toSpill[minReg] = true;
643 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
644 toSpill[*as] = true;
645
646 // the earliest start of a spilled interval indicates up to where
647 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000648 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000649
650 // set of spilled vregs (used later to rollback properly)
651 std::set<unsigned> spilled;
652
Chris Lattner19828d42004-11-18 03:49:30 +0000653 // spill live intervals of virtual regs mapped to the physical register we
654 // want to clear (and its aliases). We only spill those that overlap with the
655 // current interval as the rest do not affect its allocation. we also keep
656 // track of the earliest start of all spilled live intervals since this will
657 // mark our rollback point.
658 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000659 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000660 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000661 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000662 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000663 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000664 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000665 std::vector<LiveInterval*> newIs =
Evan Cheng549f27d32007-08-13 23:45:17 +0000666 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000667 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
668 spilled.insert(reg);
669 }
670 }
Chris Lattner19828d42004-11-18 03:49:30 +0000671 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000672 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000673 if (//MRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000674 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000675 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000676 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000677 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000678 std::vector<LiveInterval*> newIs =
Evan Cheng549f27d32007-08-13 23:45:17 +0000679 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000680 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
681 spilled.insert(reg);
682 }
683 }
684
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000685 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000686
687 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000688 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000689 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000690 while (!handled_.empty()) {
691 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000692 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000693 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000694 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000695 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000696 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000697
698 // When undoing a live interval allocation we must know if it is active or
699 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000700 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000701 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000702 active_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000703 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
704 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000705 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000706 prt_->delRegUse(vrm_->getPhys(i->reg));
707 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000708 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000709 inactive_.erase(it);
Chris Lattnerffab4222006-02-23 06:44:17 +0000710 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
711 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000712 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000713 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000714 } else {
715 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
716 "Can only allocate virtual registers!");
717 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000718 unhandled_.push(i);
719 }
720 }
721
Chris Lattner19828d42004-11-18 03:49:30 +0000722 // Rewind the iterators in the active, inactive, and fixed lists back to the
723 // point we reverted to.
724 RevertVectorIteratorsTo(active_, earliestStart);
725 RevertVectorIteratorsTo(inactive_, earliestStart);
726 RevertVectorIteratorsTo(fixed_, earliestStart);
727
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000728 // scan the rest and undo each interval that expired after t and
729 // insert it in active (the next iteration of the algorithm will
730 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000731 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
732 LiveInterval *HI = handled_[i];
733 if (!HI->expiredAt(earliestStart) &&
734 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000735 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000736 active_.push_back(std::make_pair(HI, HI->begin()));
Chris Lattnerffab4222006-02-23 06:44:17 +0000737 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
738 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000739 }
740 }
741
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000742 // merge added with unhandled
743 for (unsigned i = 0, e = added.size(); i != e; ++i)
744 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000745}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000746
Chris Lattnercbb56252004-11-18 02:42:27 +0000747/// getFreePhysReg - return a free physical register for this virtual register
748/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000749unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000750 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000751 unsigned MaxInactiveCount = 0;
752
Chris Lattnerb9805782005-08-23 22:27:31 +0000753 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
754 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
755
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000756 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
757 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000758 unsigned reg = i->first->reg;
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000759 assert(MRegisterInfo::isVirtualRegister(reg) &&
760 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000761
762 // If this is not in a related reg class to the register we're allocating,
763 // don't check it.
764 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
765 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
766 reg = vrm_->getPhys(reg);
767 ++inactiveCounts[reg];
768 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
769 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000770 }
771
Chris Lattnerf8355d92005-08-22 16:55:22 +0000772 unsigned FreeReg = 0;
773 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000774
775 // If copy coalescer has assigned a "preferred" register, check if it's
776 // available first.
777 if (cur->preference)
778 if (prt_->isRegAvail(cur->preference)) {
779 DOUT << "\t\tassigned the preferred register: "
780 << mri_->getName(cur->preference) << "\n";
781 return cur->preference;
782 } else
783 DOUT << "\t\tunable to assign the preferred register: "
784 << mri_->getName(cur->preference) << "\n";
785
Chris Lattnerf8355d92005-08-22 16:55:22 +0000786 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000787 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
788 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000789 for (; I != E; ++I)
790 if (prt_->isRegAvail(*I)) {
791 FreeReg = *I;
792 FreeRegInactiveCount = inactiveCounts[FreeReg];
793 break;
794 }
795
796 // If there are no free regs, or if this reg has the max inactive count,
797 // return this register.
798 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
799
800 // Continue scanning the registers, looking for the one with the highest
801 // inactive count. Alkis found that this reduced register pressure very
802 // slightly on X86 (in rev 1.94 of this file), though this should probably be
803 // reevaluated now.
804 for (; I != E; ++I) {
805 unsigned Reg = *I;
806 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
807 FreeReg = Reg;
808 FreeRegInactiveCount = inactiveCounts[Reg];
809 if (FreeRegInactiveCount == MaxInactiveCount)
810 break; // We found the one with the max inactive count.
811 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000812 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000813
814 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000815}
816
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000817FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000818 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000819}