blob: d29f6da7fdff677769ed8c5f78402c39b46c48cb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "regalloc"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015#include "PhysRegTracker.h"
16#include "VirtRegMap.h"
17#include "llvm/Function.h"
Evan Cheng14f8a502008-06-04 09:18:41 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/LiveStackAnalysis.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng26d17df2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/CodeGen/Passes.h"
25#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene1d80f1b2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Target/TargetMachine.h"
Evan Chengc4c75f52007-11-03 07:20:12 +000029#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/ADT/EquivalenceClasses.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/Compiler.h"
35#include <algorithm>
36#include <set>
37#include <queue>
38#include <memory>
39#include <cmath>
40using namespace llvm;
41
42STATISTIC(NumIters , "Number of iterations performed");
43STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc4c75f52007-11-03 07:20:12 +000044STATISTIC(NumCoalesce, "Number of copies coalesced");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045
46static RegisterRegAlloc
47linearscanRegAlloc("linearscan", " linear scan register allocator",
48 createLinearScanRegisterAllocator);
49
50namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
52 static char ID;
53 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
54
55 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
56 typedef std::vector<IntervalPtr> IntervalPtrs;
57 private:
58 /// RelatedRegClasses - This structure is built the first time a function is
59 /// compiled, and keeps track of which register classes have registers that
60 /// belong to multiple classes or have aliases that are in other classes.
61 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
62 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
63
64 MachineFunction* mf_;
65 const TargetMachine* tm_;
Dan Gohman1e57df32008-02-10 18:45:23 +000066 const TargetRegisterInfo* tri_;
Evan Chengc4c75f52007-11-03 07:20:12 +000067 const TargetInstrInfo* tii_;
Chris Lattner1b989192007-12-31 04:13:23 +000068 MachineRegisterInfo *reginfo_;
Evan Chengc4c75f52007-11-03 07:20:12 +000069 BitVector allocatableRegs_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 LiveIntervals* li_;
Evan Cheng14f8a502008-06-04 09:18:41 +000071 LiveStacks* ls_;
Evan Cheng26d17df2007-12-11 02:09:15 +000072 const MachineLoopInfo *loopInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073
74 /// handled_ - Intervals are added to the handled_ set in the order of their
75 /// start value. This is uses for backtracking.
76 std::vector<LiveInterval*> handled_;
77
78 /// fixed_ - Intervals that correspond to machine registers.
79 ///
80 IntervalPtrs fixed_;
81
82 /// active_ - Intervals that are currently being processed, and which have a
83 /// live range active for the current point.
84 IntervalPtrs active_;
85
86 /// inactive_ - Intervals that are currently being processed, but which have
87 /// a hold at the current point.
88 IntervalPtrs inactive_;
89
90 typedef std::priority_queue<LiveInterval*,
91 std::vector<LiveInterval*>,
92 greater_ptr<LiveInterval> > IntervalHeap;
93 IntervalHeap unhandled_;
94 std::auto_ptr<PhysRegTracker> prt_;
95 std::auto_ptr<VirtRegMap> vrm_;
96 std::auto_ptr<Spiller> spiller_;
97
98 public:
99 virtual const char* getPassName() const {
100 return "Linear Scan Register Allocator";
101 }
102
103 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
104 AU.addRequired<LiveIntervals>();
David Greene1d80f1b2007-09-06 16:18:45 +0000105 // Make sure PassManager knows which analyses to make available
106 // to coalescing and which analyses coalescing invalidates.
107 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng14f8a502008-06-04 09:18:41 +0000108 AU.addRequired<LiveStacks>();
109 AU.addPreserved<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000110 AU.addRequired<MachineLoopInfo>();
Bill Wendling62264362008-01-04 20:54:55 +0000111 AU.addPreserved<MachineLoopInfo>();
112 AU.addPreservedID(MachineDominatorsID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 MachineFunctionPass::getAnalysisUsage(AU);
114 }
115
116 /// runOnMachineFunction - register allocate the whole function
117 bool runOnMachineFunction(MachineFunction&);
118
119 private:
120 /// linearScan - the linear scan algorithm
121 void linearScan();
122
123 /// initIntervalSets - initialize the interval sets.
124 ///
125 void initIntervalSets();
126
127 /// processActiveIntervals - expire old intervals and move non-overlapping
128 /// ones to the inactive list.
129 void processActiveIntervals(unsigned CurPoint);
130
131 /// processInactiveIntervals - expire old intervals and move overlapping
132 /// ones to the active list.
133 void processInactiveIntervals(unsigned CurPoint);
134
135 /// assignRegOrStackSlotAtInterval - assign a register if one
136 /// is available, or spill.
137 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
138
Evan Chengc4c75f52007-11-03 07:20:12 +0000139 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
140 /// try allocate the definition the same register as the source register
141 /// if the register is not defined during live time of the interval. This
142 /// eliminate a copy. This is used to coalesce copies which were not
143 /// coalesced away before allocation either due to dest and src being in
144 /// different register classes or because the coalescer was overly
145 /// conservative.
146 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
147
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 ///
149 /// register handling helpers
150 ///
151
152 /// getFreePhysReg - return a free physical register for this virtual
153 /// register interval if we have one, otherwise return 0.
154 unsigned getFreePhysReg(LiveInterval* cur);
155
156 /// assignVirt2StackSlot - assigns this virtual register to a
157 /// stack slot. returns the stack slot
158 int assignVirt2StackSlot(unsigned virtReg);
159
160 void ComputeRelatedRegClasses();
161
162 template <typename ItTy>
163 void printIntervals(const char* const str, ItTy i, ItTy e) const {
164 if (str) DOUT << str << " intervals:\n";
165 for (; i != e; ++i) {
166 DOUT << "\t" << *i->first << " -> ";
167 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000168 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 reg = vrm_->getPhys(reg);
170 }
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000171 DOUT << tri_->getName(reg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 }
173 }
174 };
175 char RALinScan::ID = 0;
176}
177
Evan Cheng14f8a502008-06-04 09:18:41 +0000178static RegisterPass<RALinScan>
179X("linearscan-regalloc", "Linear Scan Register Allocator");
180
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman1e57df32008-02-10 18:45:23 +0000182 const TargetRegisterInfo &TRI = *tri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183
184 // First pass, add all reg classes to the union, and determine at least one
185 // reg class that each register is in.
186 bool HasAliases = false;
Dan Gohman1e57df32008-02-10 18:45:23 +0000187 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
188 E = TRI.regclass_end(); RCI != E; ++RCI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 RelatedRegClasses.insert(*RCI);
190 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
191 I != E; ++I) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000192 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193
194 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
195 if (PRC) {
196 // Already processed this register. Just make sure we know that
197 // multiple register classes share a register.
198 RelatedRegClasses.unionSets(PRC, *RCI);
199 } else {
200 PRC = *RCI;
201 }
202 }
203 }
204
205 // Second pass, now that we know conservatively what register classes each reg
206 // belongs to, add info about aliases. We don't need to do this for targets
207 // without register aliases.
208 if (HasAliases)
209 for (std::map<unsigned, const TargetRegisterClass*>::iterator
210 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
211 I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000212 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
214}
215
Evan Chengc4c75f52007-11-03 07:20:12 +0000216/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
217/// try allocate the definition the same register as the source register
218/// if the register is not defined during live time of the interval. This
219/// eliminate a copy. This is used to coalesce copies which were not
220/// coalesced away before allocation either due to dest and src being in
221/// different register classes or because the coalescer was overly
222/// conservative.
223unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Chengb6aa6712007-11-04 08:32:21 +0000224 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc4c75f52007-11-03 07:20:12 +0000225 return Reg;
226
227 VNInfo *vni = cur.getValNumInfo(0);
228 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
229 return Reg;
230 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
231 unsigned SrcReg, DstReg;
232 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
233 return Reg;
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000234 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000235 if (!vrm_->isAssignedReg(SrcReg))
236 return Reg;
237 else
238 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000239 }
Evan Chengc4c75f52007-11-03 07:20:12 +0000240 if (Reg == SrcReg)
241 return Reg;
242
Chris Lattner1b989192007-12-31 04:13:23 +0000243 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc4c75f52007-11-03 07:20:12 +0000244 if (!RC->contains(SrcReg))
245 return Reg;
246
247 // Try to coalesce.
248 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000249 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling8eeb9792008-02-26 21:11:01 +0000250 << '\n';
Evan Chengc4c75f52007-11-03 07:20:12 +0000251 vrm_->clearVirt(cur.reg);
252 vrm_->assignVirt2Phys(cur.reg, SrcReg);
253 ++NumCoalesce;
254 return SrcReg;
255 }
256
257 return Reg;
258}
259
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
261 mf_ = &fn;
262 tm_ = &fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +0000263 tri_ = tm_->getRegisterInfo();
Evan Chengc4c75f52007-11-03 07:20:12 +0000264 tii_ = tm_->getInstrInfo();
Chris Lattner1b989192007-12-31 04:13:23 +0000265 reginfo_ = &mf_->getRegInfo();
Dan Gohman1e57df32008-02-10 18:45:23 +0000266 allocatableRegs_ = tri_->getAllocatableSet(fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng14f8a502008-06-04 09:18:41 +0000268 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000269 loopInfo = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270
David Greene1d80f1b2007-09-06 16:18:45 +0000271 // We don't run the coalescer here because we have no reason to
272 // interact with it. If the coalescer requires interaction, it
273 // won't do anything. If it doesn't require interaction, we assume
274 // it was run as a separate pass.
275
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 // If this is the first function compiled, compute the related reg classes.
277 if (RelatedRegClasses.empty())
278 ComputeRelatedRegClasses();
279
Dan Gohman1e57df32008-02-10 18:45:23 +0000280 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 vrm_.reset(new VirtRegMap(*mf_));
282 if (!spiller_.get()) spiller_.reset(createSpiller());
283
284 initIntervalSets();
285
286 linearScan();
287
288 // Rewrite spill code and update the PhysRegsUsed set.
289 spiller_->runOnMachineFunction(*mf_, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 vrm_.reset(); // Free the VirtRegMap
291
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 while (!unhandled_.empty()) unhandled_.pop();
293 fixed_.clear();
294 active_.clear();
295 inactive_.clear();
296 handled_.clear();
297
298 return true;
299}
300
301/// initIntervalSets - initialize the interval sets.
302///
303void RALinScan::initIntervalSets()
304{
305 assert(unhandled_.empty() && fixed_.empty() &&
306 active_.empty() && inactive_.empty() &&
307 "interval sets should be empty on initialization");
308
309 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000310 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
Chris Lattner1b989192007-12-31 04:13:23 +0000311 reginfo_->setPhysRegUsed(i->second.reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
313 } else
314 unhandled_.push(&i->second);
315 }
316}
317
318void RALinScan::linearScan()
319{
320 // linear scan algorithm
321 DOUT << "********** LINEAR SCAN **********\n";
322 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325
326 while (!unhandled_.empty()) {
327 // pick the interval with the earliest start point
328 LiveInterval* cur = unhandled_.top();
329 unhandled_.pop();
Evan Chengd48f2bc2007-10-16 21:09:14 +0000330 ++NumIters;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
332
Evan Chenga3186992008-04-03 16:40:27 +0000333 if (!cur->empty()) {
334 processActiveIntervals(cur->beginNumber());
335 processInactiveIntervals(cur->beginNumber());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
Evan Chenga3186992008-04-03 16:40:27 +0000337 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
338 "Can only allocate virtual registers!");
339 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
341 // Allocating a virtual register. try to find a free
342 // physical register or spill an interval (possibly this one) in order to
343 // assign it one.
344 assignRegOrStackSlotAtInterval(cur);
345
346 DEBUG(printIntervals("active", active_.begin(), active_.end()));
347 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
348 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349
350 // expire any remaining active intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000351 while (!active_.empty()) {
352 IntervalPtr &IP = active_.back();
353 unsigned reg = IP.first->reg;
354 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000355 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 "Can only allocate virtual registers!");
357 reg = vrm_->getPhys(reg);
358 prt_->delRegUse(reg);
Evan Chengd48f2bc2007-10-16 21:09:14 +0000359 active_.pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 }
361
362 // expire any remaining inactive intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000363 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling1817ab82007-11-15 00:40:48 +0000364 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Chengd48f2bc2007-10-16 21:09:14 +0000365 DOUT << "\tinterval " << *i->first << " expired\n");
366 inactive_.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367
Evan Chengcecc8222007-11-17 00:40:40 +0000368 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Chengf5cdf122007-10-17 02:12:22 +0000369 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000370 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Chengf5cdf122007-10-17 02:12:22 +0000371 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000372 LiveInterval &cur = i->second;
Evan Chengf5cdf122007-10-17 02:12:22 +0000373 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000374 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Chengcecc8222007-11-17 00:40:40 +0000375 if (isPhys)
Evan Chengf5cdf122007-10-17 02:12:22 +0000376 Reg = i->second.reg;
377 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000378 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Chengf5cdf122007-10-17 02:12:22 +0000379 if (!Reg)
380 continue;
Evan Chengcecc8222007-11-17 00:40:40 +0000381 // Ignore splited live intervals.
382 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
383 continue;
Evan Chengf5cdf122007-10-17 02:12:22 +0000384 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
385 I != E; ++I) {
386 const LiveRange &LR = *I;
Evan Chengf5cdf122007-10-17 02:12:22 +0000387 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
388 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
389 if (LiveInMBBs[i] != EntryMBB)
390 LiveInMBBs[i]->addLiveIn(Reg);
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000391 LiveInMBBs.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 }
393 }
394 }
395
396 DOUT << *vrm_;
397}
398
399/// processActiveIntervals - expire old intervals and move non-overlapping ones
400/// to the inactive list.
401void RALinScan::processActiveIntervals(unsigned CurPoint)
402{
403 DOUT << "\tprocessing active intervals:\n";
404
405 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
406 LiveInterval *Interval = active_[i].first;
407 LiveInterval::iterator IntervalPos = active_[i].second;
408 unsigned reg = Interval->reg;
409
410 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
411
412 if (IntervalPos == Interval->end()) { // Remove expired intervals.
413 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000414 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 "Can only allocate virtual registers!");
416 reg = vrm_->getPhys(reg);
417 prt_->delRegUse(reg);
418
419 // Pop off the end of the list.
420 active_[i] = active_.back();
421 active_.pop_back();
422 --i; --e;
423
424 } else if (IntervalPos->start > CurPoint) {
425 // Move inactive intervals to inactive list.
426 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000427 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 "Can only allocate virtual registers!");
429 reg = vrm_->getPhys(reg);
430 prt_->delRegUse(reg);
431 // add to inactive.
432 inactive_.push_back(std::make_pair(Interval, IntervalPos));
433
434 // Pop off the end of the list.
435 active_[i] = active_.back();
436 active_.pop_back();
437 --i; --e;
438 } else {
439 // Otherwise, just update the iterator position.
440 active_[i].second = IntervalPos;
441 }
442 }
443}
444
445/// processInactiveIntervals - expire old intervals and move overlapping
446/// ones to the active list.
447void RALinScan::processInactiveIntervals(unsigned CurPoint)
448{
449 DOUT << "\tprocessing inactive intervals:\n";
450
451 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
452 LiveInterval *Interval = inactive_[i].first;
453 LiveInterval::iterator IntervalPos = inactive_[i].second;
454 unsigned reg = Interval->reg;
455
456 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
457
458 if (IntervalPos == Interval->end()) { // remove expired intervals.
459 DOUT << "\t\tinterval " << *Interval << " expired\n";
460
461 // Pop off the end of the list.
462 inactive_[i] = inactive_.back();
463 inactive_.pop_back();
464 --i; --e;
465 } else if (IntervalPos->start <= CurPoint) {
466 // move re-activated intervals in active list
467 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000468 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 "Can only allocate virtual registers!");
470 reg = vrm_->getPhys(reg);
471 prt_->addRegUse(reg);
472 // add to active
473 active_.push_back(std::make_pair(Interval, IntervalPos));
474
475 // Pop off the end of the list.
476 inactive_[i] = inactive_.back();
477 inactive_.pop_back();
478 --i; --e;
479 } else {
480 // Otherwise, just update the iterator position.
481 inactive_[i].second = IntervalPos;
482 }
483 }
484}
485
486/// updateSpillWeights - updates the spill weights of the specifed physical
487/// register and its weight.
488static void updateSpillWeights(std::vector<float> &Weights,
489 unsigned reg, float weight,
Dan Gohman1e57df32008-02-10 18:45:23 +0000490 const TargetRegisterInfo *TRI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 Weights[reg] += weight;
Dan Gohman1e57df32008-02-10 18:45:23 +0000492 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 Weights[*as] += weight;
494}
495
496static
497RALinScan::IntervalPtrs::iterator
498FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
499 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
500 I != E; ++I)
501 if (I->first == LI) return I;
502 return IP.end();
503}
504
505static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
506 for (unsigned i = 0, e = V.size(); i != e; ++i) {
507 RALinScan::IntervalPtr &IP = V[i];
508 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
509 IP.second, Point);
510 if (I != IP.first->begin()) --I;
511 IP.second = I;
512 }
513}
514
Evan Cheng14f8a502008-06-04 09:18:41 +0000515/// addStackInterval - Create a LiveInterval for stack if the specified live
516/// interval has been spilled.
517static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Chengba221ca2008-06-06 07:54:39 +0000518 LiveIntervals *li_, float &Weight,
519 VirtRegMap &vrm_) {
Evan Cheng14f8a502008-06-04 09:18:41 +0000520 int SS = vrm_.getStackSlot(cur->reg);
521 if (SS == VirtRegMap::NO_STACK_SLOT)
522 return;
523 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Chengba221ca2008-06-06 07:54:39 +0000524 SI.weight += Weight;
525
Evan Cheng14f8a502008-06-04 09:18:41 +0000526 VNInfo *VNI;
527 if (SI.getNumValNums())
528 VNI = SI.getValNumInfo(0);
529 else
530 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
531
532 LiveInterval &RI = li_->getInterval(cur->reg);
533 // FIXME: This may be overly conservative.
534 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng14f8a502008-06-04 09:18:41 +0000535}
536
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
538/// spill.
539void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
540{
541 DOUT << "\tallocating current interval: ";
542
Evan Chenga3186992008-04-03 16:40:27 +0000543 // This is an implicitly defined live interval, just assign any register.
544 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
545 if (cur->empty()) {
546 unsigned physReg = cur->preference;
547 if (!physReg)
548 physReg = *RC->allocation_order_begin(*mf_);
549 DOUT << tri_->getName(physReg) << '\n';
550 // Note the register is not really in use.
551 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chenga3186992008-04-03 16:40:27 +0000552 return;
553 }
554
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 PhysRegTracker backupPrt = *prt_;
556
557 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
558 unsigned StartPosition = cur->beginNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc4c75f52007-11-03 07:20:12 +0000560
561 // If this live interval is defined by a move instruction and its source is
562 // assigned a physical register that is compatible with the target register
563 // class, then we should try to assign it the same register.
564 // This can happen when the move is from a larger register class to a smaller
565 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
566 if (!cur->preference && cur->containsOneValue()) {
567 VNInfo *vni = cur->getValNumInfo(0);
568 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
569 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
570 unsigned SrcReg, DstReg;
Evan Cheng1fbf9c22008-04-11 17:55:47 +0000571 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000572 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000573 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000574 Reg = SrcReg;
575 else if (vrm_->isAssignedReg(SrcReg))
576 Reg = vrm_->getPhys(SrcReg);
577 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
578 cur->preference = Reg;
579 }
580 }
581 }
582
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 // for every interval in inactive we overlap with, mark the
584 // register as not free and update spill weights.
585 for (IntervalPtrs::const_iterator i = inactive_.begin(),
586 e = inactive_.end(); i != e; ++i) {
587 unsigned Reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000588 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 "Can only allocate virtual registers!");
Chris Lattner1b989192007-12-31 04:13:23 +0000590 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 // If this is not in a related reg class to the register we're allocating,
592 // don't check it.
593 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
594 cur->overlapsFrom(*i->first, i->second-1)) {
595 Reg = vrm_->getPhys(Reg);
596 prt_->addRegUse(Reg);
597 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
598 }
599 }
600
601 // Speculatively check to see if we can get a register right now. If not,
602 // we know we won't be able to by adding more constraints. If so, we can
603 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
604 // is very bad (it contains all callee clobbered registers for any functions
605 // with a call), so we want to avoid doing that if possible.
606 unsigned physReg = getFreePhysReg(cur);
Evan Cheng14cc83f2008-03-11 07:19:34 +0000607 unsigned BestPhysReg = physReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 if (physReg) {
609 // We got a register. However, if it's in the fixed_ list, we might
610 // conflict with it. Check to see if we conflict with it or any of its
611 // aliases.
Evan Chengc4c75f52007-11-03 07:20:12 +0000612 SmallSet<unsigned, 8> RegAliases;
Dan Gohman1e57df32008-02-10 18:45:23 +0000613 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 RegAliases.insert(*AS);
615
616 bool ConflictsWithFixed = false;
617 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
618 IntervalPtr &IP = fixed_[i];
619 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
620 // Okay, this reg is on the fixed list. Check to see if we actually
621 // conflict.
622 LiveInterval *I = IP.first;
623 if (I->endNumber() > StartPosition) {
624 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
625 IP.second = II;
626 if (II != I->begin() && II->start > StartPosition)
627 --II;
628 if (cur->overlapsFrom(*I, II)) {
629 ConflictsWithFixed = true;
630 break;
631 }
632 }
633 }
634 }
635
636 // Okay, the register picked by our speculative getFreePhysReg call turned
637 // out to be in use. Actually add all of the conflicting fixed registers to
638 // prt so we can do an accurate query.
639 if (ConflictsWithFixed) {
640 // For every interval in fixed we overlap with, mark the register as not
641 // free and update spill weights.
642 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
643 IntervalPtr &IP = fixed_[i];
644 LiveInterval *I = IP.first;
645
646 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
647 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
648 I->endNumber() > StartPosition) {
649 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
650 IP.second = II;
651 if (II != I->begin() && II->start > StartPosition)
652 --II;
653 if (cur->overlapsFrom(*I, II)) {
654 unsigned reg = I->reg;
655 prt_->addRegUse(reg);
656 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
657 }
658 }
659 }
660
661 // Using the newly updated prt_ object, which includes conflicts in the
662 // future, see if there are any registers available.
663 physReg = getFreePhysReg(cur);
664 }
665 }
666
667 // Restore the physical register tracker, removing information about the
668 // future.
669 *prt_ = backupPrt;
670
671 // if we find a free register, we are done: assign this virtual to
672 // the free physical register and add this interval to the active
673 // list.
674 if (physReg) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000675 DOUT << tri_->getName(physReg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 vrm_->assignVirt2Phys(cur->reg, physReg);
677 prt_->addRegUse(physReg);
678 active_.push_back(std::make_pair(cur, cur->begin()));
679 handled_.push_back(cur);
680 return;
681 }
682 DOUT << "no free registers\n";
683
684 // Compile the spill weights into an array that is better for scanning.
Dan Gohman1e57df32008-02-10 18:45:23 +0000685 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 for (std::vector<std::pair<unsigned, float> >::iterator
687 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000688 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689
690 // for each interval in active, update spill weights.
691 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
692 i != e; ++i) {
693 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000694 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 "Can only allocate virtual registers!");
696 reg = vrm_->getPhys(reg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000697 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 }
699
700 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
701
702 // Find a register to spill.
703 float minWeight = HUGE_VALF;
704 unsigned minReg = cur->preference; // Try the preferred register first.
705
706 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
707 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
708 e = RC->allocation_order_end(*mf_); i != e; ++i) {
709 unsigned reg = *i;
710 if (minWeight > SpillWeights[reg]) {
711 minWeight = SpillWeights[reg];
712 minReg = reg;
713 }
714 }
715
716 // If we didn't find a register that is spillable, try aliases?
717 if (!minReg) {
718 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
719 e = RC->allocation_order_end(*mf_); i != e; ++i) {
720 unsigned reg = *i;
721 // No need to worry about if the alias register size < regsize of RC.
722 // We are going to spill all registers that alias it anyway.
Dan Gohman1e57df32008-02-10 18:45:23 +0000723 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 if (minWeight > SpillWeights[*as]) {
725 minWeight = SpillWeights[*as];
726 minReg = *as;
727 }
728 }
729 }
730
731 // All registers must have inf weight. Just grab one!
Evan Cheng14cc83f2008-03-11 07:19:34 +0000732 if (!minReg) {
Evan Cheng39033332008-03-13 17:42:48 +0000733 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
734 if (cur->weight == HUGE_VALF || cur->getSize() == 1)
735 // Spill a physical register around defs and uses.
736 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng14cc83f2008-03-11 07:19:34 +0000737 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 }
739
740 DOUT << "\t\tregister with min weight: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000741 << tri_->getName(minReg) << " (" << minWeight << ")\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742
743 // if the current has the minimum weight, we need to spill it and
744 // add any added intervals back to unhandled, and restart
745 // linearscan.
746 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
747 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Chengba221ca2008-06-06 07:54:39 +0000748 float SSWeight;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 std::vector<LiveInterval*> added =
Evan Chengba221ca2008-06-06 07:54:39 +0000750 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_, SSWeight);
751 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 if (added.empty())
753 return; // Early exit if all spills were folded.
754
755 // Merge added with unhandled. Note that we know that
756 // addIntervalsForSpills returns intervals sorted by their starting
757 // point.
758 for (unsigned i = 0, e = added.size(); i != e; ++i)
759 unhandled_.push(added[i]);
760 return;
761 }
762
763 ++NumBacktracks;
764
765 // push the current interval back to unhandled since we are going
766 // to re-run at least this iteration. Since we didn't modify it it
767 // should go back right in the front of the list
768 unhandled_.push(cur);
769
770 // otherwise we spill all intervals aliasing the register with
771 // minimum weight, rollback to the interval with the earliest
772 // start point and let the linear scan algorithm run again
773 std::vector<LiveInterval*> added;
Dan Gohman1e57df32008-02-10 18:45:23 +0000774 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 "did not choose a register to spill?");
Dan Gohman1e57df32008-02-10 18:45:23 +0000776 BitVector toSpill(tri_->getNumRegs());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777
778 // We are going to spill minReg and all its aliases.
779 toSpill[minReg] = true;
Dan Gohman1e57df32008-02-10 18:45:23 +0000780 for (const unsigned* as = tri_->getAliasSet(minReg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 toSpill[*as] = true;
782
783 // the earliest start of a spilled interval indicates up to where
784 // in handled we need to roll back
785 unsigned earliestStart = cur->beginNumber();
786
787 // set of spilled vregs (used later to rollback properly)
Evan Chengc4c75f52007-11-03 07:20:12 +0000788 SmallSet<unsigned, 32> spilled;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789
790 // spill live intervals of virtual regs mapped to the physical register we
791 // want to clear (and its aliases). We only spill those that overlap with the
792 // current interval as the rest do not affect its allocation. we also keep
793 // track of the earliest start of all spilled live intervals since this will
794 // mark our rollback point.
795 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
796 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000797 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798 toSpill[vrm_->getPhys(reg)] &&
799 cur->overlapsFrom(*i->first, i->second)) {
800 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
801 earliestStart = std::min(earliestStart, i->first->beginNumber());
Evan Chengba221ca2008-06-06 07:54:39 +0000802 float SSWeight;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 std::vector<LiveInterval*> newIs =
Evan Chengba221ca2008-06-06 07:54:39 +0000804 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_, SSWeight);
805 addStackInterval(i->first, ls_, li_, SSWeight, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
807 spilled.insert(reg);
808 }
809 }
810 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
811 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000812 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 toSpill[vrm_->getPhys(reg)] &&
814 cur->overlapsFrom(*i->first, i->second-1)) {
815 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
816 earliestStart = std::min(earliestStart, i->first->beginNumber());
Evan Chengba221ca2008-06-06 07:54:39 +0000817 float SSWeight;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 std::vector<LiveInterval*> newIs =
Evan Chengba221ca2008-06-06 07:54:39 +0000819 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_, SSWeight);
820 addStackInterval(i->first, ls_, li_, SSWeight, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
822 spilled.insert(reg);
823 }
824 }
825
826 DOUT << "\t\trolling back to: " << earliestStart << '\n';
827
828 // Scan handled in reverse order up to the earliest start of a
829 // spilled live interval and undo each one, restoring the state of
830 // unhandled.
831 while (!handled_.empty()) {
832 LiveInterval* i = handled_.back();
833 // If this interval starts before t we are done.
834 if (i->beginNumber() < earliestStart)
835 break;
836 DOUT << "\t\t\tundo changes for: " << *i << '\n';
837 handled_.pop_back();
838
839 // When undoing a live interval allocation we must know if it is active or
840 // inactive to properly update the PhysRegTracker and the VirtRegMap.
841 IntervalPtrs::iterator it;
842 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
843 active_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000844 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 if (!spilled.count(i->reg))
846 unhandled_.push(i);
847 prt_->delRegUse(vrm_->getPhys(i->reg));
848 vrm_->clearVirt(i->reg);
849 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
850 inactive_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000851 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 if (!spilled.count(i->reg))
853 unhandled_.push(i);
854 vrm_->clearVirt(i->reg);
855 } else {
Dan Gohman1e57df32008-02-10 18:45:23 +0000856 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 "Can only allocate virtual registers!");
858 vrm_->clearVirt(i->reg);
859 unhandled_.push(i);
860 }
Evan Chengb6aa6712007-11-04 08:32:21 +0000861
862 // It interval has a preference, it must be defined by a copy. Clear the
863 // preference now since the source interval allocation may have been undone
864 // as well.
865 i->preference = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 }
867
868 // Rewind the iterators in the active, inactive, and fixed lists back to the
869 // point we reverted to.
870 RevertVectorIteratorsTo(active_, earliestStart);
871 RevertVectorIteratorsTo(inactive_, earliestStart);
872 RevertVectorIteratorsTo(fixed_, earliestStart);
873
874 // scan the rest and undo each interval that expired after t and
875 // insert it in active (the next iteration of the algorithm will
876 // put it in inactive if required)
877 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
878 LiveInterval *HI = handled_[i];
879 if (!HI->expiredAt(earliestStart) &&
880 HI->expiredAt(cur->beginNumber())) {
881 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
882 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman1e57df32008-02-10 18:45:23 +0000883 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 prt_->addRegUse(vrm_->getPhys(HI->reg));
885 }
886 }
887
888 // merge added with unhandled
889 for (unsigned i = 0, e = added.size(); i != e; ++i)
890 unhandled_.push(added[i]);
891}
892
893/// getFreePhysReg - return a free physical register for this virtual register
894/// interval if we have one, otherwise return 0.
895unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000896 SmallVector<unsigned, 256> inactiveCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 unsigned MaxInactiveCount = 0;
898
Chris Lattner1b989192007-12-31 04:13:23 +0000899 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
901
902 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
903 i != e; ++i) {
904 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000905 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 "Can only allocate virtual registers!");
907
908 // If this is not in a related reg class to the register we're allocating,
909 // don't check it.
Chris Lattner1b989192007-12-31 04:13:23 +0000910 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
912 reg = vrm_->getPhys(reg);
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000913 if (inactiveCounts.size() <= reg)
914 inactiveCounts.resize(reg+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 ++inactiveCounts[reg];
916 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
917 }
918 }
919
920 unsigned FreeReg = 0;
921 unsigned FreeRegInactiveCount = 0;
922
923 // If copy coalescer has assigned a "preferred" register, check if it's
924 // available first.
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000925 if (cur->preference) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 if (prt_->isRegAvail(cur->preference)) {
927 DOUT << "\t\tassigned the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000928 << tri_->getName(cur->preference) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 return cur->preference;
930 } else
931 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000932 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000933 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 // Scan for the first available register.
936 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
937 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf091bd2008-03-24 23:28:21 +0000938 assert(I != E && "No allocatable register in this register class!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 for (; I != E; ++I)
940 if (prt_->isRegAvail(*I)) {
941 FreeReg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000942 if (FreeReg < inactiveCounts.size())
943 FreeRegInactiveCount = inactiveCounts[FreeReg];
944 else
945 FreeRegInactiveCount = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 break;
947 }
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000948
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 // If there are no free regs, or if this reg has the max inactive count,
950 // return this register.
951 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
952
953 // Continue scanning the registers, looking for the one with the highest
954 // inactive count. Alkis found that this reduced register pressure very
955 // slightly on X86 (in rev 1.94 of this file), though this should probably be
956 // reevaluated now.
957 for (; I != E; ++I) {
958 unsigned Reg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +0000959 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
960 FreeRegInactiveCount < inactiveCounts[Reg]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 FreeReg = Reg;
962 FreeRegInactiveCount = inactiveCounts[Reg];
963 if (FreeRegInactiveCount == MaxInactiveCount)
964 break; // We found the one with the max inactive count.
965 }
966 }
967
968 return FreeReg;
969}
970
971FunctionPass* llvm::createLinearScanRegisterAllocator() {
972 return new RALinScan();
973}