blob: c6f714a9cb7d59bb21505e4852faacd929327027 [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001//===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a linear scan register allocator.
11//
12//===----------------------------------------------------------------------===//
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +000013
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000014#define DEBUG_TYPE "regalloc"
Chris Lattnerb9805782005-08-23 22:27:31 +000015#include "PhysRegTracker.h"
16#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000017#include "llvm/Function.h"
Evan Cheng3f32d652008-06-04 09:18:41 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/LiveStackAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000025#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/Target/TargetMachine.h"
Evan Chengc92da382007-11-03 07:20:12 +000029#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000030#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000035#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000036#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000037#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000038#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000040using namespace llvm;
41
Chris Lattnercd3245a2006-12-19 22:41:21 +000042STATISTIC(NumIters , "Number of iterations performed");
43STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000044STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000045
Evan Cheng3e172252008-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
Chris Lattnercd3245a2006-12-19 22:41:21 +000051static RegisterRegAlloc
52linearscanRegAlloc("linearscan", " linear scan register allocator",
53 createLinearScanRegisterAllocator);
54
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000055namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000056 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000057 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000058 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000059
Chris Lattnercbb56252004-11-18 02:42:27 +000060 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000061 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000062 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000063 /// 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 Anderson97382162008-08-13 23:36:23 +000067 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000068
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000070 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000071 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000072 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000073 const TargetInstrInfo* tii_;
Chris Lattner84bc5422007-12-31 04:13:23 +000074 MachineRegisterInfo *reginfo_;
Evan Chengc92da382007-11-03 07:20:12 +000075 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000077 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000078 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +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
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000096 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000097 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +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_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000103
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 public:
105 virtual const char* getPassName() const {
106 return "Linear Scan Register Allocator";
107 }
108
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000110 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-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 Cheng3f32d652008-06-04 09:18:41 +0000114 AU.addRequired<LiveStacks>();
115 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000116 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119 MachineFunctionPass::getAnalysisUsage(AU);
120 }
121
122 /// runOnMachineFunction - register allocate the whole function
123 bool runOnMachineFunction(MachineFunction&);
124
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125 private:
126 /// linearScan - the linear scan algorithm
127 void linearScan();
128
Chris Lattnercbb56252004-11-18 02:42:27 +0000129 /// initIntervalSets - initialize the interval sets.
130 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 void initIntervalSets();
132
Chris Lattnercbb56252004-11-18 02:42:27 +0000133 /// processActiveIntervals - expire old intervals and move non-overlapping
134 /// ones to the inactive list.
135 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000136
Chris Lattnercbb56252004-11-18 02:42:27 +0000137 /// processInactiveIntervals - expire old intervals and move overlapping
138 /// ones to the active list.
139 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000141 /// assignRegOrStackSlotAtInterval - assign a register if one
142 /// is available, or spill.
143 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
144
Evan Cheng3e172252008-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 Chengc92da382007-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
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000163 ///
164 /// register handling helpers
165 ///
166
Chris Lattnercbb56252004-11-18 02:42:27 +0000167 /// getFreePhysReg - return a free physical register for this virtual
168 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000169 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
Chris Lattnerb9805782005-08-23 22:27:31 +0000175 void ComputeRelatedRegClasses();
176
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000177 template <typename ItTy>
178 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000179 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000180 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000181 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000182 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000183 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000184 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000185 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000186 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000187 }
188 }
189 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000190 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000191}
192
Evan Cheng3f32d652008-06-04 09:18:41 +0000193static RegisterPass<RALinScan>
194X("linearscan-regalloc", "Linear Scan Register Allocator");
195
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000196void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000197 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +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 Gohman6f0d0242008-02-10 18:45:23 +0000202 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
203 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000204 RelatedRegClasses.insert(*RCI);
205 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
206 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000207 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +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 Anderson97382162008-08-13 23:36:23 +0000224 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000225 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
226 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000227 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000228 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
229}
230
Evan Chengc92da382007-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 Cheng9aeaf752007-11-04 08:32:21 +0000239 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-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 Korobeynikov4aefd6b2008-02-20 12:07:57 +0000249 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000250 if (!vrm_->isAssignedReg(SrcReg))
251 return Reg;
252 else
253 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000254 }
Evan Chengc92da382007-11-03 07:20:12 +0000255 if (Reg == SrcReg)
256 return Reg;
257
Chris Lattner84bc5422007-12-31 04:13:23 +0000258 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc92da382007-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 Wendlinge6d088a2008-02-26 21:47:57 +0000264 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000265 << '\n';
Evan Chengc92da382007-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
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000275bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000276 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000277 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000278 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000279 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000280 tii_ = tm_->getInstrInfo();
Chris Lattner84bc5422007-12-31 04:13:23 +0000281 reginfo_ = &mf_->getRegInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000282 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000283 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000284 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000285 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000286
David Greene2c17c4d2007-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
Chris Lattnerb9805782005-08-23 22:27:31 +0000292 // If this is the first function compiled, compute the related reg classes.
293 if (RelatedRegClasses.empty())
294 ComputeRelatedRegClasses();
295
Dan Gohman6f0d0242008-02-10 18:45:23 +0000296 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000297 vrm_.reset(new VirtRegMap(*mf_));
298 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000299
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000301
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000302 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000303
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000304 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000306 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000307
Dan Gohman51cd9d62008-06-23 23:51:16 +0000308 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000309 fixed_.clear();
310 active_.clear();
311 inactive_.clear();
312 handled_.clear();
313
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000314 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000315}
316
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000317/// initIntervalSets - initialize the interval sets.
318///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000319void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000320{
321 assert(unhandled_.empty() && fixed_.empty() &&
322 active_.empty() && inactive_.empty() &&
323 "interval sets should be empty on initialization");
324
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000325 handled_.reserve(li_->getNumIntervals());
326
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000327 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-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()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000331 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000332 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000333 }
334}
335
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000336void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000337{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000338 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000339 DOUT << "********** LINEAR SCAN **********\n";
340 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000341
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000342 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343
344 while (!unhandled_.empty()) {
345 // pick the interval with the earliest start point
346 LiveInterval* cur = unhandled_.top();
347 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000348 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000349 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350
Evan Chengf30a49d2008-04-03 16:40:27 +0000351 if (!cur->empty()) {
352 processActiveIntervals(cur->beginNumber());
353 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354
Evan Chengf30a49d2008-04-03 16:40:27 +0000355 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
356 "Can only allocate virtual registers!");
357 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000358
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000359 // 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);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000363
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000364 DEBUG(printIntervals("active", active_.begin(), active_.end()));
365 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000367
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 // expire any remaining active intervals
Evan Cheng11923cc2007-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 Gohman6f0d0242008-02-10 18:45:23 +0000373 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000374 "Can only allocate virtual registers!");
375 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000377 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000378 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000379
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000380 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000381 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000382 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000383 DOUT << "\tinterval " << *i->first << " expired\n");
384 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000385
Evan Cheng81a03822007-11-17 00:40:40 +0000386 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000387 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000388 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000389 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000390 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000391 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000392 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000393 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000394 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000395 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000396 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000397 if (!Reg)
398 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000399 // Ignore splited live intervals.
400 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
401 continue;
Evan Cheng3f4b80e2007-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 Cheng3f4b80e2007-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 Chenga5bfc972007-10-17 06:53:44 +0000409 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000410 }
411 }
412 }
413
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000414 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000415}
416
Chris Lattnercbb56252004-11-18 02:42:27 +0000417/// processActiveIntervals - expire old intervals and move non-overlapping ones
418/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000419void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000420{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000421 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000422
Chris Lattnercbb56252004-11-18 02:42:27 +0000423 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;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000427
Chris Lattnercbb56252004-11-18 02:42:27 +0000428 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
429
430 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000431 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000432 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000433 "Can only allocate virtual registers!");
434 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000435 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000436
437 // Pop off the end of the list.
438 active_[i] = active_.back();
439 active_.pop_back();
440 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000441
Chris Lattnercbb56252004-11-18 02:42:27 +0000442 } else if (IntervalPos->start > CurPoint) {
443 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000444 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000445 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000446 "Can only allocate virtual registers!");
447 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000449 // 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;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 }
460 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000461}
462
Chris Lattnercbb56252004-11-18 02:42:27 +0000463/// processInactiveIntervals - expire old intervals and move overlapping
464/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000465void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000466{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000467 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000468
Chris Lattnercbb56252004-11-18 02:42:27 +0000469 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;
Chris Lattner23b71c12004-11-18 01:29:39 +0000473
Chris Lattnercbb56252004-11-18 02:42:27 +0000474 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000475
Chris Lattnercbb56252004-11-18 02:42:27 +0000476 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000477 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000478
Chris Lattnercbb56252004-11-18 02:42:27 +0000479 // 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
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000485 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000486 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000487 "Can only allocate virtual registers!");
488 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000489 prt_->addRegUse(reg);
490 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000491 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;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000500 }
501 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000502}
503
Chris Lattnercbb56252004-11-18 02:42:27 +0000504/// updateSpillWeights - updates the spill weights of the specifed physical
505/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000506static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000507 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000508 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000509 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000510 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000511 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000512}
513
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000514static
515RALinScan::IntervalPtrs::iterator
516FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
517 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
518 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000519 if (I->first == LI) return I;
520 return IP.end();
521}
522
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000523static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000524 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000525 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000526 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}
Chris Lattnercbb56252004-11-18 02:42:27 +0000532
Evan Cheng3f32d652008-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 Cheng9c3c2212008-06-06 07:54:39 +0000536 LiveIntervals *li_, float &Weight,
537 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-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 Cheng9c3c2212008-06-06 07:54:39 +0000542 SI.weight += Weight;
543
Evan Cheng3f32d652008-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 Cheng3f32d652008-06-04 09:18:41 +0000553}
554
Evan Cheng3e172252008-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
Chris Lattnercbb56252004-11-18 02:42:27 +0000656/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
657/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000658void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000659{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000660 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000661
Evan Chengf30a49d2008-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 Chengf30a49d2008-04-03 16:40:27 +0000671 return;
672 }
673
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000674 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000675
Chris Lattnera6c17502005-08-22 20:20:42 +0000676 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000677 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000678 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-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 Chengf2b24ca2008-04-11 17:55:47 +0000690 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000691 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000692 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-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
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000702 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000703 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000704 for (IntervalPtrs::const_iterator i = inactive_.begin(),
705 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000706 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000707 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000708 "Can only allocate virtual registers!");
Chris Lattner84bc5422007-12-31 04:13:23 +0000709 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +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));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000717 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000718 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000719
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 Cheng676dd7c2008-03-11 07:19:34 +0000726 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000727 if (physReg) {
728 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000729 // conflict with it. Check to see if we conflict with it or any of its
730 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000731 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000732 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000733 RegAliases.insert(*AS);
734
Chris Lattnera411cbc2005-08-22 20:59:30 +0000735 bool ConflictsWithFixed = false;
736 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000737 IntervalPtr &IP = fixed_[i];
738 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000739 // Okay, this reg is on the fixed list. Check to see if we actually
740 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000741 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;
Chris Lattnere836ad62005-08-30 21:03:36 +0000747 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000748 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000749 break;
750 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000751 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000752 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000753 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000754
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) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000759 // For every interval in fixed we overlap with, mark the register as not
760 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000761 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
762 IntervalPtr &IP = fixed_[i];
763 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000764
765 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
766 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
767 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000768 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 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000779
Chris Lattnera411cbc2005-08-22 20:59:30 +0000780 // 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
Chris Lattnera6c17502005-08-22 20:20:42 +0000786 // Restore the physical register tracker, removing information about the
787 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000788 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000789
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000790 // 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 Wendlinge6d088a2008-02-26 21:47:57 +0000794 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000795 vrm_->assignVirt2Phys(cur->reg, physReg);
796 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000797 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000798 handled_.push_back(cur);
799 return;
800 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000801 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000802
Chris Lattnera6c17502005-08-22 20:20:42 +0000803 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000804 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000805 for (std::vector<std::pair<unsigned, float> >::iterator
806 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000807 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +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 Gohman6f0d0242008-02-10 18:45:23 +0000813 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000814 "Can only allocate virtual registers!");
815 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000816 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000817 }
818
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000819 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000820
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000821 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000822 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-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;
Evan Cheng20b0abc2007-04-17 20:32:26 +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 Cheng3e172252008-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));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000835 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000836
837 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000838 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07: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 Cheng3e172252008-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 Cheng676dd7c2008-03-11 07:19:34 +0000846 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000847 }
Evan Cheng3e172252008-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 Andersona1566f22008-07-22 22:46:49 +0000856 if (cur->weight == HUGE_VALF ||
Owen Anderson496bac52008-07-23 19:47:27 +0000857 li_->getApproximateInstructionCount(*cur) == 0)
Evan Cheng3e172252008-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");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000874
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000875 // 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.
Jim Laskey7902c752006-11-07 12:25:45 +0000878 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000879 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000880 float SSWeight;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000881 std::vector<LiveInterval*> added =
Evan Cheng9c3c2212008-06-06 07:54:39 +0000882 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_, SSWeight);
883 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000884 if (added.empty())
885 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000886
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000887 // Merge added with unhandled. Note that we know that
888 // addIntervalsForSpills returns intervals sorted by their starting
889 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000890 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000891 unhandled_.push(added[i]);
892 return;
893 }
894
Chris Lattner19828d42004-11-18 03:49:30 +0000895 ++NumBacktracks;
896
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000897 // 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 Gohman6f0d0242008-02-10 18:45:23 +0000902 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000903 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000904
Evan Cheng3e172252008-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;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000909
Evan Cheng3e172252008-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
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000917 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000918 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000919
Evan Cheng3e172252008-06-20 21:45:16 +0000920 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +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 Cheng3e172252008-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);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000937 }
938
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000939 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000940
941 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000942 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000943 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000944 while (!handled_.empty()) {
945 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000946 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000947 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000948 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000949 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000950 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000951
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.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000954 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000955 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000956 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000957 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000958 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000959 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000960 prt_->delRegUse(vrm_->getPhys(i->reg));
961 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000962 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000963 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000964 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000965 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000966 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000967 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000968 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000969 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000970 "Can only allocate virtual registers!");
971 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000972 unhandled_.push(i);
973 }
Evan Cheng9aeaf752007-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;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000979 }
980
Chris Lattner19828d42004-11-18 03:49:30 +0000981 // 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
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000987 // 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)
Chris Lattnercbb56252004-11-18 02:42:27 +0000990 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())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000994 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000995 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +0000996 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000997 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000998 }
999 }
1000
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001001 // merge added with unhandled
1002 for (unsigned i = 0, e = added.size(); i != e; ++i)
1003 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001004}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001005
Chris Lattnercbb56252004-11-18 02:42:27 +00001006/// getFreePhysReg - return a free physical register for this virtual register
1007/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001008unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001009 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001010 unsigned MaxInactiveCount = 0;
1011
Chris Lattner84bc5422007-12-31 04:13:23 +00001012 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001013 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1014
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001015 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1016 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001017 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001018 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001019 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001020
1021 // If this is not in a related reg class to the register we're allocating,
1022 // don't check it.
Chris Lattner84bc5422007-12-31 04:13:23 +00001023 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001024 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1025 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001026 if (inactiveCounts.size() <= reg)
1027 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001028 ++inactiveCounts[reg];
1029 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1030 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001031 }
1032
Chris Lattnerf8355d92005-08-22 16:55:22 +00001033 unsigned FreeReg = 0;
1034 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001035
1036 // If copy coalescer has assigned a "preferred" register, check if it's
1037 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001038 if (cur->preference) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001039 if (prt_->isRegAvail(cur->preference)) {
1040 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001041 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001042 return cur->preference;
1043 } else
1044 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001045 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001046 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001047
Chris Lattnerf8355d92005-08-22 16:55:22 +00001048 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001049 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1050 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001051 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001052 for (; I != E; ++I)
1053 if (prt_->isRegAvail(*I)) {
1054 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001055 if (FreeReg < inactiveCounts.size())
1056 FreeRegInactiveCount = inactiveCounts[FreeReg];
1057 else
1058 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001059 break;
1060 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001061
Chris Lattnerf8355d92005-08-22 16:55:22 +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 Lattnerfe424622008-02-26 22:08:41 +00001072 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1073 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001074 FreeReg = Reg;
1075 FreeRegInactiveCount = inactiveCounts[Reg];
1076 if (FreeRegInactiveCount == MaxInactiveCount)
1077 break; // We found the one with the max inactive count.
1078 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001079 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001080
1081 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001082}
1083
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001084FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001085 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001086}