blob: a9444619fa5d239120a79ad663911d361e09af15 [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"
Owen Anderson95dad832008-10-07 20:22:28 +000029#include "llvm/Target/TargetOptions.h"
Evan Chengc92da382007-11-03 07:20:12 +000030#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000031#include "llvm/ADT/EquivalenceClasses.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000032#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000035#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000036#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000037#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000038#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000039#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000040#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000041#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000042using namespace llvm;
43
Chris Lattnercd3245a2006-12-19 22:41:21 +000044STATISTIC(NumIters , "Number of iterations performed");
45STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000046STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000047
Evan Cheng3e172252008-06-20 21:45:16 +000048static cl::opt<bool>
49NewHeuristic("new-spilling-heuristic",
50 cl::desc("Use new spilling heuristic"),
51 cl::init(false), cl::Hidden);
52
Evan Chengf5cd4f02008-10-23 20:43:13 +000053static cl::opt<bool>
54PreSplitIntervals("pre-alloc-split",
55 cl::desc("Pre-register allocation live interval splitting"),
56 cl::init(false), cl::Hidden);
57
Chris Lattnercd3245a2006-12-19 22:41:21 +000058static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000059linearscanRegAlloc("linearscan", "linear scan register allocator",
Chris Lattnercd3245a2006-12-19 22:41:21 +000060 createLinearScanRegisterAllocator);
61
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000062namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000063 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000064 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000065 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000066
Chris Lattnercbb56252004-11-18 02:42:27 +000067 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000068 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000069 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000070 /// RelatedRegClasses - This structure is built the first time a function is
71 /// compiled, and keeps track of which register classes have registers that
72 /// belong to multiple classes or have aliases that are in other classes.
73 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000074 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000075
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000077 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000078 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000079 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000080 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000081 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000082 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000083 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000084 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000085
86 /// handled_ - Intervals are added to the handled_ set in the order of their
87 /// start value. This is uses for backtracking.
88 std::vector<LiveInterval*> handled_;
89
90 /// fixed_ - Intervals that correspond to machine registers.
91 ///
92 IntervalPtrs fixed_;
93
94 /// active_ - Intervals that are currently being processed, and which have a
95 /// live range active for the current point.
96 IntervalPtrs active_;
97
98 /// inactive_ - Intervals that are currently being processed, but which have
99 /// a hold at the current point.
100 IntervalPtrs inactive_;
101
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000102 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000103 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 greater_ptr<LiveInterval> > IntervalHeap;
105 IntervalHeap unhandled_;
106 std::auto_ptr<PhysRegTracker> prt_;
107 std::auto_ptr<VirtRegMap> vrm_;
108 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000109
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000110 public:
111 virtual const char* getPassName() const {
112 return "Linear Scan Register Allocator";
113 }
114
115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000117 if (StrongPHIElim)
118 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000119 // Make sure PassManager knows which analyses to make available
120 // to coalescing and which analyses coalescing invalidates.
121 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000122 if (PreSplitIntervals)
123 AU.addRequiredID(PreAllocSplittingID);
Evan Cheng3f32d652008-06-04 09:18:41 +0000124 AU.addRequired<LiveStacks>();
125 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000126 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000127 AU.addPreserved<MachineLoopInfo>();
128 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000129 MachineFunctionPass::getAnalysisUsage(AU);
130 }
131
132 /// runOnMachineFunction - register allocate the whole function
133 bool runOnMachineFunction(MachineFunction&);
134
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000135 private:
136 /// linearScan - the linear scan algorithm
137 void linearScan();
138
Chris Lattnercbb56252004-11-18 02:42:27 +0000139 /// initIntervalSets - initialize the interval sets.
140 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000141 void initIntervalSets();
142
Chris Lattnercbb56252004-11-18 02:42:27 +0000143 /// processActiveIntervals - expire old intervals and move non-overlapping
144 /// ones to the inactive list.
145 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000146
Chris Lattnercbb56252004-11-18 02:42:27 +0000147 /// processInactiveIntervals - expire old intervals and move overlapping
148 /// ones to the active list.
149 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000151 /// assignRegOrStackSlotAtInterval - assign a register if one
152 /// is available, or spill.
153 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
154
Evan Cheng3e172252008-06-20 21:45:16 +0000155 /// findIntervalsToSpill - Determine the intervals to spill for the
156 /// specified interval. It's passed the physical registers whose spill
157 /// weight is the lowest among all the registers whose live intervals
158 /// conflict with the interval.
159 void findIntervalsToSpill(LiveInterval *cur,
160 std::vector<std::pair<unsigned,float> > &Candidates,
161 unsigned NumCands,
162 SmallVector<LiveInterval*, 8> &SpillIntervals);
163
Evan Chengc92da382007-11-03 07:20:12 +0000164 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
165 /// try allocate the definition the same register as the source register
166 /// if the register is not defined during live time of the interval. This
167 /// eliminate a copy. This is used to coalesce copies which were not
168 /// coalesced away before allocation either due to dest and src being in
169 /// different register classes or because the coalescer was overly
170 /// conservative.
171 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
172
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000173 ///
174 /// register handling helpers
175 ///
176
Chris Lattnercbb56252004-11-18 02:42:27 +0000177 /// getFreePhysReg - return a free physical register for this virtual
178 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000179 unsigned getFreePhysReg(LiveInterval* cur);
180
181 /// assignVirt2StackSlot - assigns this virtual register to a
182 /// stack slot. returns the stack slot
183 int assignVirt2StackSlot(unsigned virtReg);
184
Chris Lattnerb9805782005-08-23 22:27:31 +0000185 void ComputeRelatedRegClasses();
186
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000187 template <typename ItTy>
188 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000189 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000190 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000191 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000192 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000193 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000194 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000195 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000196 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000197 }
198 }
199 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000200 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000201}
202
Evan Cheng3f32d652008-06-04 09:18:41 +0000203static RegisterPass<RALinScan>
204X("linearscan-regalloc", "Linear Scan Register Allocator");
205
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000206void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000207 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000208
209 // First pass, add all reg classes to the union, and determine at least one
210 // reg class that each register is in.
211 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000212 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
213 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000214 RelatedRegClasses.insert(*RCI);
215 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
216 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000217 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000218
219 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
220 if (PRC) {
221 // Already processed this register. Just make sure we know that
222 // multiple register classes share a register.
223 RelatedRegClasses.unionSets(PRC, *RCI);
224 } else {
225 PRC = *RCI;
226 }
227 }
228 }
229
230 // Second pass, now that we know conservatively what register classes each reg
231 // belongs to, add info about aliases. We don't need to do this for targets
232 // without register aliases.
233 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000234 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000235 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
236 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000237 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000238 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
239}
240
Evan Chengc92da382007-11-03 07:20:12 +0000241/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
242/// try allocate the definition the same register as the source register
243/// if the register is not defined during live time of the interval. This
244/// eliminate a copy. This is used to coalesce copies which were not
245/// coalesced away before allocation either due to dest and src being in
246/// different register classes or because the coalescer was overly
247/// conservative.
248unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000249 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000250 return Reg;
251
Evan Chengd0deec22009-01-20 00:16:18 +0000252 VNInfo *vni = cur.begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000253 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
254 return Reg;
255 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000256 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
257 if (!CopyMI ||
258 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc92da382007-11-03 07:20:12 +0000259 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000260 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000261 if (!vrm_->isAssignedReg(SrcReg))
262 return Reg;
263 else
264 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000265 }
Evan Chengc92da382007-11-03 07:20:12 +0000266 if (Reg == SrcReg)
267 return Reg;
268
Evan Cheng841ee1a2008-09-18 22:38:47 +0000269 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000270 if (!RC->contains(SrcReg))
271 return Reg;
272
273 // Try to coalesce.
274 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000275 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000276 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000277 vrm_->clearVirt(cur.reg);
278 vrm_->assignVirt2Phys(cur.reg, SrcReg);
279 ++NumCoalesce;
280 return SrcReg;
281 }
282
283 return Reg;
284}
285
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000286bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000287 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000288 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000289 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000290 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000291 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000292 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000293 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000294 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000295 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000296
David Greene2c17c4d2007-09-06 16:18:45 +0000297 // We don't run the coalescer here because we have no reason to
298 // interact with it. If the coalescer requires interaction, it
299 // won't do anything. If it doesn't require interaction, we assume
300 // it was run as a separate pass.
301
Chris Lattnerb9805782005-08-23 22:27:31 +0000302 // If this is the first function compiled, compute the related reg classes.
303 if (RelatedRegClasses.empty())
304 ComputeRelatedRegClasses();
305
Dan Gohman6f0d0242008-02-10 18:45:23 +0000306 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000307 vrm_.reset(new VirtRegMap(*mf_));
308 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000309
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000310 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000311
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000312 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000313
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000314 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000316 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000317
Dan Gohman51cd9d62008-06-23 23:51:16 +0000318 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000319 fixed_.clear();
320 active_.clear();
321 inactive_.clear();
322 handled_.clear();
323
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000324 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000325}
326
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000327/// initIntervalSets - initialize the interval sets.
328///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000329void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000330{
331 assert(unhandled_.empty() && fixed_.empty() &&
332 active_.empty() && inactive_.empty() &&
333 "interval sets should be empty on initialization");
334
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000335 handled_.reserve(li_->getNumIntervals());
336
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000337 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000338 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000339 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000340 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000341 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000342 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000343 }
344}
345
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000346void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000347{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000349 DOUT << "********** LINEAR SCAN **********\n";
350 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000351
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000353
354 while (!unhandled_.empty()) {
355 // pick the interval with the earliest start point
356 LiveInterval* cur = unhandled_.top();
357 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000358 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000359 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000360
Evan Chengf30a49d2008-04-03 16:40:27 +0000361 if (!cur->empty()) {
362 processActiveIntervals(cur->beginNumber());
363 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364
Evan Chengf30a49d2008-04-03 16:40:27 +0000365 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
366 "Can only allocate virtual registers!");
367 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000368
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000369 // Allocating a virtual register. try to find a free
370 // physical register or spill an interval (possibly this one) in order to
371 // assign it one.
372 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000373
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000374 DEBUG(printIntervals("active", active_.begin(), active_.end()));
375 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
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 active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000379 while (!active_.empty()) {
380 IntervalPtr &IP = active_.back();
381 unsigned reg = IP.first->reg;
382 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000383 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000384 "Can only allocate virtual registers!");
385 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000386 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000387 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000388 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000389
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000391 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000392 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000393 DOUT << "\tinterval " << *i->first << " expired\n");
394 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000395
Evan Cheng81a03822007-11-17 00:40:40 +0000396 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000397 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000398 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000399 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000400 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000401 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000402 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000403 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000404 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000405 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000406 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000407 if (!Reg)
408 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000409 // Ignore splited live intervals.
410 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
411 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000412 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
413 I != E; ++I) {
414 const LiveRange &LR = *I;
Evan Chengd0e32c52008-10-29 05:06:14 +0000415 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000416 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
417 if (LiveInMBBs[i] != EntryMBB)
418 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000419 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000420 }
421 }
422 }
423
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000424 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000425}
426
Chris Lattnercbb56252004-11-18 02:42:27 +0000427/// processActiveIntervals - expire old intervals and move non-overlapping ones
428/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000429void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000430{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000431 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000432
Chris Lattnercbb56252004-11-18 02:42:27 +0000433 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
434 LiveInterval *Interval = active_[i].first;
435 LiveInterval::iterator IntervalPos = active_[i].second;
436 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000437
Chris Lattnercbb56252004-11-18 02:42:27 +0000438 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
439
440 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000441 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000442 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000443 "Can only allocate virtual registers!");
444 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000445 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000446
447 // Pop off the end of the list.
448 active_[i] = active_.back();
449 active_.pop_back();
450 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000451
Chris Lattnercbb56252004-11-18 02:42:27 +0000452 } else if (IntervalPos->start > CurPoint) {
453 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000454 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000455 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000456 "Can only allocate virtual registers!");
457 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000458 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000459 // add to inactive.
460 inactive_.push_back(std::make_pair(Interval, IntervalPos));
461
462 // Pop off the end of the list.
463 active_[i] = active_.back();
464 active_.pop_back();
465 --i; --e;
466 } else {
467 // Otherwise, just update the iterator position.
468 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000469 }
470 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000471}
472
Chris Lattnercbb56252004-11-18 02:42:27 +0000473/// processInactiveIntervals - expire old intervals and move overlapping
474/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000475void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000476{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000477 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000478
Chris Lattnercbb56252004-11-18 02:42:27 +0000479 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
480 LiveInterval *Interval = inactive_[i].first;
481 LiveInterval::iterator IntervalPos = inactive_[i].second;
482 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000483
Chris Lattnercbb56252004-11-18 02:42:27 +0000484 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000485
Chris Lattnercbb56252004-11-18 02:42:27 +0000486 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000487 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000488
Chris Lattnercbb56252004-11-18 02:42:27 +0000489 // Pop off the end of the list.
490 inactive_[i] = inactive_.back();
491 inactive_.pop_back();
492 --i; --e;
493 } else if (IntervalPos->start <= CurPoint) {
494 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000495 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000496 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000497 "Can only allocate virtual registers!");
498 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000499 prt_->addRegUse(reg);
500 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000501 active_.push_back(std::make_pair(Interval, IntervalPos));
502
503 // Pop off the end of the list.
504 inactive_[i] = inactive_.back();
505 inactive_.pop_back();
506 --i; --e;
507 } else {
508 // Otherwise, just update the iterator position.
509 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 }
511 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000512}
513
Chris Lattnercbb56252004-11-18 02:42:27 +0000514/// updateSpillWeights - updates the spill weights of the specifed physical
515/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000516static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000517 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000518 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000519 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000520 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000521 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000522}
523
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000524static
525RALinScan::IntervalPtrs::iterator
526FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
527 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
528 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000529 if (I->first == LI) return I;
530 return IP.end();
531}
532
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000533static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000534 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000535 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000536 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
537 IP.second, Point);
538 if (I != IP.first->begin()) --I;
539 IP.second = I;
540 }
541}
Chris Lattnercbb56252004-11-18 02:42:27 +0000542
Evan Cheng3f32d652008-06-04 09:18:41 +0000543/// addStackInterval - Create a LiveInterval for stack if the specified live
544/// interval has been spilled.
545static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000546 LiveIntervals *li_, float &Weight,
547 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000548 int SS = vrm_.getStackSlot(cur->reg);
549 if (SS == VirtRegMap::NO_STACK_SLOT)
550 return;
551 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000552 SI.weight += Weight;
553
Evan Cheng3f32d652008-06-04 09:18:41 +0000554 VNInfo *VNI;
Evan Cheng54898932008-10-29 08:39:34 +0000555 if (SI.hasAtLeastOneValue())
Evan Cheng3f32d652008-06-04 09:18:41 +0000556 VNI = SI.getValNumInfo(0);
557 else
558 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
559
560 LiveInterval &RI = li_->getInterval(cur->reg);
561 // FIXME: This may be overly conservative.
562 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000563}
564
Evan Cheng3e172252008-06-20 21:45:16 +0000565/// getConflictWeight - Return the number of conflicts between cur
566/// live interval and defs and uses of Reg weighted by loop depthes.
567static float getConflictWeight(LiveInterval *cur, unsigned Reg,
568 LiveIntervals *li_,
569 MachineRegisterInfo *mri_,
570 const MachineLoopInfo *loopInfo) {
571 float Conflicts = 0;
572 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
573 E = mri_->reg_end(); I != E; ++I) {
574 MachineInstr *MI = &*I;
575 if (cur->liveAt(li_->getInstructionIndex(MI))) {
576 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
577 Conflicts += powf(10.0f, (float)loopDepth);
578 }
579 }
580 return Conflicts;
581}
582
583/// findIntervalsToSpill - Determine the intervals to spill for the
584/// specified interval. It's passed the physical registers whose spill
585/// weight is the lowest among all the registers whose live intervals
586/// conflict with the interval.
587void RALinScan::findIntervalsToSpill(LiveInterval *cur,
588 std::vector<std::pair<unsigned,float> > &Candidates,
589 unsigned NumCands,
590 SmallVector<LiveInterval*, 8> &SpillIntervals) {
591 // We have figured out the *best* register to spill. But there are other
592 // registers that are pretty good as well (spill weight within 3%). Spill
593 // the one that has fewest defs and uses that conflict with cur.
594 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
595 SmallVector<LiveInterval*, 8> SLIs[3];
596
597 DOUT << "\tConsidering " << NumCands << " candidates: ";
598 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
599 DOUT << tri_->getName(Candidates[i].first) << " ";
600 DOUT << "\n";);
601
602 // Calculate the number of conflicts of each candidate.
603 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
604 unsigned Reg = i->first->reg;
605 unsigned PhysReg = vrm_->getPhys(Reg);
606 if (!cur->overlapsFrom(*i->first, i->second))
607 continue;
608 for (unsigned j = 0; j < NumCands; ++j) {
609 unsigned Candidate = Candidates[j].first;
610 if (tri_->regsOverlap(PhysReg, Candidate)) {
611 if (NumCands > 1)
612 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
613 SLIs[j].push_back(i->first);
614 }
615 }
616 }
617
618 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
619 unsigned Reg = i->first->reg;
620 unsigned PhysReg = vrm_->getPhys(Reg);
621 if (!cur->overlapsFrom(*i->first, i->second-1))
622 continue;
623 for (unsigned j = 0; j < NumCands; ++j) {
624 unsigned Candidate = Candidates[j].first;
625 if (tri_->regsOverlap(PhysReg, Candidate)) {
626 if (NumCands > 1)
627 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
628 SLIs[j].push_back(i->first);
629 }
630 }
631 }
632
633 // Which is the best candidate?
634 unsigned BestCandidate = 0;
635 float MinConflicts = Conflicts[0];
636 for (unsigned i = 1; i != NumCands; ++i) {
637 if (Conflicts[i] < MinConflicts) {
638 BestCandidate = i;
639 MinConflicts = Conflicts[i];
640 }
641 }
642
643 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
644 std::back_inserter(SpillIntervals));
645}
646
647namespace {
648 struct WeightCompare {
649 typedef std::pair<unsigned, float> RegWeightPair;
650 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
651 return LHS.second < RHS.second;
652 }
653 };
654}
655
656static bool weightsAreClose(float w1, float w2) {
657 if (!NewHeuristic)
658 return false;
659
660 float diff = w1 - w2;
661 if (diff <= 0.02f) // Within 0.02f
662 return true;
663 return (diff / w2) <= 0.05f; // Within 5%.
664}
665
Chris Lattnercbb56252004-11-18 02:42:27 +0000666/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
667/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000668void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000669{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000670 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000671
Evan Chengf30a49d2008-04-03 16:40:27 +0000672 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000673 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000674 if (cur->empty()) {
675 unsigned physReg = cur->preference;
676 if (!physReg)
677 physReg = *RC->allocation_order_begin(*mf_);
678 DOUT << tri_->getName(physReg) << '\n';
679 // Note the register is not really in use.
680 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000681 return;
682 }
683
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000684 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000685
Chris Lattnera6c17502005-08-22 20:20:42 +0000686 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000687 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000688 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000689
Evan Chengd0deec22009-01-20 00:16:18 +0000690 // If start of this live interval is defined by a move instruction and its
691 // source is assigned a physical register that is compatible with the target
692 // register class, then we should try to assign it the same register.
Evan Chengc92da382007-11-03 07:20:12 +0000693 // This can happen when the move is from a larger register class to a smaller
694 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
Evan Chengd0deec22009-01-20 00:16:18 +0000695 if (!cur->preference && cur->hasAtLeastOneValue()) {
696 VNInfo *vni = cur->begin()->valno;
Evan Chengc92da382007-11-03 07:20:12 +0000697 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
698 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000699 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
700 if (CopyMI &&
701 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000702 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000703 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000704 Reg = SrcReg;
705 else if (vrm_->isAssignedReg(SrcReg))
706 Reg = vrm_->getPhys(SrcReg);
707 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
708 cur->preference = Reg;
709 }
710 }
711 }
712
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000713 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000714 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000715 for (IntervalPtrs::const_iterator i = inactive_.begin(),
716 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000717 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000718 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000719 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000720 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000721 // If this is not in a related reg class to the register we're allocating,
722 // don't check it.
723 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
724 cur->overlapsFrom(*i->first, i->second-1)) {
725 Reg = vrm_->getPhys(Reg);
726 prt_->addRegUse(Reg);
727 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000728 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000729 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000730
731 // Speculatively check to see if we can get a register right now. If not,
732 // we know we won't be able to by adding more constraints. If so, we can
733 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
734 // is very bad (it contains all callee clobbered registers for any functions
735 // with a call), so we want to avoid doing that if possible.
736 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000737 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000738 if (physReg) {
739 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000740 // conflict with it. Check to see if we conflict with it or any of its
741 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000742 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000743 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000744 RegAliases.insert(*AS);
745
Chris Lattnera411cbc2005-08-22 20:59:30 +0000746 bool ConflictsWithFixed = false;
747 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000748 IntervalPtr &IP = fixed_[i];
749 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000750 // Okay, this reg is on the fixed list. Check to see if we actually
751 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000752 LiveInterval *I = IP.first;
753 if (I->endNumber() > StartPosition) {
754 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
755 IP.second = II;
756 if (II != I->begin() && II->start > StartPosition)
757 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000758 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000759 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000760 break;
761 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000762 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000763 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000764 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000765
766 // Okay, the register picked by our speculative getFreePhysReg call turned
767 // out to be in use. Actually add all of the conflicting fixed registers to
768 // prt so we can do an accurate query.
769 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000770 // For every interval in fixed we overlap with, mark the register as not
771 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000772 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
773 IntervalPtr &IP = fixed_[i];
774 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000775
776 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
777 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
778 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000779 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
780 IP.second = II;
781 if (II != I->begin() && II->start > StartPosition)
782 --II;
783 if (cur->overlapsFrom(*I, II)) {
784 unsigned reg = I->reg;
785 prt_->addRegUse(reg);
786 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
787 }
788 }
789 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000790
Chris Lattnera411cbc2005-08-22 20:59:30 +0000791 // Using the newly updated prt_ object, which includes conflicts in the
792 // future, see if there are any registers available.
793 physReg = getFreePhysReg(cur);
794 }
795 }
796
Chris Lattnera6c17502005-08-22 20:20:42 +0000797 // Restore the physical register tracker, removing information about the
798 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000799 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000800
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000801 // if we find a free register, we are done: assign this virtual to
802 // the free physical register and add this interval to the active
803 // list.
804 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000805 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000806 vrm_->assignVirt2Phys(cur->reg, physReg);
807 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000808 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000809 handled_.push_back(cur);
810 return;
811 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000812 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000813
Chris Lattnera6c17502005-08-22 20:20:42 +0000814 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000815 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000816 for (std::vector<std::pair<unsigned, float> >::iterator
817 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000818 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000819
820 // for each interval in active, update spill weights.
821 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
822 i != e; ++i) {
823 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000824 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000825 "Can only allocate virtual registers!");
826 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000827 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000828 }
829
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000830 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000831
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000832 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000833 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000834 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
835
836 bool Found = false;
837 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000838 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
839 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
840 e = RC->allocation_order_end(*mf_); i != e; ++i) {
841 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000842 float regWeight = SpillWeights[reg];
843 if (minWeight > regWeight)
844 Found = true;
845 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000846 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000847
848 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000849 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000850 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
851 e = RC->allocation_order_end(*mf_); i != e; ++i) {
852 unsigned reg = *i;
853 // No need to worry about if the alias register size < regsize of RC.
854 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000855 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
856 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000857 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000858 }
Evan Cheng3e172252008-06-20 21:45:16 +0000859
860 // Sort all potential spill candidates by weight.
861 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
862 minReg = RegsWeights[0].first;
863 minWeight = RegsWeights[0].second;
864 if (minWeight == HUGE_VALF) {
865 // All registers must have inf weight. Just grab one!
866 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000867 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000868 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000869 // Spill a physical register around defs and uses.
870 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000871 assignRegOrStackSlotAtInterval(cur);
872 return;
873 }
Evan Cheng3e172252008-06-20 21:45:16 +0000874 }
875
876 // Find up to 3 registers to consider as spill candidates.
877 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
878 while (LastCandidate > 1) {
879 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
880 break;
881 --LastCandidate;
882 }
883
884 DOUT << "\t\tregister(s) with min weight(s): ";
885 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
886 DOUT << tri_->getName(RegsWeights[i].first)
887 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000888
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000889 // if the current has the minimum weight, we need to spill it and
890 // add any added intervals back to unhandled, and restart
891 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000892 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000893 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000894 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000895 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000896 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000897 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000898 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000899 if (added.empty())
900 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000901
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000902 // Merge added with unhandled. Note that we know that
903 // addIntervalsForSpills returns intervals sorted by their starting
904 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000905 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000906 unhandled_.push(added[i]);
907 return;
908 }
909
Chris Lattner19828d42004-11-18 03:49:30 +0000910 ++NumBacktracks;
911
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000912 // push the current interval back to unhandled since we are going
913 // to re-run at least this iteration. Since we didn't modify it it
914 // should go back right in the front of the list
915 unhandled_.push(cur);
916
Dan Gohman6f0d0242008-02-10 18:45:23 +0000917 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000918 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000919
Evan Cheng3e172252008-06-20 21:45:16 +0000920 // We spill all intervals aliasing the register with
921 // minimum weight, rollback to the interval with the earliest
922 // start point and let the linear scan algorithm run again
923 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000924
Evan Cheng3e172252008-06-20 21:45:16 +0000925 // Determine which intervals have to be spilled.
926 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
927
928 // Set of spilled vregs (used later to rollback properly)
929 SmallSet<unsigned, 8> spilled;
930
931 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000932 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000933 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000934
Evan Cheng3e172252008-06-20 21:45:16 +0000935 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000936 // want to clear (and its aliases). We only spill those that overlap with the
937 // current interval as the rest do not affect its allocation. we also keep
938 // track of the earliest start of all spilled live intervals since this will
939 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000940 std::vector<LiveInterval*> added;
941 while (!spillIs.empty()) {
942 LiveInterval *sli = spillIs.back();
943 spillIs.pop_back();
944 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
945 earliestStart = std::min(earliestStart, sli->beginNumber());
946 float SSWeight;
947 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000948 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000949 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
950 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
951 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000952 }
953
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000954 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000955
956 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000957 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000958 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000959 while (!handled_.empty()) {
960 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000961 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000962 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000963 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000964 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000965 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000966
967 // When undoing a live interval allocation we must know if it is active or
968 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000969 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000970 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000971 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000972 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000973 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000974 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000975 prt_->delRegUse(vrm_->getPhys(i->reg));
976 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000977 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000978 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000979 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000980 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000981 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000982 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000983 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000984 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000985 "Can only allocate virtual registers!");
986 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000987 unhandled_.push(i);
988 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000989
990 // It interval has a preference, it must be defined by a copy. Clear the
991 // preference now since the source interval allocation may have been undone
992 // as well.
993 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000994 }
995
Chris Lattner19828d42004-11-18 03:49:30 +0000996 // Rewind the iterators in the active, inactive, and fixed lists back to the
997 // point we reverted to.
998 RevertVectorIteratorsTo(active_, earliestStart);
999 RevertVectorIteratorsTo(inactive_, earliestStart);
1000 RevertVectorIteratorsTo(fixed_, earliestStart);
1001
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001002 // scan the rest and undo each interval that expired after t and
1003 // insert it in active (the next iteration of the algorithm will
1004 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +00001005 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1006 LiveInterval *HI = handled_[i];
1007 if (!HI->expiredAt(earliestStart) &&
1008 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +00001009 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001010 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001011 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001012 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001013 }
1014 }
1015
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001016 // merge added with unhandled
1017 for (unsigned i = 0, e = added.size(); i != e; ++i)
1018 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001019}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001020
Chris Lattnercbb56252004-11-18 02:42:27 +00001021/// getFreePhysReg - return a free physical register for this virtual register
1022/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001023unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001024 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001025 unsigned MaxInactiveCount = 0;
1026
Evan Cheng841ee1a2008-09-18 22:38:47 +00001027 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001028 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1029
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001030 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1031 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001032 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001033 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001034 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001035
1036 // If this is not in a related reg class to the register we're allocating,
1037 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001038 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001039 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1040 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001041 if (inactiveCounts.size() <= reg)
1042 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001043 ++inactiveCounts[reg];
1044 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1045 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001046 }
1047
Chris Lattnerf8355d92005-08-22 16:55:22 +00001048 unsigned FreeReg = 0;
1049 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001050
1051 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001052 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001053 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001054 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001055 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001056 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001057 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001058 return cur->preference;
1059 } else
1060 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001061 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001062 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001063
Chris Lattnerf8355d92005-08-22 16:55:22 +00001064 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001065 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1066 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001067 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001068 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001069 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001070 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001071 if (FreeReg < inactiveCounts.size())
1072 FreeRegInactiveCount = inactiveCounts[FreeReg];
1073 else
1074 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001075 break;
1076 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001077
Chris Lattnerf8355d92005-08-22 16:55:22 +00001078 // If there are no free regs, or if this reg has the max inactive count,
1079 // return this register.
1080 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1081
1082 // Continue scanning the registers, looking for the one with the highest
1083 // inactive count. Alkis found that this reduced register pressure very
1084 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1085 // reevaluated now.
1086 for (; I != E; ++I) {
1087 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001088 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001089 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001090 FreeReg = Reg;
1091 FreeRegInactiveCount = inactiveCounts[Reg];
1092 if (FreeRegInactiveCount == MaxInactiveCount)
1093 break; // We found the one with the max inactive count.
1094 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001095 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001096
1097 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001098}
1099
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001100FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001101 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001102}