blob: 8c20a632c9deae40e1fe739a489890e6f160aaee [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"
Owen Anderson860d4822009-03-11 22:31:21 +000017#include "Spiller.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/Function.h"
Evan Cheng14f8a502008-06-04 09:18:41 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
20#include "llvm/CodeGen/LiveStackAnalysis.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng26d17df2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene1d80f1b2007-09-06 16:18:45 +000027#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Target/TargetMachine.h"
Owen Andersonbac9ae22008-10-07 20:22:28 +000030#include "llvm/Target/TargetOptions.h"
Evan Chengc4c75f52007-11-03 07:20:12 +000031#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/ADT/EquivalenceClasses.h"
Dan Gohmanc24a3f82009-01-05 17:59:02 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/Compiler.h"
38#include <algorithm>
39#include <set>
40#include <queue>
41#include <memory>
42#include <cmath>
43using namespace llvm;
44
45STATISTIC(NumIters , "Number of iterations performed");
46STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc4c75f52007-11-03 07:20:12 +000047STATISTIC(NumCoalesce, "Number of copies coalesced");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
Evan Chengc5952452008-06-20 21:45:16 +000049static cl::opt<bool>
50NewHeuristic("new-spilling-heuristic",
51 cl::desc("Use new spilling heuristic"),
52 cl::init(false), cl::Hidden);
53
Evan Cheng99dcc172008-10-23 20:43:13 +000054static cl::opt<bool>
55PreSplitIntervals("pre-alloc-split",
56 cl::desc("Pre-register allocation live interval splitting"),
57 cl::init(false), cl::Hidden);
58
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059static RegisterRegAlloc
Dan Gohman669b9bf2008-10-14 20:25:08 +000060linearscanRegAlloc("linearscan", "linear scan register allocator",
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 createLinearScanRegisterAllocator);
62
63namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
65 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +000066 RALinScan() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067
68 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersonba926a32008-08-15 18:49:41 +000069 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 private:
71 /// RelatedRegClasses - This structure is built the first time a function is
72 /// compiled, and keeps track of which register classes have registers that
73 /// belong to multiple classes or have aliases that are in other classes.
74 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson4a472712008-08-13 23:36:23 +000075 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076
77 MachineFunction* mf_;
Evan Chengc5952452008-06-20 21:45:16 +000078 MachineRegisterInfo* mri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079 const TargetMachine* tm_;
Dan Gohman1e57df32008-02-10 18:45:23 +000080 const TargetRegisterInfo* tri_;
Evan Chengc4c75f52007-11-03 07:20:12 +000081 const TargetInstrInfo* tii_;
Evan Chengc4c75f52007-11-03 07:20:12 +000082 BitVector allocatableRegs_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 LiveIntervals* li_;
Evan Cheng14f8a502008-06-04 09:18:41 +000084 LiveStacks* ls_;
Evan Cheng26d17df2007-12-11 02:09:15 +000085 const MachineLoopInfo *loopInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
87 /// handled_ - Intervals are added to the handled_ set in the order of their
88 /// start value. This is uses for backtracking.
89 std::vector<LiveInterval*> handled_;
90
91 /// fixed_ - Intervals that correspond to machine registers.
92 ///
93 IntervalPtrs fixed_;
94
95 /// active_ - Intervals that are currently being processed, and which have a
96 /// live range active for the current point.
97 IntervalPtrs active_;
98
99 /// inactive_ - Intervals that are currently being processed, but which have
100 /// a hold at the current point.
101 IntervalPtrs inactive_;
102
103 typedef std::priority_queue<LiveInterval*,
Owen Andersonba926a32008-08-15 18:49:41 +0000104 SmallVector<LiveInterval*, 64>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105 greater_ptr<LiveInterval> > IntervalHeap;
106 IntervalHeap unhandled_;
107 std::auto_ptr<PhysRegTracker> prt_;
108 std::auto_ptr<VirtRegMap> vrm_;
109 std::auto_ptr<Spiller> spiller_;
110
111 public:
112 virtual const char* getPassName() const {
113 return "Linear Scan Register Allocator";
114 }
115
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.addRequired<LiveIntervals>();
Owen Andersonbac9ae22008-10-07 20:22:28 +0000118 if (StrongPHIElim)
119 AU.addRequiredID(StrongPHIEliminationID);
David Greene1d80f1b2007-09-06 16:18:45 +0000120 // Make sure PassManager knows which analyses to make available
121 // to coalescing and which analyses coalescing invalidates.
122 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng99dcc172008-10-23 20:43:13 +0000123 if (PreSplitIntervals)
124 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng14f8a502008-06-04 09:18:41 +0000125 AU.addRequired<LiveStacks>();
126 AU.addPreserved<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000127 AU.addRequired<MachineLoopInfo>();
Bill Wendling62264362008-01-04 20:54:55 +0000128 AU.addPreserved<MachineLoopInfo>();
129 AU.addPreservedID(MachineDominatorsID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 MachineFunctionPass::getAnalysisUsage(AU);
131 }
132
133 /// runOnMachineFunction - register allocate the whole function
134 bool runOnMachineFunction(MachineFunction&);
135
136 private:
137 /// linearScan - the linear scan algorithm
138 void linearScan();
139
140 /// initIntervalSets - initialize the interval sets.
141 ///
142 void initIntervalSets();
143
144 /// processActiveIntervals - expire old intervals and move non-overlapping
145 /// ones to the inactive list.
146 void processActiveIntervals(unsigned CurPoint);
147
148 /// processInactiveIntervals - expire old intervals and move overlapping
149 /// ones to the active list.
150 void processInactiveIntervals(unsigned CurPoint);
151
152 /// assignRegOrStackSlotAtInterval - assign a register if one
153 /// is available, or spill.
154 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
155
Evan Chengc5952452008-06-20 21:45:16 +0000156 /// findIntervalsToSpill - Determine the intervals to spill for the
157 /// specified interval. It's passed the physical registers whose spill
158 /// weight is the lowest among all the registers whose live intervals
159 /// conflict with the interval.
160 void findIntervalsToSpill(LiveInterval *cur,
161 std::vector<std::pair<unsigned,float> > &Candidates,
162 unsigned NumCands,
163 SmallVector<LiveInterval*, 8> &SpillIntervals);
164
Evan Chengc4c75f52007-11-03 07:20:12 +0000165 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
166 /// try allocate the definition the same register as the source register
167 /// if the register is not defined during live time of the interval. This
168 /// eliminate a copy. This is used to coalesce copies which were not
169 /// coalesced away before allocation either due to dest and src being in
170 /// different register classes or because the coalescer was overly
171 /// conservative.
172 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
173
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 ///
175 /// register handling helpers
176 ///
177
178 /// getFreePhysReg - return a free physical register for this virtual
179 /// register interval if we have one, otherwise return 0.
180 unsigned getFreePhysReg(LiveInterval* cur);
181
182 /// assignVirt2StackSlot - assigns this virtual register to a
183 /// stack slot. returns the stack slot
184 int assignVirt2StackSlot(unsigned virtReg);
185
186 void ComputeRelatedRegClasses();
187
188 template <typename ItTy>
189 void printIntervals(const char* const str, ItTy i, ItTy e) const {
190 if (str) DOUT << str << " intervals:\n";
191 for (; i != e; ++i) {
192 DOUT << "\t" << *i->first << " -> ";
193 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000194 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 reg = vrm_->getPhys(reg);
196 }
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000197 DOUT << tri_->getName(reg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 }
199 }
200 };
201 char RALinScan::ID = 0;
202}
203
Evan Cheng14f8a502008-06-04 09:18:41 +0000204static RegisterPass<RALinScan>
205X("linearscan-regalloc", "Linear Scan Register Allocator");
206
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman1e57df32008-02-10 18:45:23 +0000208 const TargetRegisterInfo &TRI = *tri_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209
210 // First pass, add all reg classes to the union, and determine at least one
211 // reg class that each register is in.
212 bool HasAliases = false;
Dan Gohman1e57df32008-02-10 18:45:23 +0000213 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
214 E = TRI.regclass_end(); RCI != E; ++RCI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 RelatedRegClasses.insert(*RCI);
216 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
217 I != E; ++I) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000218 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219
220 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
221 if (PRC) {
222 // Already processed this register. Just make sure we know that
223 // multiple register classes share a register.
224 RelatedRegClasses.unionSets(PRC, *RCI);
225 } else {
226 PRC = *RCI;
227 }
228 }
229 }
230
231 // Second pass, now that we know conservatively what register classes each reg
232 // belongs to, add info about aliases. We don't need to do this for targets
233 // without register aliases.
234 if (HasAliases)
Owen Anderson4a472712008-08-13 23:36:23 +0000235 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
237 I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000238 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
240}
241
Evan Chengc4c75f52007-11-03 07:20:12 +0000242/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
243/// try allocate the definition the same register as the source register
244/// if the register is not defined during live time of the interval. This
245/// eliminate a copy. This is used to coalesce copies which were not
246/// coalesced away before allocation either due to dest and src being in
247/// different register classes or because the coalescer was overly
248/// conservative.
249unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Chengb6aa6712007-11-04 08:32:21 +0000250 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc4c75f52007-11-03 07:20:12 +0000251 return Reg;
252
Evan Chengdb4b2602009-01-20 00:16:18 +0000253 VNInfo *vni = cur.begin()->valno;
Evan Chengc4c75f52007-11-03 07:20:12 +0000254 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
255 return Reg;
256 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Chengf97496a2009-01-20 19:12:24 +0000257 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
258 if (!CopyMI ||
259 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000260 return Reg;
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000261 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000262 if (!vrm_->isAssignedReg(SrcReg))
263 return Reg;
264 else
265 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000266 }
Evan Chengc4c75f52007-11-03 07:20:12 +0000267 if (Reg == SrcReg)
268 return Reg;
269
Evan Cheng06b74c52008-09-18 22:38:47 +0000270 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc4c75f52007-11-03 07:20:12 +0000271 if (!RC->contains(SrcReg))
272 return Reg;
273
274 // Try to coalesce.
275 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000276 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling8eeb9792008-02-26 21:11:01 +0000277 << '\n';
Evan Chengc4c75f52007-11-03 07:20:12 +0000278 vrm_->clearVirt(cur.reg);
279 vrm_->assignVirt2Phys(cur.reg, SrcReg);
280 ++NumCoalesce;
281 return SrcReg;
282 }
283
284 return Reg;
285}
286
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
288 mf_ = &fn;
Evan Chengc5952452008-06-20 21:45:16 +0000289 mri_ = &fn.getRegInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 tm_ = &fn.getTarget();
Dan Gohman1e57df32008-02-10 18:45:23 +0000291 tri_ = tm_->getRegisterInfo();
Evan Chengc4c75f52007-11-03 07:20:12 +0000292 tii_ = tm_->getInstrInfo();
Dan Gohman1e57df32008-02-10 18:45:23 +0000293 allocatableRegs_ = tri_->getAllocatableSet(fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng14f8a502008-06-04 09:18:41 +0000295 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng26d17df2007-12-11 02:09:15 +0000296 loopInfo = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297
David Greene1d80f1b2007-09-06 16:18:45 +0000298 // We don't run the coalescer here because we have no reason to
299 // interact with it. If the coalescer requires interaction, it
300 // won't do anything. If it doesn't require interaction, we assume
301 // it was run as a separate pass.
302
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 // If this is the first function compiled, compute the related reg classes.
304 if (RelatedRegClasses.empty())
305 ComputeRelatedRegClasses();
306
Dan Gohman1e57df32008-02-10 18:45:23 +0000307 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 vrm_.reset(new VirtRegMap(*mf_));
309 if (!spiller_.get()) spiller_.reset(createSpiller());
310
311 initIntervalSets();
312
313 linearScan();
314
315 // Rewrite spill code and update the PhysRegsUsed set.
316 spiller_->runOnMachineFunction(*mf_, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 vrm_.reset(); // Free the VirtRegMap
318
Dan Gohman79a9f152008-06-23 23:51:16 +0000319 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 fixed_.clear();
321 active_.clear();
322 inactive_.clear();
323 handled_.clear();
324
325 return true;
326}
327
328/// initIntervalSets - initialize the interval sets.
329///
330void RALinScan::initIntervalSets()
331{
332 assert(unhandled_.empty() && fixed_.empty() &&
333 active_.empty() && inactive_.empty() &&
334 "interval sets should be empty on initialization");
335
Owen Andersonba926a32008-08-15 18:49:41 +0000336 handled_.reserve(li_->getNumIntervals());
337
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000339 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng06b74c52008-09-18 22:38:47 +0000340 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson348d1d82008-08-13 21:49:13 +0000341 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 } else
Owen Anderson348d1d82008-08-13 21:49:13 +0000343 unhandled_.push(i->second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 }
345}
346
347void RALinScan::linearScan()
348{
349 // linear scan algorithm
350 DOUT << "********** LINEAR SCAN **********\n";
351 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
352
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354
355 while (!unhandled_.empty()) {
356 // pick the interval with the earliest start point
357 LiveInterval* cur = unhandled_.top();
358 unhandled_.pop();
Evan Chengd48f2bc2007-10-16 21:09:14 +0000359 ++NumIters;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
361
Evan Chenga3186992008-04-03 16:40:27 +0000362 if (!cur->empty()) {
363 processActiveIntervals(cur->beginNumber());
364 processInactiveIntervals(cur->beginNumber());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365
Evan Chenga3186992008-04-03 16:40:27 +0000366 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
367 "Can only allocate virtual registers!");
368 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369
370 // Allocating a virtual register. try to find a free
371 // physical register or spill an interval (possibly this one) in order to
372 // assign it one.
373 assignRegOrStackSlotAtInterval(cur);
374
375 DEBUG(printIntervals("active", active_.begin(), active_.end()));
376 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
377 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378
379 // expire any remaining active intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000380 while (!active_.empty()) {
381 IntervalPtr &IP = active_.back();
382 unsigned reg = IP.first->reg;
383 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000384 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 "Can only allocate virtual registers!");
386 reg = vrm_->getPhys(reg);
387 prt_->delRegUse(reg);
Evan Chengd48f2bc2007-10-16 21:09:14 +0000388 active_.pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 }
390
391 // expire any remaining inactive intervals
Evan Chengd48f2bc2007-10-16 21:09:14 +0000392 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling1817ab82007-11-15 00:40:48 +0000393 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Chengd48f2bc2007-10-16 21:09:14 +0000394 DOUT << "\tinterval " << *i->first << " expired\n");
395 inactive_.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
Evan Chengcecc8222007-11-17 00:40:40 +0000397 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Chengf5cdf122007-10-17 02:12:22 +0000398 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000399 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Chengf5cdf122007-10-17 02:12:22 +0000400 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000401 LiveInterval &cur = *i->second;
Evan Chengf5cdf122007-10-17 02:12:22 +0000402 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000403 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Chengcecc8222007-11-17 00:40:40 +0000404 if (isPhys)
Owen Anderson348d1d82008-08-13 21:49:13 +0000405 Reg = cur.reg;
Evan Chengf5cdf122007-10-17 02:12:22 +0000406 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000407 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Chengf5cdf122007-10-17 02:12:22 +0000408 if (!Reg)
409 continue;
Evan Chengcecc8222007-11-17 00:40:40 +0000410 // Ignore splited live intervals.
411 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
412 continue;
Evan Chengf5cdf122007-10-17 02:12:22 +0000413 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
414 I != E; ++I) {
415 const LiveRange &LR = *I;
Evan Cheng84f9fc22008-10-29 05:06:14 +0000416 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Chengf5cdf122007-10-17 02:12:22 +0000417 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
418 if (LiveInMBBs[i] != EntryMBB)
419 LiveInMBBs[i]->addLiveIn(Reg);
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000420 LiveInMBBs.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 }
422 }
423 }
424
425 DOUT << *vrm_;
426}
427
428/// processActiveIntervals - expire old intervals and move non-overlapping ones
429/// to the inactive list.
430void RALinScan::processActiveIntervals(unsigned CurPoint)
431{
432 DOUT << "\tprocessing active intervals:\n";
433
434 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
435 LiveInterval *Interval = active_[i].first;
436 LiveInterval::iterator IntervalPos = active_[i].second;
437 unsigned reg = Interval->reg;
438
439 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
440
441 if (IntervalPos == Interval->end()) { // Remove expired intervals.
442 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000443 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 "Can only allocate virtual registers!");
445 reg = vrm_->getPhys(reg);
446 prt_->delRegUse(reg);
447
448 // Pop off the end of the list.
449 active_[i] = active_.back();
450 active_.pop_back();
451 --i; --e;
452
453 } else if (IntervalPos->start > CurPoint) {
454 // Move inactive intervals to inactive list.
455 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000456 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 "Can only allocate virtual registers!");
458 reg = vrm_->getPhys(reg);
459 prt_->delRegUse(reg);
460 // add to inactive.
461 inactive_.push_back(std::make_pair(Interval, IntervalPos));
462
463 // Pop off the end of the list.
464 active_[i] = active_.back();
465 active_.pop_back();
466 --i; --e;
467 } else {
468 // Otherwise, just update the iterator position.
469 active_[i].second = IntervalPos;
470 }
471 }
472}
473
474/// processInactiveIntervals - expire old intervals and move overlapping
475/// ones to the active list.
476void RALinScan::processInactiveIntervals(unsigned CurPoint)
477{
478 DOUT << "\tprocessing inactive intervals:\n";
479
480 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
481 LiveInterval *Interval = inactive_[i].first;
482 LiveInterval::iterator IntervalPos = inactive_[i].second;
483 unsigned reg = Interval->reg;
484
485 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
486
487 if (IntervalPos == Interval->end()) { // remove expired intervals.
488 DOUT << "\t\tinterval " << *Interval << " expired\n";
489
490 // Pop off the end of the list.
491 inactive_[i] = inactive_.back();
492 inactive_.pop_back();
493 --i; --e;
494 } else if (IntervalPos->start <= CurPoint) {
495 // move re-activated intervals in active list
496 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman1e57df32008-02-10 18:45:23 +0000497 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 "Can only allocate virtual registers!");
499 reg = vrm_->getPhys(reg);
500 prt_->addRegUse(reg);
501 // add to active
502 active_.push_back(std::make_pair(Interval, IntervalPos));
503
504 // Pop off the end of the list.
505 inactive_[i] = inactive_.back();
506 inactive_.pop_back();
507 --i; --e;
508 } else {
509 // Otherwise, just update the iterator position.
510 inactive_[i].second = IntervalPos;
511 }
512 }
513}
514
515/// updateSpillWeights - updates the spill weights of the specifed physical
516/// register and its weight.
517static void updateSpillWeights(std::vector<float> &Weights,
518 unsigned reg, float weight,
Dan Gohman1e57df32008-02-10 18:45:23 +0000519 const TargetRegisterInfo *TRI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 Weights[reg] += weight;
Dan Gohman1e57df32008-02-10 18:45:23 +0000521 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 Weights[*as] += weight;
523}
524
525static
526RALinScan::IntervalPtrs::iterator
527FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
528 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
529 I != E; ++I)
530 if (I->first == LI) return I;
531 return IP.end();
532}
533
534static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
535 for (unsigned i = 0, e = V.size(); i != e; ++i) {
536 RALinScan::IntervalPtr &IP = V[i];
537 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
538 IP.second, Point);
539 if (I != IP.first->begin()) --I;
540 IP.second = I;
541 }
542}
543
Evan Cheng14f8a502008-06-04 09:18:41 +0000544/// addStackInterval - Create a LiveInterval for stack if the specified live
545/// interval has been spilled.
546static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Chengba221ca2008-06-06 07:54:39 +0000547 LiveIntervals *li_, float &Weight,
548 VirtRegMap &vrm_) {
Evan Cheng14f8a502008-06-04 09:18:41 +0000549 int SS = vrm_.getStackSlot(cur->reg);
550 if (SS == VirtRegMap::NO_STACK_SLOT)
551 return;
552 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Chengba221ca2008-06-06 07:54:39 +0000553 SI.weight += Weight;
554
Evan Cheng14f8a502008-06-04 09:18:41 +0000555 VNInfo *VNI;
Evan Cheng29f36f52008-10-29 08:39:34 +0000556 if (SI.hasAtLeastOneValue())
Evan Cheng14f8a502008-06-04 09:18:41 +0000557 VNI = SI.getValNumInfo(0);
558 else
559 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
560
561 LiveInterval &RI = li_->getInterval(cur->reg);
562 // FIXME: This may be overly conservative.
563 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng14f8a502008-06-04 09:18:41 +0000564}
565
Evan Chengc5952452008-06-20 21:45:16 +0000566/// getConflictWeight - Return the number of conflicts between cur
567/// live interval and defs and uses of Reg weighted by loop depthes.
568static float getConflictWeight(LiveInterval *cur, unsigned Reg,
569 LiveIntervals *li_,
570 MachineRegisterInfo *mri_,
571 const MachineLoopInfo *loopInfo) {
572 float Conflicts = 0;
573 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
574 E = mri_->reg_end(); I != E; ++I) {
575 MachineInstr *MI = &*I;
576 if (cur->liveAt(li_->getInstructionIndex(MI))) {
577 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
578 Conflicts += powf(10.0f, (float)loopDepth);
579 }
580 }
581 return Conflicts;
582}
583
584/// findIntervalsToSpill - Determine the intervals to spill for the
585/// specified interval. It's passed the physical registers whose spill
586/// weight is the lowest among all the registers whose live intervals
587/// conflict with the interval.
588void RALinScan::findIntervalsToSpill(LiveInterval *cur,
589 std::vector<std::pair<unsigned,float> > &Candidates,
590 unsigned NumCands,
591 SmallVector<LiveInterval*, 8> &SpillIntervals) {
592 // We have figured out the *best* register to spill. But there are other
593 // registers that are pretty good as well (spill weight within 3%). Spill
594 // the one that has fewest defs and uses that conflict with cur.
595 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
596 SmallVector<LiveInterval*, 8> SLIs[3];
597
598 DOUT << "\tConsidering " << NumCands << " candidates: ";
599 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
600 DOUT << tri_->getName(Candidates[i].first) << " ";
601 DOUT << "\n";);
602
603 // Calculate the number of conflicts of each candidate.
604 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
605 unsigned Reg = i->first->reg;
606 unsigned PhysReg = vrm_->getPhys(Reg);
607 if (!cur->overlapsFrom(*i->first, i->second))
608 continue;
609 for (unsigned j = 0; j < NumCands; ++j) {
610 unsigned Candidate = Candidates[j].first;
611 if (tri_->regsOverlap(PhysReg, Candidate)) {
612 if (NumCands > 1)
613 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
614 SLIs[j].push_back(i->first);
615 }
616 }
617 }
618
619 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
620 unsigned Reg = i->first->reg;
621 unsigned PhysReg = vrm_->getPhys(Reg);
622 if (!cur->overlapsFrom(*i->first, i->second-1))
623 continue;
624 for (unsigned j = 0; j < NumCands; ++j) {
625 unsigned Candidate = Candidates[j].first;
626 if (tri_->regsOverlap(PhysReg, Candidate)) {
627 if (NumCands > 1)
628 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
629 SLIs[j].push_back(i->first);
630 }
631 }
632 }
633
634 // Which is the best candidate?
635 unsigned BestCandidate = 0;
636 float MinConflicts = Conflicts[0];
637 for (unsigned i = 1; i != NumCands; ++i) {
638 if (Conflicts[i] < MinConflicts) {
639 BestCandidate = i;
640 MinConflicts = Conflicts[i];
641 }
642 }
643
644 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
645 std::back_inserter(SpillIntervals));
646}
647
648namespace {
649 struct WeightCompare {
650 typedef std::pair<unsigned, float> RegWeightPair;
651 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
652 return LHS.second < RHS.second;
653 }
654 };
655}
656
657static bool weightsAreClose(float w1, float w2) {
658 if (!NewHeuristic)
659 return false;
660
661 float diff = w1 - w2;
662 if (diff <= 0.02f) // Within 0.02f
663 return true;
664 return (diff / w2) <= 0.05f; // Within 5%.
665}
666
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
668/// spill.
669void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
670{
671 DOUT << "\tallocating current interval: ";
672
Evan Chenga3186992008-04-03 16:40:27 +0000673 // This is an implicitly defined live interval, just assign any register.
Evan Cheng06b74c52008-09-18 22:38:47 +0000674 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chenga3186992008-04-03 16:40:27 +0000675 if (cur->empty()) {
676 unsigned physReg = cur->preference;
677 if (!physReg)
678 physReg = *RC->allocation_order_begin(*mf_);
679 DOUT << tri_->getName(physReg) << '\n';
680 // Note the register is not really in use.
681 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chenga3186992008-04-03 16:40:27 +0000682 return;
683 }
684
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 PhysRegTracker backupPrt = *prt_;
686
687 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
688 unsigned StartPosition = cur->beginNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc4c75f52007-11-03 07:20:12 +0000690
Evan Chengdb4b2602009-01-20 00:16:18 +0000691 // If start of this live interval is defined by a move instruction and its
692 // source is assigned a physical register that is compatible with the target
693 // register class, then we should try to assign it the same register.
Evan Chengc4c75f52007-11-03 07:20:12 +0000694 // This can happen when the move is from a larger register class to a smaller
695 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengdb4b2602009-01-20 00:16:18 +0000696 if (!cur->preference && cur->hasAtLeastOneValue()) {
697 VNInfo *vni = cur->begin()->valno;
Evan Chengc4c75f52007-11-03 07:20:12 +0000698 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
699 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Chengf97496a2009-01-20 19:12:24 +0000700 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
701 if (CopyMI &&
702 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000703 unsigned Reg = 0;
Dan Gohman1e57df32008-02-10 18:45:23 +0000704 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000705 Reg = SrcReg;
706 else if (vrm_->isAssignedReg(SrcReg))
707 Reg = vrm_->getPhys(SrcReg);
708 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
709 cur->preference = Reg;
710 }
711 }
712 }
713
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 // for every interval in inactive we overlap with, mark the
715 // register as not free and update spill weights.
716 for (IntervalPtrs::const_iterator i = inactive_.begin(),
717 e = inactive_.end(); i != e; ++i) {
718 unsigned Reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000719 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 "Can only allocate virtual registers!");
Evan Cheng06b74c52008-09-18 22:38:47 +0000721 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 // If this is not in a related reg class to the register we're allocating,
723 // don't check it.
724 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
725 cur->overlapsFrom(*i->first, i->second-1)) {
726 Reg = vrm_->getPhys(Reg);
727 prt_->addRegUse(Reg);
728 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
729 }
730 }
731
732 // Speculatively check to see if we can get a register right now. If not,
733 // we know we won't be able to by adding more constraints. If so, we can
734 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
735 // is very bad (it contains all callee clobbered registers for any functions
736 // with a call), so we want to avoid doing that if possible.
737 unsigned physReg = getFreePhysReg(cur);
Evan Cheng14cc83f2008-03-11 07:19:34 +0000738 unsigned BestPhysReg = physReg;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 if (physReg) {
740 // We got a register. However, if it's in the fixed_ list, we might
741 // conflict with it. Check to see if we conflict with it or any of its
742 // aliases.
Evan Chengc4c75f52007-11-03 07:20:12 +0000743 SmallSet<unsigned, 8> RegAliases;
Dan Gohman1e57df32008-02-10 18:45:23 +0000744 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 RegAliases.insert(*AS);
746
747 bool ConflictsWithFixed = false;
748 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
749 IntervalPtr &IP = fixed_[i];
750 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
751 // Okay, this reg is on the fixed list. Check to see if we actually
752 // conflict.
753 LiveInterval *I = IP.first;
754 if (I->endNumber() > StartPosition) {
755 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
756 IP.second = II;
757 if (II != I->begin() && II->start > StartPosition)
758 --II;
759 if (cur->overlapsFrom(*I, II)) {
760 ConflictsWithFixed = true;
761 break;
762 }
763 }
764 }
765 }
766
767 // Okay, the register picked by our speculative getFreePhysReg call turned
768 // out to be in use. Actually add all of the conflicting fixed registers to
769 // prt so we can do an accurate query.
770 if (ConflictsWithFixed) {
771 // For every interval in fixed we overlap with, mark the register as not
772 // free and update spill weights.
773 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
774 IntervalPtr &IP = fixed_[i];
775 LiveInterval *I = IP.first;
776
777 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
778 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
779 I->endNumber() > StartPosition) {
780 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
781 IP.second = II;
782 if (II != I->begin() && II->start > StartPosition)
783 --II;
784 if (cur->overlapsFrom(*I, II)) {
785 unsigned reg = I->reg;
786 prt_->addRegUse(reg);
787 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
788 }
789 }
790 }
791
792 // Using the newly updated prt_ object, which includes conflicts in the
793 // future, see if there are any registers available.
794 physReg = getFreePhysReg(cur);
795 }
796 }
797
798 // Restore the physical register tracker, removing information about the
799 // future.
800 *prt_ = backupPrt;
801
802 // if we find a free register, we are done: assign this virtual to
803 // the free physical register and add this interval to the active
804 // list.
805 if (physReg) {
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000806 DOUT << tri_->getName(physReg) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 vrm_->assignVirt2Phys(cur->reg, physReg);
808 prt_->addRegUse(physReg);
809 active_.push_back(std::make_pair(cur, cur->begin()));
810 handled_.push_back(cur);
811 return;
812 }
813 DOUT << "no free registers\n";
814
815 // Compile the spill weights into an array that is better for scanning.
Evan Chengc5952452008-06-20 21:45:16 +0000816 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 for (std::vector<std::pair<unsigned, float> >::iterator
818 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman1e57df32008-02-10 18:45:23 +0000819 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820
821 // for each interval in active, update spill weights.
822 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
823 i != e; ++i) {
824 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +0000825 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 "Can only allocate virtual registers!");
827 reg = vrm_->getPhys(reg);
Dan Gohman1e57df32008-02-10 18:45:23 +0000828 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 }
830
831 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
832
833 // Find a register to spill.
834 float minWeight = HUGE_VALF;
Evan Chengc5952452008-06-20 21:45:16 +0000835 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
836
837 bool Found = false;
838 std::vector<std::pair<unsigned,float> > RegsWeights;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
840 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
841 e = RC->allocation_order_end(*mf_); i != e; ++i) {
842 unsigned reg = *i;
Evan Chengc5952452008-06-20 21:45:16 +0000843 float regWeight = SpillWeights[reg];
844 if (minWeight > regWeight)
845 Found = true;
846 RegsWeights.push_back(std::make_pair(reg, regWeight));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 }
848
849 // If we didn't find a register that is spillable, try aliases?
Evan Chengc5952452008-06-20 21:45:16 +0000850 if (!Found) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
852 e = RC->allocation_order_end(*mf_); i != e; ++i) {
853 unsigned reg = *i;
854 // No need to worry about if the alias register size < regsize of RC.
855 // We are going to spill all registers that alias it anyway.
Evan Chengc5952452008-06-20 21:45:16 +0000856 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
857 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng14cc83f2008-03-11 07:19:34 +0000858 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 }
Evan Chengc5952452008-06-20 21:45:16 +0000860
861 // Sort all potential spill candidates by weight.
862 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
863 minReg = RegsWeights[0].first;
864 minWeight = RegsWeights[0].second;
865 if (minWeight == HUGE_VALF) {
866 // All registers must have inf weight. Just grab one!
867 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona0e65132008-07-22 22:46:49 +0000868 if (cur->weight == HUGE_VALF ||
Evan Chengaf3c4e32008-09-20 01:28:05 +0000869 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Chengc5952452008-06-20 21:45:16 +0000870 // Spill a physical register around defs and uses.
871 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Chengaf3c4e32008-09-20 01:28:05 +0000872 assignRegOrStackSlotAtInterval(cur);
873 return;
874 }
Evan Chengc5952452008-06-20 21:45:16 +0000875 }
876
877 // Find up to 3 registers to consider as spill candidates.
878 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
879 while (LastCandidate > 1) {
880 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
881 break;
882 --LastCandidate;
883 }
884
885 DOUT << "\t\tregister(s) with min weight(s): ";
886 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
887 DOUT << tri_->getName(RegsWeights[i].first)
888 << " (" << RegsWeights[i].second << ")\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889
890 // if the current has the minimum weight, we need to spill it and
891 // add any added intervals back to unhandled, and restart
892 // linearscan.
893 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
894 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Chengba221ca2008-06-06 07:54:39 +0000895 float SSWeight;
Evan Chengc84ea132008-09-30 15:44:16 +0000896 SmallVector<LiveInterval*, 8> spillIs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 std::vector<LiveInterval*> added =
Evan Chengc84ea132008-09-30 15:44:16 +0000898 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Chengba221ca2008-06-06 07:54:39 +0000899 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 if (added.empty())
901 return; // Early exit if all spills were folded.
902
903 // Merge added with unhandled. Note that we know that
904 // addIntervalsForSpills returns intervals sorted by their starting
905 // point.
906 for (unsigned i = 0, e = added.size(); i != e; ++i)
907 unhandled_.push(added[i]);
908 return;
909 }
910
911 ++NumBacktracks;
912
913 // push the current interval back to unhandled since we are going
914 // to re-run at least this iteration. Since we didn't modify it it
915 // should go back right in the front of the list
916 unhandled_.push(cur);
917
Dan Gohman1e57df32008-02-10 18:45:23 +0000918 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 "did not choose a register to spill?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920
Evan Chengc5952452008-06-20 21:45:16 +0000921 // We spill all intervals aliasing the register with
922 // minimum weight, rollback to the interval with the earliest
923 // start point and let the linear scan algorithm run again
924 SmallVector<LiveInterval*, 8> spillIs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925
Evan Chengc5952452008-06-20 21:45:16 +0000926 // Determine which intervals have to be spilled.
927 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
928
929 // Set of spilled vregs (used later to rollback properly)
930 SmallSet<unsigned, 8> spilled;
931
932 // The earliest start of a Spilled interval indicates up to where
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933 // in handled we need to roll back
934 unsigned earliestStart = cur->beginNumber();
935
Evan Chengc5952452008-06-20 21:45:16 +0000936 // Spill live intervals of virtual regs mapped to the physical register we
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 // want to clear (and its aliases). We only spill those that overlap with the
938 // current interval as the rest do not affect its allocation. we also keep
939 // track of the earliest start of all spilled live intervals since this will
940 // mark our rollback point.
Evan Chengc5952452008-06-20 21:45:16 +0000941 std::vector<LiveInterval*> added;
942 while (!spillIs.empty()) {
943 LiveInterval *sli = spillIs.back();
944 spillIs.pop_back();
945 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
946 earliestStart = std::min(earliestStart, sli->beginNumber());
947 float SSWeight;
948 std::vector<LiveInterval*> newIs =
Evan Chengc84ea132008-09-30 15:44:16 +0000949 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Chengc5952452008-06-20 21:45:16 +0000950 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
951 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
952 spilled.insert(sli->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 }
954
955 DOUT << "\t\trolling back to: " << earliestStart << '\n';
956
957 // Scan handled in reverse order up to the earliest start of a
958 // spilled live interval and undo each one, restoring the state of
959 // unhandled.
960 while (!handled_.empty()) {
961 LiveInterval* i = handled_.back();
962 // If this interval starts before t we are done.
963 if (i->beginNumber() < earliestStart)
964 break;
965 DOUT << "\t\t\tundo changes for: " << *i << '\n';
966 handled_.pop_back();
967
968 // When undoing a live interval allocation we must know if it is active or
969 // inactive to properly update the PhysRegTracker and the VirtRegMap.
970 IntervalPtrs::iterator it;
971 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
972 active_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000973 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 if (!spilled.count(i->reg))
975 unhandled_.push(i);
976 prt_->delRegUse(vrm_->getPhys(i->reg));
977 vrm_->clearVirt(i->reg);
978 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
979 inactive_.erase(it);
Dan Gohman1e57df32008-02-10 18:45:23 +0000980 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 if (!spilled.count(i->reg))
982 unhandled_.push(i);
983 vrm_->clearVirt(i->reg);
984 } else {
Dan Gohman1e57df32008-02-10 18:45:23 +0000985 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 "Can only allocate virtual registers!");
987 vrm_->clearVirt(i->reg);
988 unhandled_.push(i);
989 }
Evan Chengb6aa6712007-11-04 08:32:21 +0000990
991 // It interval has a preference, it must be defined by a copy. Clear the
992 // preference now since the source interval allocation may have been undone
993 // as well.
994 i->preference = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 }
996
997 // Rewind the iterators in the active, inactive, and fixed lists back to the
998 // point we reverted to.
999 RevertVectorIteratorsTo(active_, earliestStart);
1000 RevertVectorIteratorsTo(inactive_, earliestStart);
1001 RevertVectorIteratorsTo(fixed_, earliestStart);
1002
1003 // scan the rest and undo each interval that expired after t and
1004 // insert it in active (the next iteration of the algorithm will
1005 // put it in inactive if required)
1006 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1007 LiveInterval *HI = handled_[i];
1008 if (!HI->expiredAt(earliestStart) &&
1009 HI->expiredAt(cur->beginNumber())) {
1010 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1011 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman1e57df32008-02-10 18:45:23 +00001012 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 prt_->addRegUse(vrm_->getPhys(HI->reg));
1014 }
1015 }
1016
1017 // merge added with unhandled
1018 for (unsigned i = 0, e = added.size(); i != e; ++i)
1019 unhandled_.push(added[i]);
1020}
1021
1022/// getFreePhysReg - return a free physical register for this virtual register
1023/// interval if we have one, otherwise return 0.
1024unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001025 SmallVector<unsigned, 256> inactiveCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 unsigned MaxInactiveCount = 0;
1027
Evan Cheng06b74c52008-09-18 22:38:47 +00001028 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1030
1031 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1032 i != e; ++i) {
1033 unsigned reg = i->first->reg;
Dan Gohman1e57df32008-02-10 18:45:23 +00001034 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035 "Can only allocate virtual registers!");
1036
1037 // If this is not in a related reg class to the register we're allocating,
1038 // don't check it.
Evan Cheng06b74c52008-09-18 22:38:47 +00001039 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1041 reg = vrm_->getPhys(reg);
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001042 if (inactiveCounts.size() <= reg)
1043 inactiveCounts.resize(reg+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 ++inactiveCounts[reg];
1045 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1046 }
1047 }
1048
1049 unsigned FreeReg = 0;
1050 unsigned FreeRegInactiveCount = 0;
1051
1052 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen94464072008-09-24 01:07:17 +00001053 // available first.
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001054 if (cur->preference) {
Dale Johannesend9e4fd62008-09-20 02:03:04 +00001055 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen94464072008-09-24 01:07:17 +00001056 RC->contains(cur->preference)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 DOUT << "\t\tassigned the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +00001058 << tri_->getName(cur->preference) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 return cur->preference;
1060 } else
1061 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendling9b0baeb2008-02-26 21:47:57 +00001062 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00001063 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064
1065 // Scan for the first available register.
1066 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1067 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf091bd2008-03-24 23:28:21 +00001068 assert(I != E && "No allocatable register in this register class!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 for (; I != E; ++I)
Dale Johannesen94464072008-09-24 01:07:17 +00001070 if (prt_->isRegAvail(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 FreeReg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001072 if (FreeReg < inactiveCounts.size())
1073 FreeRegInactiveCount = inactiveCounts[FreeReg];
1074 else
1075 FreeRegInactiveCount = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 break;
1077 }
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001078
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 // If there are no free regs, or if this reg has the max inactive count,
1080 // return this register.
1081 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1082
1083 // Continue scanning the registers, looking for the one with the highest
1084 // inactive count. Alkis found that this reduced register pressure very
1085 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1086 // reevaluated now.
1087 for (; I != E; ++I) {
1088 unsigned Reg = *I;
Chris Lattner9f6dc2c2008-02-26 22:08:41 +00001089 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen94464072008-09-24 01:07:17 +00001090 FreeRegInactiveCount < inactiveCounts[Reg]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091 FreeReg = Reg;
1092 FreeRegInactiveCount = inactiveCounts[Reg];
1093 if (FreeRegInactiveCount == MaxInactiveCount)
1094 break; // We found the one with the max inactive count.
1095 }
1096 }
1097
1098 return FreeReg;
1099}
1100
1101FunctionPass* llvm::createLinearScanRegisterAllocator() {
1102 return new RALinScan();
1103}