blob: 7291e12bbea438135a0ca0b7e0a9e7440f68c7ad [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;
Dan Gohmanae73dc12008-09-04 17:05:41 +000058 RALinScan() : MachineFunctionPass(&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_;
Evan Chengc92da382007-11-03 07:20:12 +000074 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000075 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000076 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000077 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000078
79 /// handled_ - Intervals are added to the handled_ set in the order of their
80 /// start value. This is uses for backtracking.
81 std::vector<LiveInterval*> handled_;
82
83 /// fixed_ - Intervals that correspond to machine registers.
84 ///
85 IntervalPtrs fixed_;
86
87 /// active_ - Intervals that are currently being processed, and which have a
88 /// live range active for the current point.
89 IntervalPtrs active_;
90
91 /// inactive_ - Intervals that are currently being processed, but which have
92 /// a hold at the current point.
93 IntervalPtrs inactive_;
94
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000095 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000096 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000097 greater_ptr<LiveInterval> > IntervalHeap;
98 IntervalHeap unhandled_;
99 std::auto_ptr<PhysRegTracker> prt_;
100 std::auto_ptr<VirtRegMap> vrm_;
101 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000102
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000103 public:
104 virtual const char* getPassName() const {
105 return "Linear Scan Register Allocator";
106 }
107
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000109 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +0000110 // Make sure PassManager knows which analyses to make available
111 // to coalescing and which analyses coalescing invalidates.
112 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000113 AU.addRequired<LiveStacks>();
114 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000115 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000116 AU.addPreserved<MachineLoopInfo>();
117 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000118 MachineFunctionPass::getAnalysisUsage(AU);
119 }
120
121 /// runOnMachineFunction - register allocate the whole function
122 bool runOnMachineFunction(MachineFunction&);
123
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000124 private:
125 /// linearScan - the linear scan algorithm
126 void linearScan();
127
Chris Lattnercbb56252004-11-18 02:42:27 +0000128 /// initIntervalSets - initialize the interval sets.
129 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130 void initIntervalSets();
131
Chris Lattnercbb56252004-11-18 02:42:27 +0000132 /// processActiveIntervals - expire old intervals and move non-overlapping
133 /// ones to the inactive list.
134 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000135
Chris Lattnercbb56252004-11-18 02:42:27 +0000136 /// processInactiveIntervals - expire old intervals and move overlapping
137 /// ones to the active list.
138 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000139
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000140 /// assignRegOrStackSlotAtInterval - assign a register if one
141 /// is available, or spill.
142 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
143
Evan Cheng3e172252008-06-20 21:45:16 +0000144 /// findIntervalsToSpill - Determine the intervals to spill for the
145 /// specified interval. It's passed the physical registers whose spill
146 /// weight is the lowest among all the registers whose live intervals
147 /// conflict with the interval.
148 void findIntervalsToSpill(LiveInterval *cur,
149 std::vector<std::pair<unsigned,float> > &Candidates,
150 unsigned NumCands,
151 SmallVector<LiveInterval*, 8> &SpillIntervals);
152
Evan Chengc92da382007-11-03 07:20:12 +0000153 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
154 /// try allocate the definition the same register as the source register
155 /// if the register is not defined during live time of the interval. This
156 /// eliminate a copy. This is used to coalesce copies which were not
157 /// coalesced away before allocation either due to dest and src being in
158 /// different register classes or because the coalescer was overly
159 /// conservative.
160 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
161
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000162 ///
163 /// register handling helpers
164 ///
165
Chris Lattnercbb56252004-11-18 02:42:27 +0000166 /// getFreePhysReg - return a free physical register for this virtual
167 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000168 unsigned getFreePhysReg(LiveInterval* cur);
169
170 /// assignVirt2StackSlot - assigns this virtual register to a
171 /// stack slot. returns the stack slot
172 int assignVirt2StackSlot(unsigned virtReg);
173
Chris Lattnerb9805782005-08-23 22:27:31 +0000174 void ComputeRelatedRegClasses();
175
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000176 template <typename ItTy>
177 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000178 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000179 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000180 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000181 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000182 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000183 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000184 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000185 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000186 }
187 }
188 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000189 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000190}
191
Evan Cheng3f32d652008-06-04 09:18:41 +0000192static RegisterPass<RALinScan>
193X("linearscan-regalloc", "Linear Scan Register Allocator");
194
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000195void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000196 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000197
198 // First pass, add all reg classes to the union, and determine at least one
199 // reg class that each register is in.
200 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000201 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
202 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000203 RelatedRegClasses.insert(*RCI);
204 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
205 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000206 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000207
208 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
209 if (PRC) {
210 // Already processed this register. Just make sure we know that
211 // multiple register classes share a register.
212 RelatedRegClasses.unionSets(PRC, *RCI);
213 } else {
214 PRC = *RCI;
215 }
216 }
217 }
218
219 // Second pass, now that we know conservatively what register classes each reg
220 // belongs to, add info about aliases. We don't need to do this for targets
221 // without register aliases.
222 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000223 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000224 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
225 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000226 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000227 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
228}
229
Evan Chengc92da382007-11-03 07:20:12 +0000230/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
231/// try allocate the definition the same register as the source register
232/// if the register is not defined during live time of the interval. This
233/// eliminate a copy. This is used to coalesce copies which were not
234/// coalesced away before allocation either due to dest and src being in
235/// different register classes or because the coalescer was overly
236/// conservative.
237unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000238 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000239 return Reg;
240
241 VNInfo *vni = cur.getValNumInfo(0);
242 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
243 return Reg;
244 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
245 unsigned SrcReg, DstReg;
246 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
247 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000248 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000249 if (!vrm_->isAssignedReg(SrcReg))
250 return Reg;
251 else
252 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000253 }
Evan Chengc92da382007-11-03 07:20:12 +0000254 if (Reg == SrcReg)
255 return Reg;
256
Evan Cheng841ee1a2008-09-18 22:38:47 +0000257 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000258 if (!RC->contains(SrcReg))
259 return Reg;
260
261 // Try to coalesce.
262 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000263 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000264 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000265 vrm_->clearVirt(cur.reg);
266 vrm_->assignVirt2Phys(cur.reg, SrcReg);
267 ++NumCoalesce;
268 return SrcReg;
269 }
270
271 return Reg;
272}
273
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000274bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000275 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000276 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000277 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000278 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000279 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000280 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000282 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000283 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000284
David Greene2c17c4d2007-09-06 16:18:45 +0000285 // We don't run the coalescer here because we have no reason to
286 // interact with it. If the coalescer requires interaction, it
287 // won't do anything. If it doesn't require interaction, we assume
288 // it was run as a separate pass.
289
Chris Lattnerb9805782005-08-23 22:27:31 +0000290 // If this is the first function compiled, compute the related reg classes.
291 if (RelatedRegClasses.empty())
292 ComputeRelatedRegClasses();
293
Dan Gohman6f0d0242008-02-10 18:45:23 +0000294 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000295 vrm_.reset(new VirtRegMap(*mf_));
296 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000297
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000298 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000299
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000301
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000302 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000304 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000305
Dan Gohman51cd9d62008-06-23 23:51:16 +0000306 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000307 fixed_.clear();
308 active_.clear();
309 inactive_.clear();
310 handled_.clear();
311
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000312 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000313}
314
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000315/// initIntervalSets - initialize the interval sets.
316///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000317void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000318{
319 assert(unhandled_.empty() && fixed_.empty() &&
320 active_.empty() && inactive_.empty() &&
321 "interval sets should be empty on initialization");
322
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000323 handled_.reserve(li_->getNumIntervals());
324
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000325 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000326 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000327 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000328 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000329 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000330 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000331 }
332}
333
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000334void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000335{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000337 DOUT << "********** LINEAR SCAN **********\n";
338 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000339
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000340 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000341
342 while (!unhandled_.empty()) {
343 // pick the interval with the earliest start point
344 LiveInterval* cur = unhandled_.top();
345 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000346 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000347 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348
Evan Chengf30a49d2008-04-03 16:40:27 +0000349 if (!cur->empty()) {
350 processActiveIntervals(cur->beginNumber());
351 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352
Evan Chengf30a49d2008-04-03 16:40:27 +0000353 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
354 "Can only allocate virtual registers!");
355 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000356
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000357 // Allocating a virtual register. try to find a free
358 // physical register or spill an interval (possibly this one) in order to
359 // assign it one.
360 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000362 DEBUG(printIntervals("active", active_.begin(), active_.end()));
363 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000365
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000367 while (!active_.empty()) {
368 IntervalPtr &IP = active_.back();
369 unsigned reg = IP.first->reg;
370 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000371 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000372 "Can only allocate virtual registers!");
373 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000375 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000377
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000378 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000379 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000380 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000381 DOUT << "\tinterval " << *i->first << " expired\n");
382 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000383
Evan Cheng81a03822007-11-17 00:40:40 +0000384 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000385 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000386 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000387 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000388 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000389 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000390 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000391 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000392 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000393 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000394 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000395 if (!Reg)
396 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000397 // Ignore splited live intervals.
398 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
399 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000400 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
401 I != E; ++I) {
402 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000403 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
404 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
405 if (LiveInMBBs[i] != EntryMBB)
406 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000407 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000408 }
409 }
410 }
411
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000412 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000413}
414
Chris Lattnercbb56252004-11-18 02:42:27 +0000415/// processActiveIntervals - expire old intervals and move non-overlapping ones
416/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000417void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000418{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000419 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000420
Chris Lattnercbb56252004-11-18 02:42:27 +0000421 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
422 LiveInterval *Interval = active_[i].first;
423 LiveInterval::iterator IntervalPos = active_[i].second;
424 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000425
Chris Lattnercbb56252004-11-18 02:42:27 +0000426 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
427
428 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000429 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000430 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000431 "Can only allocate virtual registers!");
432 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000433 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000434
435 // Pop off the end of the list.
436 active_[i] = active_.back();
437 active_.pop_back();
438 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000439
Chris Lattnercbb56252004-11-18 02:42:27 +0000440 } else if (IntervalPos->start > CurPoint) {
441 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000442 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000443 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000444 "Can only allocate virtual registers!");
445 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000447 // add to inactive.
448 inactive_.push_back(std::make_pair(Interval, IntervalPos));
449
450 // Pop off the end of the list.
451 active_[i] = active_.back();
452 active_.pop_back();
453 --i; --e;
454 } else {
455 // Otherwise, just update the iterator position.
456 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000457 }
458 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000459}
460
Chris Lattnercbb56252004-11-18 02:42:27 +0000461/// processInactiveIntervals - expire old intervals and move overlapping
462/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000463void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000464{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000465 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000466
Chris Lattnercbb56252004-11-18 02:42:27 +0000467 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
468 LiveInterval *Interval = inactive_[i].first;
469 LiveInterval::iterator IntervalPos = inactive_[i].second;
470 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000471
Chris Lattnercbb56252004-11-18 02:42:27 +0000472 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000473
Chris Lattnercbb56252004-11-18 02:42:27 +0000474 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000475 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000476
Chris Lattnercbb56252004-11-18 02:42:27 +0000477 // Pop off the end of the list.
478 inactive_[i] = inactive_.back();
479 inactive_.pop_back();
480 --i; --e;
481 } else if (IntervalPos->start <= CurPoint) {
482 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000483 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000484 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000485 "Can only allocate virtual registers!");
486 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000487 prt_->addRegUse(reg);
488 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000489 active_.push_back(std::make_pair(Interval, IntervalPos));
490
491 // Pop off the end of the list.
492 inactive_[i] = inactive_.back();
493 inactive_.pop_back();
494 --i; --e;
495 } else {
496 // Otherwise, just update the iterator position.
497 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 }
499 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000500}
501
Chris Lattnercbb56252004-11-18 02:42:27 +0000502/// updateSpillWeights - updates the spill weights of the specifed physical
503/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000504static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000505 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000506 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000507 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000508 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000509 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000510}
511
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000512static
513RALinScan::IntervalPtrs::iterator
514FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
515 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
516 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000517 if (I->first == LI) return I;
518 return IP.end();
519}
520
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000521static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000522 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000523 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000524 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
525 IP.second, Point);
526 if (I != IP.first->begin()) --I;
527 IP.second = I;
528 }
529}
Chris Lattnercbb56252004-11-18 02:42:27 +0000530
Evan Cheng3f32d652008-06-04 09:18:41 +0000531/// addStackInterval - Create a LiveInterval for stack if the specified live
532/// interval has been spilled.
533static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000534 LiveIntervals *li_, float &Weight,
535 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000536 int SS = vrm_.getStackSlot(cur->reg);
537 if (SS == VirtRegMap::NO_STACK_SLOT)
538 return;
539 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000540 SI.weight += Weight;
541
Evan Cheng3f32d652008-06-04 09:18:41 +0000542 VNInfo *VNI;
543 if (SI.getNumValNums())
544 VNI = SI.getValNumInfo(0);
545 else
546 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
547
548 LiveInterval &RI = li_->getInterval(cur->reg);
549 // FIXME: This may be overly conservative.
550 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000551}
552
Evan Cheng3e172252008-06-20 21:45:16 +0000553/// getConflictWeight - Return the number of conflicts between cur
554/// live interval and defs and uses of Reg weighted by loop depthes.
555static float getConflictWeight(LiveInterval *cur, unsigned Reg,
556 LiveIntervals *li_,
557 MachineRegisterInfo *mri_,
558 const MachineLoopInfo *loopInfo) {
559 float Conflicts = 0;
560 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
561 E = mri_->reg_end(); I != E; ++I) {
562 MachineInstr *MI = &*I;
563 if (cur->liveAt(li_->getInstructionIndex(MI))) {
564 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
565 Conflicts += powf(10.0f, (float)loopDepth);
566 }
567 }
568 return Conflicts;
569}
570
571/// findIntervalsToSpill - Determine the intervals to spill for the
572/// specified interval. It's passed the physical registers whose spill
573/// weight is the lowest among all the registers whose live intervals
574/// conflict with the interval.
575void RALinScan::findIntervalsToSpill(LiveInterval *cur,
576 std::vector<std::pair<unsigned,float> > &Candidates,
577 unsigned NumCands,
578 SmallVector<LiveInterval*, 8> &SpillIntervals) {
579 // We have figured out the *best* register to spill. But there are other
580 // registers that are pretty good as well (spill weight within 3%). Spill
581 // the one that has fewest defs and uses that conflict with cur.
582 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
583 SmallVector<LiveInterval*, 8> SLIs[3];
584
585 DOUT << "\tConsidering " << NumCands << " candidates: ";
586 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
587 DOUT << tri_->getName(Candidates[i].first) << " ";
588 DOUT << "\n";);
589
590 // Calculate the number of conflicts of each candidate.
591 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
592 unsigned Reg = i->first->reg;
593 unsigned PhysReg = vrm_->getPhys(Reg);
594 if (!cur->overlapsFrom(*i->first, i->second))
595 continue;
596 for (unsigned j = 0; j < NumCands; ++j) {
597 unsigned Candidate = Candidates[j].first;
598 if (tri_->regsOverlap(PhysReg, Candidate)) {
599 if (NumCands > 1)
600 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
601 SLIs[j].push_back(i->first);
602 }
603 }
604 }
605
606 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
607 unsigned Reg = i->first->reg;
608 unsigned PhysReg = vrm_->getPhys(Reg);
609 if (!cur->overlapsFrom(*i->first, i->second-1))
610 continue;
611 for (unsigned j = 0; j < NumCands; ++j) {
612 unsigned Candidate = Candidates[j].first;
613 if (tri_->regsOverlap(PhysReg, Candidate)) {
614 if (NumCands > 1)
615 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
616 SLIs[j].push_back(i->first);
617 }
618 }
619 }
620
621 // Which is the best candidate?
622 unsigned BestCandidate = 0;
623 float MinConflicts = Conflicts[0];
624 for (unsigned i = 1; i != NumCands; ++i) {
625 if (Conflicts[i] < MinConflicts) {
626 BestCandidate = i;
627 MinConflicts = Conflicts[i];
628 }
629 }
630
631 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
632 std::back_inserter(SpillIntervals));
633}
634
635namespace {
636 struct WeightCompare {
637 typedef std::pair<unsigned, float> RegWeightPair;
638 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
639 return LHS.second < RHS.second;
640 }
641 };
642}
643
644static bool weightsAreClose(float w1, float w2) {
645 if (!NewHeuristic)
646 return false;
647
648 float diff = w1 - w2;
649 if (diff <= 0.02f) // Within 0.02f
650 return true;
651 return (diff / w2) <= 0.05f; // Within 5%.
652}
653
Chris Lattnercbb56252004-11-18 02:42:27 +0000654/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
655/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000656void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000657{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000658 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000659
Evan Chengf30a49d2008-04-03 16:40:27 +0000660 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000661 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000662 if (cur->empty()) {
663 unsigned physReg = cur->preference;
664 if (!physReg)
665 physReg = *RC->allocation_order_begin(*mf_);
666 DOUT << tri_->getName(physReg) << '\n';
667 // Note the register is not really in use.
668 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000669 return;
670 }
671
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000672 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000673
Chris Lattnera6c17502005-08-22 20:20:42 +0000674 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000675 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000676 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000677
678 // If this live interval is defined by a move instruction and its source is
679 // assigned a physical register that is compatible with the target register
680 // class, then we should try to assign it the same register.
681 // This can happen when the move is from a larger register class to a smaller
682 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
683 if (!cur->preference && cur->containsOneValue()) {
684 VNInfo *vni = cur->getValNumInfo(0);
685 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
686 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
687 unsigned SrcReg, DstReg;
Evan Chengf2b24ca2008-04-11 17:55:47 +0000688 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000689 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000690 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000691 Reg = SrcReg;
692 else if (vrm_->isAssignedReg(SrcReg))
693 Reg = vrm_->getPhys(SrcReg);
694 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
695 cur->preference = Reg;
696 }
697 }
698 }
699
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000700 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000701 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000702 for (IntervalPtrs::const_iterator i = inactive_.begin(),
703 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000704 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000705 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000706 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000707 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000708 // If this is not in a related reg class to the register we're allocating,
709 // don't check it.
710 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
711 cur->overlapsFrom(*i->first, i->second-1)) {
712 Reg = vrm_->getPhys(Reg);
713 prt_->addRegUse(Reg);
714 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000715 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000716 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000717
718 // Speculatively check to see if we can get a register right now. If not,
719 // we know we won't be able to by adding more constraints. If so, we can
720 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
721 // is very bad (it contains all callee clobbered registers for any functions
722 // with a call), so we want to avoid doing that if possible.
723 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000724 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000725 if (physReg) {
726 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000727 // conflict with it. Check to see if we conflict with it or any of its
728 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000729 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000730 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000731 RegAliases.insert(*AS);
732
Chris Lattnera411cbc2005-08-22 20:59:30 +0000733 bool ConflictsWithFixed = false;
734 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000735 IntervalPtr &IP = fixed_[i];
736 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000737 // Okay, this reg is on the fixed list. Check to see if we actually
738 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000739 LiveInterval *I = IP.first;
740 if (I->endNumber() > StartPosition) {
741 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
742 IP.second = II;
743 if (II != I->begin() && II->start > StartPosition)
744 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000745 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000746 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000747 break;
748 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000749 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000750 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000751 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000752
753 // Okay, the register picked by our speculative getFreePhysReg call turned
754 // out to be in use. Actually add all of the conflicting fixed registers to
755 // prt so we can do an accurate query.
756 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000757 // For every interval in fixed we overlap with, mark the register as not
758 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000759 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
760 IntervalPtr &IP = fixed_[i];
761 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000762
763 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
764 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
765 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000766 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
767 IP.second = II;
768 if (II != I->begin() && II->start > StartPosition)
769 --II;
770 if (cur->overlapsFrom(*I, II)) {
771 unsigned reg = I->reg;
772 prt_->addRegUse(reg);
773 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
774 }
775 }
776 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000777
Chris Lattnera411cbc2005-08-22 20:59:30 +0000778 // Using the newly updated prt_ object, which includes conflicts in the
779 // future, see if there are any registers available.
780 physReg = getFreePhysReg(cur);
781 }
782 }
783
Chris Lattnera6c17502005-08-22 20:20:42 +0000784 // Restore the physical register tracker, removing information about the
785 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000786 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000787
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000788 // if we find a free register, we are done: assign this virtual to
789 // the free physical register and add this interval to the active
790 // list.
791 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000792 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000793 vrm_->assignVirt2Phys(cur->reg, physReg);
794 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000795 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000796 handled_.push_back(cur);
797 return;
798 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000799 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000800
Chris Lattnera6c17502005-08-22 20:20:42 +0000801 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000802 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000803 for (std::vector<std::pair<unsigned, float> >::iterator
804 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000805 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000806
807 // for each interval in active, update spill weights.
808 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
809 i != e; ++i) {
810 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000811 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000812 "Can only allocate virtual registers!");
813 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000814 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000815 }
816
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000817 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000818
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000819 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000820 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000821 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
822
823 bool Found = false;
824 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000825 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
826 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
827 e = RC->allocation_order_end(*mf_); i != e; ++i) {
828 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000829 float regWeight = SpillWeights[reg];
830 if (minWeight > regWeight)
831 Found = true;
832 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000833 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000834
835 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000836 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000837 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
838 e = RC->allocation_order_end(*mf_); i != e; ++i) {
839 unsigned reg = *i;
840 // No need to worry about if the alias register size < regsize of RC.
841 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000842 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
843 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000844 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000845 }
Evan Cheng3e172252008-06-20 21:45:16 +0000846
847 // Sort all potential spill candidates by weight.
848 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
849 minReg = RegsWeights[0].first;
850 minWeight = RegsWeights[0].second;
851 if (minWeight == HUGE_VALF) {
852 // All registers must have inf weight. Just grab one!
853 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000854 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000855 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000856 // Spill a physical register around defs and uses.
857 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000858 assignRegOrStackSlotAtInterval(cur);
859 return;
860 }
Evan Cheng3e172252008-06-20 21:45:16 +0000861 }
862
863 // Find up to 3 registers to consider as spill candidates.
864 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
865 while (LastCandidate > 1) {
866 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
867 break;
868 --LastCandidate;
869 }
870
871 DOUT << "\t\tregister(s) with min weight(s): ";
872 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
873 DOUT << tri_->getName(RegsWeights[i].first)
874 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000875
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000876 // if the current has the minimum weight, we need to spill it and
877 // add any added intervals back to unhandled, and restart
878 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000879 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000880 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000881 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000882 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000883 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000884 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000885 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000886 if (added.empty())
887 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000888
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000889 // Merge added with unhandled. Note that we know that
890 // addIntervalsForSpills returns intervals sorted by their starting
891 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000892 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000893 unhandled_.push(added[i]);
894 return;
895 }
896
Chris Lattner19828d42004-11-18 03:49:30 +0000897 ++NumBacktracks;
898
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000899 // push the current interval back to unhandled since we are going
900 // to re-run at least this iteration. Since we didn't modify it it
901 // should go back right in the front of the list
902 unhandled_.push(cur);
903
Dan Gohman6f0d0242008-02-10 18:45:23 +0000904 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000905 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000906
Evan Cheng3e172252008-06-20 21:45:16 +0000907 // We spill all intervals aliasing the register with
908 // minimum weight, rollback to the interval with the earliest
909 // start point and let the linear scan algorithm run again
910 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000911
Evan Cheng3e172252008-06-20 21:45:16 +0000912 // Determine which intervals have to be spilled.
913 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
914
915 // Set of spilled vregs (used later to rollback properly)
916 SmallSet<unsigned, 8> spilled;
917
918 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000919 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000920 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000921
Evan Cheng3e172252008-06-20 21:45:16 +0000922 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000923 // want to clear (and its aliases). We only spill those that overlap with the
924 // current interval as the rest do not affect its allocation. we also keep
925 // track of the earliest start of all spilled live intervals since this will
926 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000927 std::vector<LiveInterval*> added;
928 while (!spillIs.empty()) {
929 LiveInterval *sli = spillIs.back();
930 spillIs.pop_back();
931 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
932 earliestStart = std::min(earliestStart, sli->beginNumber());
933 float SSWeight;
934 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000935 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000936 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
937 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
938 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000939 }
940
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000941 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000942
943 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000944 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000945 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000946 while (!handled_.empty()) {
947 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000948 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000949 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000950 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000951 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000952 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000953
954 // When undoing a live interval allocation we must know if it is active or
955 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000956 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000957 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000958 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000959 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000960 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000961 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000962 prt_->delRegUse(vrm_->getPhys(i->reg));
963 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000964 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000965 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000966 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000967 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000968 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000969 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000970 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000971 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000972 "Can only allocate virtual registers!");
973 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000974 unhandled_.push(i);
975 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000976
977 // It interval has a preference, it must be defined by a copy. Clear the
978 // preference now since the source interval allocation may have been undone
979 // as well.
980 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000981 }
982
Chris Lattner19828d42004-11-18 03:49:30 +0000983 // Rewind the iterators in the active, inactive, and fixed lists back to the
984 // point we reverted to.
985 RevertVectorIteratorsTo(active_, earliestStart);
986 RevertVectorIteratorsTo(inactive_, earliestStart);
987 RevertVectorIteratorsTo(fixed_, earliestStart);
988
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000989 // scan the rest and undo each interval that expired after t and
990 // insert it in active (the next iteration of the algorithm will
991 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000992 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
993 LiveInterval *HI = handled_[i];
994 if (!HI->expiredAt(earliestStart) &&
995 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000996 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000997 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +0000998 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000999 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001000 }
1001 }
1002
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001003 // merge added with unhandled
1004 for (unsigned i = 0, e = added.size(); i != e; ++i)
1005 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001006}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001007
Chris Lattnercbb56252004-11-18 02:42:27 +00001008/// getFreePhysReg - return a free physical register for this virtual register
1009/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001010unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001011 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001012 unsigned MaxInactiveCount = 0;
1013
Evan Cheng841ee1a2008-09-18 22:38:47 +00001014 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001015 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1016
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001017 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1018 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001019 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001020 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001021 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001022
1023 // If this is not in a related reg class to the register we're allocating,
1024 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001025 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001026 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1027 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001028 if (inactiveCounts.size() <= reg)
1029 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001030 ++inactiveCounts[reg];
1031 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1032 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001033 }
1034
Chris Lattnerf8355d92005-08-22 16:55:22 +00001035 unsigned FreeReg = 0;
1036 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001037
1038 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001039 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001040 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001041 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001042 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001043 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001044 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001045 return cur->preference;
1046 } else
1047 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001048 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001049 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001050
Chris Lattnerf8355d92005-08-22 16:55:22 +00001051 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001052 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1053 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001054 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001055 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001056 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001057 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001058 if (FreeReg < inactiveCounts.size())
1059 FreeRegInactiveCount = inactiveCounts[FreeReg];
1060 else
1061 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001062 break;
1063 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001064
Chris Lattnerf8355d92005-08-22 16:55:22 +00001065 // If there are no free regs, or if this reg has the max inactive count,
1066 // return this register.
1067 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1068
1069 // Continue scanning the registers, looking for the one with the highest
1070 // inactive count. Alkis found that this reduced register pressure very
1071 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1072 // reevaluated now.
1073 for (; I != E; ++I) {
1074 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001075 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001076 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001077 FreeReg = Reg;
1078 FreeRegInactiveCount = inactiveCounts[Reg];
1079 if (FreeRegInactiveCount == MaxInactiveCount)
1080 break; // We found the one with the max inactive count.
1081 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001082 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001083
1084 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001085}
1086
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001087FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001088 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001089}