blob: 91dda771475964ce38f0098fa1ccfc7fb99545cf [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
Evan Chengc5952452008-06-20 21:45:16 +000046static cl::opt<bool>
47NewHeuristic("new-spilling-heuristic",
48 cl::desc("Use new spilling heuristic"),
49 cl::init(false), cl::Hidden);
50
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051static RegisterRegAlloc
52linearscanRegAlloc("linearscan", " linear scan register allocator",
53 createLinearScanRegisterAllocator);
54
55namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
57 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +000058 RALinScan() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersonba926a32008-08-15 18:49:41 +000061 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 private:
63 /// RelatedRegClasses - This structure is built the first time a function is
64 /// compiled, and keeps track of which register classes have registers that
65 /// belong to multiple classes or have aliases that are in other classes.
66 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson4a472712008-08-13 23:36:23 +000067 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068
69 MachineFunction* mf_;
Evan Chengc5952452008-06-20 21:45:16 +000070 MachineRegisterInfo* mri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071 const TargetMachine* tm_;
Dan Gohman1e57df32008-02-10 18:45:23 +000072 const TargetRegisterInfo* tri_;
Evan Chengc4c75f52007-11-03 07:20:12 +000073 const TargetInstrInfo* tii_;
Chris Lattner1b989192007-12-31 04:13:23 +000074 MachineRegisterInfo *reginfo_;
Evan Chengc4c75f52007-11-03 07:20:12 +000075 BitVector allocatableRegs_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076 LiveIntervals* li_;
Evan Cheng14f8a502008-06-04 09:18:41 +000077 LiveStacks* ls_;
Evan Cheng26d17df2007-12-11 02:09:15 +000078 const MachineLoopInfo *loopInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079
80 /// handled_ - Intervals are added to the handled_ set in the order of their
81 /// start value. This is uses for backtracking.
82 std::vector<LiveInterval*> handled_;
83
84 /// fixed_ - Intervals that correspond to machine registers.
85 ///
86 IntervalPtrs fixed_;
87
88 /// active_ - Intervals that are currently being processed, and which have a
89 /// live range active for the current point.
90 IntervalPtrs active_;
91
92 /// inactive_ - Intervals that are currently being processed, but which have
93 /// a hold at the current point.
94 IntervalPtrs inactive_;
95
96 typedef std::priority_queue<LiveInterval*,
Owen Andersonba926a32008-08-15 18:49:41 +000097 SmallVector<LiveInterval*, 64>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098 greater_ptr<LiveInterval> > IntervalHeap;
99 IntervalHeap unhandled_;
100 std::auto_ptr<PhysRegTracker> prt_;
101 std::auto_ptr<VirtRegMap> vrm_;
102 std::auto_ptr<Spiller> spiller_;
103
104 public:
105 virtual const char* getPassName() const {
106 return "Linear Scan Register Allocator";
107 }
108
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addRequired<LiveIntervals>();
David Greene1d80f1b2007-09-06 16:18:45 +0000111 // Make sure PassManager knows which analyses to make available
112 // to coalescing and which analyses coalescing invalidates.
113 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng14f8a502008-06-04 09:18:41 +0000114 AU.addRequired<LiveStacks>();
115 AU.addPreserved<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000116 AU.addRequired<MachineLoopInfo>();
Bill Wendling62264362008-01-04 20:54:55 +0000117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreservedID(MachineDominatorsID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 MachineFunctionPass::getAnalysisUsage(AU);
120 }
121
122 /// runOnMachineFunction - register allocate the whole function
123 bool runOnMachineFunction(MachineFunction&);
124
125 private:
126 /// linearScan - the linear scan algorithm
127 void linearScan();
128
129 /// initIntervalSets - initialize the interval sets.
130 ///
131 void initIntervalSets();
132
133 /// processActiveIntervals - expire old intervals and move non-overlapping
134 /// ones to the inactive list.
135 void processActiveIntervals(unsigned CurPoint);
136
137 /// processInactiveIntervals - expire old intervals and move overlapping
138 /// ones to the active list.
139 void processInactiveIntervals(unsigned CurPoint);
140
141 /// assignRegOrStackSlotAtInterval - assign a register if one
142 /// is available, or spill.
143 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
144
Evan Chengc5952452008-06-20 21:45:16 +0000145 /// findIntervalsToSpill - Determine the intervals to spill for the
146 /// specified interval. It's passed the physical registers whose spill
147 /// weight is the lowest among all the registers whose live intervals
148 /// conflict with the interval.
149 void findIntervalsToSpill(LiveInterval *cur,
150 std::vector<std::pair<unsigned,float> > &Candidates,
151 unsigned NumCands,
152 SmallVector<LiveInterval*, 8> &SpillIntervals);
153
Evan Chengc4c75f52007-11-03 07:20:12 +0000154 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
155 /// try allocate the definition the same register as the source register
156 /// if the register is not defined during live time of the interval. This
157 /// eliminate a copy. This is used to coalesce copies which were not
158 /// coalesced away before allocation either due to dest and src being in
159 /// different register classes or because the coalescer was overly
160 /// conservative.
161 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
162
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 ///
164 /// register handling helpers
165 ///
166
167 /// getFreePhysReg - return a free physical register for this virtual
168 /// register interval if we have one, otherwise return 0.
169 unsigned getFreePhysReg(LiveInterval* cur);
170
171 /// assignVirt2StackSlot - assigns this virtual register to a
172 /// stack slot. returns the stack slot
173 int assignVirt2StackSlot(unsigned virtReg);
174
175 void ComputeRelatedRegClasses();
176
177 template <typename ItTy>
178 void printIntervals(const char* const str, ItTy i, ItTy e) const {
179 if (str) DOUT << str << " intervals:\n";
180 for (; i != e; ++i) {
181 DOUT << "\t" << *i->first << " -> ";
182 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000183 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 reg = vrm_->getPhys(reg);
185 }
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000186 DOUT << tri_->getName(reg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 }
188 }
189 };
190 char RALinScan::ID = 0;
191}
192
Evan Cheng14f8a502008-06-04 09:18:41 +0000193static RegisterPass<RALinScan>
194X("linearscan-regalloc", "Linear Scan Register Allocator");
195
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman1e57df32008-02-10 18:45:23 +0000197 const TargetRegisterInfo &TRI = *tri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198
199 // First pass, add all reg classes to the union, and determine at least one
200 // reg class that each register is in.
201 bool HasAliases = false;
Dan Gohman1e57df32008-02-10 18:45:23 +0000202 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
203 E = TRI.regclass_end(); RCI != E; ++RCI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 RelatedRegClasses.insert(*RCI);
205 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
206 I != E; ++I) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000207 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208
209 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
210 if (PRC) {
211 // Already processed this register. Just make sure we know that
212 // multiple register classes share a register.
213 RelatedRegClasses.unionSets(PRC, *RCI);
214 } else {
215 PRC = *RCI;
216 }
217 }
218 }
219
220 // Second pass, now that we know conservatively what register classes each reg
221 // belongs to, add info about aliases. We don't need to do this for targets
222 // without register aliases.
223 if (HasAliases)
Owen Anderson4a472712008-08-13 23:36:23 +0000224 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
226 I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000227 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
229}
230
Evan Chengc4c75f52007-11-03 07:20:12 +0000231/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
232/// try allocate the definition the same register as the source register
233/// if the register is not defined during live time of the interval. This
234/// eliminate a copy. This is used to coalesce copies which were not
235/// coalesced away before allocation either due to dest and src being in
236/// different register classes or because the coalescer was overly
237/// conservative.
238unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Chengb6aa6712007-11-04 08:32:21 +0000239 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc4c75f52007-11-03 07:20:12 +0000240 return Reg;
241
242 VNInfo *vni = cur.getValNumInfo(0);
243 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
244 return Reg;
245 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
246 unsigned SrcReg, DstReg;
247 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
248 return Reg;
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000249 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000250 if (!vrm_->isAssignedReg(SrcReg))
251 return Reg;
252 else
253 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000254 }
Evan Chengc4c75f52007-11-03 07:20:12 +0000255 if (Reg == SrcReg)
256 return Reg;
257
Chris Lattner1b989192007-12-31 04:13:23 +0000258 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc4c75f52007-11-03 07:20:12 +0000259 if (!RC->contains(SrcReg))
260 return Reg;
261
262 // Try to coalesce.
263 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000264 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling8eeb9792008-02-26 21:11:01 +0000265 << '\n';
Evan Chengc4c75f52007-11-03 07:20:12 +0000266 vrm_->clearVirt(cur.reg);
267 vrm_->assignVirt2Phys(cur.reg, SrcReg);
268 ++NumCoalesce;
269 return SrcReg;
270 }
271
272 return Reg;
273}
274
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
276 mf_ = &fn;
Evan Chengc5952452008-06-20 21:45:16 +0000277 mri_ = &fn.getRegInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 tm_ = &fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +0000279 tri_ = tm_->getRegisterInfo();
Evan Chengc4c75f52007-11-03 07:20:12 +0000280 tii_ = tm_->getInstrInfo();
Chris Lattner1b989192007-12-31 04:13:23 +0000281 reginfo_ = &mf_->getRegInfo();
Dan Gohman1e57df32008-02-10 18:45:23 +0000282 allocatableRegs_ = tri_->getAllocatableSet(fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng14f8a502008-06-04 09:18:41 +0000284 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000285 loopInfo = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286
David Greene1d80f1b2007-09-06 16:18:45 +0000287 // We don't run the coalescer here because we have no reason to
288 // interact with it. If the coalescer requires interaction, it
289 // won't do anything. If it doesn't require interaction, we assume
290 // it was run as a separate pass.
291
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 // If this is the first function compiled, compute the related reg classes.
293 if (RelatedRegClasses.empty())
294 ComputeRelatedRegClasses();
295
Dan Gohman1e57df32008-02-10 18:45:23 +0000296 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 vrm_.reset(new VirtRegMap(*mf_));
298 if (!spiller_.get()) spiller_.reset(createSpiller());
299
300 initIntervalSets();
301
302 linearScan();
303
304 // Rewrite spill code and update the PhysRegsUsed set.
305 spiller_->runOnMachineFunction(*mf_, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 vrm_.reset(); // Free the VirtRegMap
307
Dan Gohman79a9f152008-06-23 23:51:16 +0000308 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 fixed_.clear();
310 active_.clear();
311 inactive_.clear();
312 handled_.clear();
313
314 return true;
315}
316
317/// initIntervalSets - initialize the interval sets.
318///
319void RALinScan::initIntervalSets()
320{
321 assert(unhandled_.empty() && fixed_.empty() &&
322 active_.empty() && inactive_.empty() &&
323 "interval sets should be empty on initialization");
324
Owen Andersonba926a32008-08-15 18:49:41 +0000325 handled_.reserve(li_->getNumIntervals());
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000328 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
329 reginfo_->setPhysRegUsed(i->second->reg);
330 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 } else
Owen Anderson348d1d82008-08-13 21:49:13 +0000332 unhandled_.push(i->second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 }
334}
335
336void RALinScan::linearScan()
337{
338 // linear scan algorithm
339 DOUT << "********** LINEAR SCAN **********\n";
340 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
341
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343
344 while (!unhandled_.empty()) {
345 // pick the interval with the earliest start point
346 LiveInterval* cur = unhandled_.top();
347 unhandled_.pop();
Evan Chengd48f2bc2007-10-16 21:09:14 +0000348 ++NumIters;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
350
Evan Chenga3186992008-04-03 16:40:27 +0000351 if (!cur->empty()) {
352 processActiveIntervals(cur->beginNumber());
353 processInactiveIntervals(cur->beginNumber());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354
Evan Chenga3186992008-04-03 16:40:27 +0000355 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
356 "Can only allocate virtual registers!");
357 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358
359 // Allocating a virtual register. try to find a free
360 // physical register or spill an interval (possibly this one) in order to
361 // assign it one.
362 assignRegOrStackSlotAtInterval(cur);
363
364 DEBUG(printIntervals("active", active_.begin(), active_.end()));
365 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
366 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367
368 // expire any remaining active intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000369 while (!active_.empty()) {
370 IntervalPtr &IP = active_.back();
371 unsigned reg = IP.first->reg;
372 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000373 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 "Can only allocate virtual registers!");
375 reg = vrm_->getPhys(reg);
376 prt_->delRegUse(reg);
Evan Chengd48f2bc2007-10-16 21:09:14 +0000377 active_.pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 }
379
380 // expire any remaining inactive intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000381 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling1817ab82007-11-15 00:40:48 +0000382 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Chengd48f2bc2007-10-16 21:09:14 +0000383 DOUT << "\tinterval " << *i->first << " expired\n");
384 inactive_.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385
Evan Chengcecc8222007-11-17 00:40:40 +0000386 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Chengf5cdf122007-10-17 02:12:22 +0000387 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000388 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Chengf5cdf122007-10-17 02:12:22 +0000389 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000390 LiveInterval &cur = *i->second;
Evan Chengf5cdf122007-10-17 02:12:22 +0000391 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000392 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Chengcecc8222007-11-17 00:40:40 +0000393 if (isPhys)
Owen Anderson348d1d82008-08-13 21:49:13 +0000394 Reg = cur.reg;
Evan Chengf5cdf122007-10-17 02:12:22 +0000395 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000396 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Chengf5cdf122007-10-17 02:12:22 +0000397 if (!Reg)
398 continue;
Evan Chengcecc8222007-11-17 00:40:40 +0000399 // Ignore splited live intervals.
400 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
401 continue;
Evan Chengf5cdf122007-10-17 02:12:22 +0000402 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
403 I != E; ++I) {
404 const LiveRange &LR = *I;
Evan Chengf5cdf122007-10-17 02:12:22 +0000405 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
406 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
407 if (LiveInMBBs[i] != EntryMBB)
408 LiveInMBBs[i]->addLiveIn(Reg);
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000409 LiveInMBBs.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 }
411 }
412 }
413
414 DOUT << *vrm_;
415}
416
417/// processActiveIntervals - expire old intervals and move non-overlapping ones
418/// to the inactive list.
419void RALinScan::processActiveIntervals(unsigned CurPoint)
420{
421 DOUT << "\tprocessing active intervals:\n";
422
423 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
424 LiveInterval *Interval = active_[i].first;
425 LiveInterval::iterator IntervalPos = active_[i].second;
426 unsigned reg = Interval->reg;
427
428 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
429
430 if (IntervalPos == Interval->end()) { // Remove expired intervals.
431 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000432 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 "Can only allocate virtual registers!");
434 reg = vrm_->getPhys(reg);
435 prt_->delRegUse(reg);
436
437 // Pop off the end of the list.
438 active_[i] = active_.back();
439 active_.pop_back();
440 --i; --e;
441
442 } else if (IntervalPos->start > CurPoint) {
443 // Move inactive intervals to inactive list.
444 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000445 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 "Can only allocate virtual registers!");
447 reg = vrm_->getPhys(reg);
448 prt_->delRegUse(reg);
449 // add to inactive.
450 inactive_.push_back(std::make_pair(Interval, IntervalPos));
451
452 // Pop off the end of the list.
453 active_[i] = active_.back();
454 active_.pop_back();
455 --i; --e;
456 } else {
457 // Otherwise, just update the iterator position.
458 active_[i].second = IntervalPos;
459 }
460 }
461}
462
463/// processInactiveIntervals - expire old intervals and move overlapping
464/// ones to the active list.
465void RALinScan::processInactiveIntervals(unsigned CurPoint)
466{
467 DOUT << "\tprocessing inactive intervals:\n";
468
469 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
470 LiveInterval *Interval = inactive_[i].first;
471 LiveInterval::iterator IntervalPos = inactive_[i].second;
472 unsigned reg = Interval->reg;
473
474 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
475
476 if (IntervalPos == Interval->end()) { // remove expired intervals.
477 DOUT << "\t\tinterval " << *Interval << " expired\n";
478
479 // Pop off the end of the list.
480 inactive_[i] = inactive_.back();
481 inactive_.pop_back();
482 --i; --e;
483 } else if (IntervalPos->start <= CurPoint) {
484 // move re-activated intervals in active list
485 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000486 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 "Can only allocate virtual registers!");
488 reg = vrm_->getPhys(reg);
489 prt_->addRegUse(reg);
490 // add to active
491 active_.push_back(std::make_pair(Interval, IntervalPos));
492
493 // Pop off the end of the list.
494 inactive_[i] = inactive_.back();
495 inactive_.pop_back();
496 --i; --e;
497 } else {
498 // Otherwise, just update the iterator position.
499 inactive_[i].second = IntervalPos;
500 }
501 }
502}
503
504/// updateSpillWeights - updates the spill weights of the specifed physical
505/// register and its weight.
506static void updateSpillWeights(std::vector<float> &Weights,
507 unsigned reg, float weight,
Dan Gohman1e57df32008-02-10 18:45:23 +0000508 const TargetRegisterInfo *TRI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 Weights[reg] += weight;
Dan Gohman1e57df32008-02-10 18:45:23 +0000510 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 Weights[*as] += weight;
512}
513
514static
515RALinScan::IntervalPtrs::iterator
516FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
517 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
518 I != E; ++I)
519 if (I->first == LI) return I;
520 return IP.end();
521}
522
523static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
524 for (unsigned i = 0, e = V.size(); i != e; ++i) {
525 RALinScan::IntervalPtr &IP = V[i];
526 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
527 IP.second, Point);
528 if (I != IP.first->begin()) --I;
529 IP.second = I;
530 }
531}
532
Evan Cheng14f8a502008-06-04 09:18:41 +0000533/// addStackInterval - Create a LiveInterval for stack if the specified live
534/// interval has been spilled.
535static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Chengba221ca2008-06-06 07:54:39 +0000536 LiveIntervals *li_, float &Weight,
537 VirtRegMap &vrm_) {
Evan Cheng14f8a502008-06-04 09:18:41 +0000538 int SS = vrm_.getStackSlot(cur->reg);
539 if (SS == VirtRegMap::NO_STACK_SLOT)
540 return;
541 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Chengba221ca2008-06-06 07:54:39 +0000542 SI.weight += Weight;
543
Evan Cheng14f8a502008-06-04 09:18:41 +0000544 VNInfo *VNI;
545 if (SI.getNumValNums())
546 VNI = SI.getValNumInfo(0);
547 else
548 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
549
550 LiveInterval &RI = li_->getInterval(cur->reg);
551 // FIXME: This may be overly conservative.
552 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng14f8a502008-06-04 09:18:41 +0000553}
554
Evan Chengc5952452008-06-20 21:45:16 +0000555/// getConflictWeight - Return the number of conflicts between cur
556/// live interval and defs and uses of Reg weighted by loop depthes.
557static float getConflictWeight(LiveInterval *cur, unsigned Reg,
558 LiveIntervals *li_,
559 MachineRegisterInfo *mri_,
560 const MachineLoopInfo *loopInfo) {
561 float Conflicts = 0;
562 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
563 E = mri_->reg_end(); I != E; ++I) {
564 MachineInstr *MI = &*I;
565 if (cur->liveAt(li_->getInstructionIndex(MI))) {
566 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
567 Conflicts += powf(10.0f, (float)loopDepth);
568 }
569 }
570 return Conflicts;
571}
572
573/// findIntervalsToSpill - Determine the intervals to spill for the
574/// specified interval. It's passed the physical registers whose spill
575/// weight is the lowest among all the registers whose live intervals
576/// conflict with the interval.
577void RALinScan::findIntervalsToSpill(LiveInterval *cur,
578 std::vector<std::pair<unsigned,float> > &Candidates,
579 unsigned NumCands,
580 SmallVector<LiveInterval*, 8> &SpillIntervals) {
581 // We have figured out the *best* register to spill. But there are other
582 // registers that are pretty good as well (spill weight within 3%). Spill
583 // the one that has fewest defs and uses that conflict with cur.
584 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
585 SmallVector<LiveInterval*, 8> SLIs[3];
586
587 DOUT << "\tConsidering " << NumCands << " candidates: ";
588 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
589 DOUT << tri_->getName(Candidates[i].first) << " ";
590 DOUT << "\n";);
591
592 // Calculate the number of conflicts of each candidate.
593 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
594 unsigned Reg = i->first->reg;
595 unsigned PhysReg = vrm_->getPhys(Reg);
596 if (!cur->overlapsFrom(*i->first, i->second))
597 continue;
598 for (unsigned j = 0; j < NumCands; ++j) {
599 unsigned Candidate = Candidates[j].first;
600 if (tri_->regsOverlap(PhysReg, Candidate)) {
601 if (NumCands > 1)
602 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
603 SLIs[j].push_back(i->first);
604 }
605 }
606 }
607
608 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
609 unsigned Reg = i->first->reg;
610 unsigned PhysReg = vrm_->getPhys(Reg);
611 if (!cur->overlapsFrom(*i->first, i->second-1))
612 continue;
613 for (unsigned j = 0; j < NumCands; ++j) {
614 unsigned Candidate = Candidates[j].first;
615 if (tri_->regsOverlap(PhysReg, Candidate)) {
616 if (NumCands > 1)
617 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
618 SLIs[j].push_back(i->first);
619 }
620 }
621 }
622
623 // Which is the best candidate?
624 unsigned BestCandidate = 0;
625 float MinConflicts = Conflicts[0];
626 for (unsigned i = 1; i != NumCands; ++i) {
627 if (Conflicts[i] < MinConflicts) {
628 BestCandidate = i;
629 MinConflicts = Conflicts[i];
630 }
631 }
632
633 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
634 std::back_inserter(SpillIntervals));
635}
636
637namespace {
638 struct WeightCompare {
639 typedef std::pair<unsigned, float> RegWeightPair;
640 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
641 return LHS.second < RHS.second;
642 }
643 };
644}
645
646static bool weightsAreClose(float w1, float w2) {
647 if (!NewHeuristic)
648 return false;
649
650 float diff = w1 - w2;
651 if (diff <= 0.02f) // Within 0.02f
652 return true;
653 return (diff / w2) <= 0.05f; // Within 5%.
654}
655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
657/// spill.
658void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
659{
660 DOUT << "\tallocating current interval: ";
661
Evan Chenga3186992008-04-03 16:40:27 +0000662 // This is an implicitly defined live interval, just assign any register.
663 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
664 if (cur->empty()) {
665 unsigned physReg = cur->preference;
666 if (!physReg)
667 physReg = *RC->allocation_order_begin(*mf_);
668 DOUT << tri_->getName(physReg) << '\n';
669 // Note the register is not really in use.
670 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chenga3186992008-04-03 16:40:27 +0000671 return;
672 }
673
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 PhysRegTracker backupPrt = *prt_;
675
676 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
677 unsigned StartPosition = cur->beginNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc4c75f52007-11-03 07:20:12 +0000679
680 // If this live interval is defined by a move instruction and its source is
681 // assigned a physical register that is compatible with the target register
682 // class, then we should try to assign it the same register.
683 // This can happen when the move is from a larger register class to a smaller
684 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
685 if (!cur->preference && cur->containsOneValue()) {
686 VNInfo *vni = cur->getValNumInfo(0);
687 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
688 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
689 unsigned SrcReg, DstReg;
Evan Cheng1fbf9c22008-04-11 17:55:47 +0000690 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000691 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000692 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000693 Reg = SrcReg;
694 else if (vrm_->isAssignedReg(SrcReg))
695 Reg = vrm_->getPhys(SrcReg);
696 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
697 cur->preference = Reg;
698 }
699 }
700 }
701
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 // for every interval in inactive we overlap with, mark the
703 // register as not free and update spill weights.
704 for (IntervalPtrs::const_iterator i = inactive_.begin(),
705 e = inactive_.end(); i != e; ++i) {
706 unsigned Reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000707 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 "Can only allocate virtual registers!");
Chris Lattner1b989192007-12-31 04:13:23 +0000709 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 // If this is not in a related reg class to the register we're allocating,
711 // don't check it.
712 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
713 cur->overlapsFrom(*i->first, i->second-1)) {
714 Reg = vrm_->getPhys(Reg);
715 prt_->addRegUse(Reg);
716 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
717 }
718 }
719
720 // Speculatively check to see if we can get a register right now. If not,
721 // we know we won't be able to by adding more constraints. If so, we can
722 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
723 // is very bad (it contains all callee clobbered registers for any functions
724 // with a call), so we want to avoid doing that if possible.
725 unsigned physReg = getFreePhysReg(cur);
Evan Cheng14cc83f2008-03-11 07:19:34 +0000726 unsigned BestPhysReg = physReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 if (physReg) {
728 // We got a register. However, if it's in the fixed_ list, we might
729 // conflict with it. Check to see if we conflict with it or any of its
730 // aliases.
Evan Chengc4c75f52007-11-03 07:20:12 +0000731 SmallSet<unsigned, 8> RegAliases;
Dan Gohman1e57df32008-02-10 18:45:23 +0000732 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 RegAliases.insert(*AS);
734
735 bool ConflictsWithFixed = false;
736 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
737 IntervalPtr &IP = fixed_[i];
738 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
739 // Okay, this reg is on the fixed list. Check to see if we actually
740 // conflict.
741 LiveInterval *I = IP.first;
742 if (I->endNumber() > StartPosition) {
743 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
744 IP.second = II;
745 if (II != I->begin() && II->start > StartPosition)
746 --II;
747 if (cur->overlapsFrom(*I, II)) {
748 ConflictsWithFixed = true;
749 break;
750 }
751 }
752 }
753 }
754
755 // Okay, the register picked by our speculative getFreePhysReg call turned
756 // out to be in use. Actually add all of the conflicting fixed registers to
757 // prt so we can do an accurate query.
758 if (ConflictsWithFixed) {
759 // For every interval in fixed we overlap with, mark the register as not
760 // free and update spill weights.
761 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
762 IntervalPtr &IP = fixed_[i];
763 LiveInterval *I = IP.first;
764
765 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
766 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
767 I->endNumber() > StartPosition) {
768 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
769 IP.second = II;
770 if (II != I->begin() && II->start > StartPosition)
771 --II;
772 if (cur->overlapsFrom(*I, II)) {
773 unsigned reg = I->reg;
774 prt_->addRegUse(reg);
775 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
776 }
777 }
778 }
779
780 // Using the newly updated prt_ object, which includes conflicts in the
781 // future, see if there are any registers available.
782 physReg = getFreePhysReg(cur);
783 }
784 }
785
786 // Restore the physical register tracker, removing information about the
787 // future.
788 *prt_ = backupPrt;
789
790 // if we find a free register, we are done: assign this virtual to
791 // the free physical register and add this interval to the active
792 // list.
793 if (physReg) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000794 DOUT << tri_->getName(physReg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 vrm_->assignVirt2Phys(cur->reg, physReg);
796 prt_->addRegUse(physReg);
797 active_.push_back(std::make_pair(cur, cur->begin()));
798 handled_.push_back(cur);
799 return;
800 }
801 DOUT << "no free registers\n";
802
803 // Compile the spill weights into an array that is better for scanning.
Evan Chengc5952452008-06-20 21:45:16 +0000804 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 for (std::vector<std::pair<unsigned, float> >::iterator
806 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000807 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808
809 // for each interval in active, update spill weights.
810 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
811 i != e; ++i) {
812 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000813 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 "Can only allocate virtual registers!");
815 reg = vrm_->getPhys(reg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000816 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 }
818
819 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
820
821 // Find a register to spill.
822 float minWeight = HUGE_VALF;
Evan Chengc5952452008-06-20 21:45:16 +0000823 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
824
825 bool Found = false;
826 std::vector<std::pair<unsigned,float> > RegsWeights;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
828 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
829 e = RC->allocation_order_end(*mf_); i != e; ++i) {
830 unsigned reg = *i;
Evan Chengc5952452008-06-20 21:45:16 +0000831 float regWeight = SpillWeights[reg];
832 if (minWeight > regWeight)
833 Found = true;
834 RegsWeights.push_back(std::make_pair(reg, regWeight));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 }
836
837 // If we didn't find a register that is spillable, try aliases?
Evan Chengc5952452008-06-20 21:45:16 +0000838 if (!Found) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
840 e = RC->allocation_order_end(*mf_); i != e; ++i) {
841 unsigned reg = *i;
842 // No need to worry about if the alias register size < regsize of RC.
843 // We are going to spill all registers that alias it anyway.
Evan Chengc5952452008-06-20 21:45:16 +0000844 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
845 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng14cc83f2008-03-11 07:19:34 +0000846 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 }
Evan Chengc5952452008-06-20 21:45:16 +0000848
849 // Sort all potential spill candidates by weight.
850 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
851 minReg = RegsWeights[0].first;
852 minWeight = RegsWeights[0].second;
853 if (minWeight == HUGE_VALF) {
854 // All registers must have inf weight. Just grab one!
855 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona0e65132008-07-22 22:46:49 +0000856 if (cur->weight == HUGE_VALF ||
Owen Anderson50ca1a22008-07-23 19:47:27 +0000857 li_->getApproximateInstructionCount(*cur) == 0)
Evan Chengc5952452008-06-20 21:45:16 +0000858 // Spill a physical register around defs and uses.
859 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
860 }
861
862 // Find up to 3 registers to consider as spill candidates.
863 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
864 while (LastCandidate > 1) {
865 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
866 break;
867 --LastCandidate;
868 }
869
870 DOUT << "\t\tregister(s) with min weight(s): ";
871 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
872 DOUT << tri_->getName(RegsWeights[i].first)
873 << " (" << RegsWeights[i].second << ")\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874
875 // if the current has the minimum weight, we need to spill it and
876 // add any added intervals back to unhandled, and restart
877 // linearscan.
878 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
879 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Chengba221ca2008-06-06 07:54:39 +0000880 float SSWeight;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000881 std::vector<LiveInterval*> added =
Evan Chengba221ca2008-06-06 07:54:39 +0000882 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_, SSWeight);
883 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 if (added.empty())
885 return; // Early exit if all spills were folded.
886
887 // Merge added with unhandled. Note that we know that
888 // addIntervalsForSpills returns intervals sorted by their starting
889 // point.
890 for (unsigned i = 0, e = added.size(); i != e; ++i)
891 unhandled_.push(added[i]);
892 return;
893 }
894
895 ++NumBacktracks;
896
897 // push the current interval back to unhandled since we are going
898 // to re-run at least this iteration. Since we didn't modify it it
899 // should go back right in the front of the list
900 unhandled_.push(cur);
901
Dan Gohman1e57df32008-02-10 18:45:23 +0000902 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 "did not choose a register to spill?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904
Evan Chengc5952452008-06-20 21:45:16 +0000905 // We spill all intervals aliasing the register with
906 // minimum weight, rollback to the interval with the earliest
907 // start point and let the linear scan algorithm run again
908 SmallVector<LiveInterval*, 8> spillIs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909
Evan Chengc5952452008-06-20 21:45:16 +0000910 // Determine which intervals have to be spilled.
911 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
912
913 // Set of spilled vregs (used later to rollback properly)
914 SmallSet<unsigned, 8> spilled;
915
916 // The earliest start of a Spilled interval indicates up to where
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 // in handled we need to roll back
918 unsigned earliestStart = cur->beginNumber();
919
Evan Chengc5952452008-06-20 21:45:16 +0000920 // Spill live intervals of virtual regs mapped to the physical register we
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 // want to clear (and its aliases). We only spill those that overlap with the
922 // current interval as the rest do not affect its allocation. we also keep
923 // track of the earliest start of all spilled live intervals since this will
924 // mark our rollback point.
Evan Chengc5952452008-06-20 21:45:16 +0000925 std::vector<LiveInterval*> added;
926 while (!spillIs.empty()) {
927 LiveInterval *sli = spillIs.back();
928 spillIs.pop_back();
929 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
930 earliestStart = std::min(earliestStart, sli->beginNumber());
931 float SSWeight;
932 std::vector<LiveInterval*> newIs =
933 li_->addIntervalsForSpills(*sli, loopInfo, *vrm_, SSWeight);
934 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
935 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
936 spilled.insert(sli->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 }
938
939 DOUT << "\t\trolling back to: " << earliestStart << '\n';
940
941 // Scan handled in reverse order up to the earliest start of a
942 // spilled live interval and undo each one, restoring the state of
943 // unhandled.
944 while (!handled_.empty()) {
945 LiveInterval* i = handled_.back();
946 // If this interval starts before t we are done.
947 if (i->beginNumber() < earliestStart)
948 break;
949 DOUT << "\t\t\tundo changes for: " << *i << '\n';
950 handled_.pop_back();
951
952 // When undoing a live interval allocation we must know if it is active or
953 // inactive to properly update the PhysRegTracker and the VirtRegMap.
954 IntervalPtrs::iterator it;
955 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
956 active_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000957 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 if (!spilled.count(i->reg))
959 unhandled_.push(i);
960 prt_->delRegUse(vrm_->getPhys(i->reg));
961 vrm_->clearVirt(i->reg);
962 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
963 inactive_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000964 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 if (!spilled.count(i->reg))
966 unhandled_.push(i);
967 vrm_->clearVirt(i->reg);
968 } else {
Dan Gohman1e57df32008-02-10 18:45:23 +0000969 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 "Can only allocate virtual registers!");
971 vrm_->clearVirt(i->reg);
972 unhandled_.push(i);
973 }
Evan Chengb6aa6712007-11-04 08:32:21 +0000974
975 // It interval has a preference, it must be defined by a copy. Clear the
976 // preference now since the source interval allocation may have been undone
977 // as well.
978 i->preference = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979 }
980
981 // Rewind the iterators in the active, inactive, and fixed lists back to the
982 // point we reverted to.
983 RevertVectorIteratorsTo(active_, earliestStart);
984 RevertVectorIteratorsTo(inactive_, earliestStart);
985 RevertVectorIteratorsTo(fixed_, earliestStart);
986
987 // scan the rest and undo each interval that expired after t and
988 // insert it in active (the next iteration of the algorithm will
989 // put it in inactive if required)
990 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
991 LiveInterval *HI = handled_[i];
992 if (!HI->expiredAt(earliestStart) &&
993 HI->expiredAt(cur->beginNumber())) {
994 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
995 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman1e57df32008-02-10 18:45:23 +0000996 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 prt_->addRegUse(vrm_->getPhys(HI->reg));
998 }
999 }
1000
1001 // merge added with unhandled
1002 for (unsigned i = 0, e = added.size(); i != e; ++i)
1003 unhandled_.push(added[i]);
1004}
1005
1006/// getFreePhysReg - return a free physical register for this virtual register
1007/// interval if we have one, otherwise return 0.
1008unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001009 SmallVector<unsigned, 256> inactiveCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 unsigned MaxInactiveCount = 0;
1011
Chris Lattner1b989192007-12-31 04:13:23 +00001012 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1014
1015 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1016 i != e; ++i) {
1017 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +00001018 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 "Can only allocate virtual registers!");
1020
1021 // If this is not in a related reg class to the register we're allocating,
1022 // don't check it.
Chris Lattner1b989192007-12-31 04:13:23 +00001023 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1025 reg = vrm_->getPhys(reg);
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001026 if (inactiveCounts.size() <= reg)
1027 inactiveCounts.resize(reg+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 ++inactiveCounts[reg];
1029 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1030 }
1031 }
1032
1033 unsigned FreeReg = 0;
1034 unsigned FreeRegInactiveCount = 0;
1035
1036 // If copy coalescer has assigned a "preferred" register, check if it's
1037 // available first.
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001038 if (cur->preference) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 if (prt_->isRegAvail(cur->preference)) {
1040 DOUT << "\t\tassigned the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +00001041 << tri_->getName(cur->preference) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 return cur->preference;
1043 } else
1044 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +00001045 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001046 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047
1048 // Scan for the first available register.
1049 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1050 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf091bd2008-03-24 23:28:21 +00001051 assert(I != E && "No allocatable register in this register class!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 for (; I != E; ++I)
1053 if (prt_->isRegAvail(*I)) {
1054 FreeReg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001055 if (FreeReg < inactiveCounts.size())
1056 FreeRegInactiveCount = inactiveCounts[FreeReg];
1057 else
1058 FreeRegInactiveCount = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 break;
1060 }
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 // If there are no free regs, or if this reg has the max inactive count,
1063 // return this register.
1064 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1065
1066 // Continue scanning the registers, looking for the one with the highest
1067 // inactive count. Alkis found that this reduced register pressure very
1068 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1069 // reevaluated now.
1070 for (; I != E; ++I) {
1071 unsigned Reg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001072 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1073 FreeRegInactiveCount < inactiveCounts[Reg]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 FreeReg = Reg;
1075 FreeRegInactiveCount = inactiveCounts[Reg];
1076 if (FreeRegInactiveCount == MaxInactiveCount)
1077 break; // We found the one with the max inactive count.
1078 }
1079 }
1080
1081 return FreeReg;
1082}
1083
1084FunctionPass* llvm::createLinearScanRegisterAllocator() {
1085 return new RALinScan();
1086}