blob: 31e47f96b4cdb1d0d9fe641f8c3077cbcb16947c [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000034#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000035#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000036#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000037#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000038#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000039#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000040#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041using namespace llvm;
42
Chris Lattnercd3245a2006-12-19 22:41:21 +000043STATISTIC(NumIters , "Number of iterations performed");
44STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000045STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000046
Evan Cheng3e172252008-06-20 21:45:16 +000047static cl::opt<bool>
48NewHeuristic("new-spilling-heuristic",
49 cl::desc("Use new spilling heuristic"),
50 cl::init(false), cl::Hidden);
51
Chris Lattnercd3245a2006-12-19 22:41:21 +000052static RegisterRegAlloc
53linearscanRegAlloc("linearscan", " linear scan register allocator",
54 createLinearScanRegisterAllocator);
55
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000056namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000057 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000058 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000059 RALinScan() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnercbb56252004-11-18 02:42:27 +000061 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000062 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
Chris Lattnercbb56252004-11-18 02:42:27 +000063 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000064 /// RelatedRegClasses - This structure is built the first time a function is
65 /// compiled, and keeps track of which register classes have registers that
66 /// belong to multiple classes or have aliases that are in other classes.
67 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
Owen Anderson97382162008-08-13 23:36:23 +000068 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
Chris Lattnerb9805782005-08-23 22:27:31 +000069
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 MachineFunction* mf_;
Evan Cheng3e172252008-06-20 21:45:16 +000071 MachineRegisterInfo* mri_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000072 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000073 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000074 const TargetInstrInfo* tii_;
Evan Chengc92da382007-11-03 07:20:12 +000075 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 LiveIntervals* li_;
Evan Cheng3f32d652008-06-04 09:18:41 +000077 LiveStacks* ls_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000078 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000079
80 /// handled_ - Intervals are added to the handled_ set in the order of their
81 /// start value. This is uses for backtracking.
82 std::vector<LiveInterval*> handled_;
83
84 /// fixed_ - Intervals that correspond to machine registers.
85 ///
86 IntervalPtrs fixed_;
87
88 /// active_ - Intervals that are currently being processed, and which have a
89 /// live range active for the current point.
90 IntervalPtrs active_;
91
92 /// inactive_ - Intervals that are currently being processed, but which have
93 /// a hold at the current point.
94 IntervalPtrs inactive_;
95
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000096 typedef std::priority_queue<LiveInterval*,
Owen Andersoncd1dcbd2008-08-15 18:49:41 +000097 SmallVector<LiveInterval*, 64>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000098 greater_ptr<LiveInterval> > IntervalHeap;
99 IntervalHeap unhandled_;
100 std::auto_ptr<PhysRegTracker> prt_;
101 std::auto_ptr<VirtRegMap> vrm_;
102 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000103
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 public:
105 virtual const char* getPassName() const {
106 return "Linear Scan Register Allocator";
107 }
108
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000110 AU.addRequired<LiveIntervals>();
Owen Anderson95dad832008-10-07 20:22:28 +0000111 if (StrongPHIElim)
112 AU.addRequiredID(StrongPHIEliminationID);
David Greene2c17c4d2007-09-06 16:18:45 +0000113 // Make sure PassManager knows which analyses to make available
114 // to coalescing and which analyses coalescing invalidates.
115 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000116 AU.addRequired<LiveStacks>();
117 AU.addPreserved<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000118 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000119 AU.addPreserved<MachineLoopInfo>();
120 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000121 MachineFunctionPass::getAnalysisUsage(AU);
122 }
123
124 /// runOnMachineFunction - register allocate the whole function
125 bool runOnMachineFunction(MachineFunction&);
126
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000127 private:
128 /// linearScan - the linear scan algorithm
129 void linearScan();
130
Chris Lattnercbb56252004-11-18 02:42:27 +0000131 /// initIntervalSets - initialize the interval sets.
132 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000133 void initIntervalSets();
134
Chris Lattnercbb56252004-11-18 02:42:27 +0000135 /// processActiveIntervals - expire old intervals and move non-overlapping
136 /// ones to the inactive list.
137 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000138
Chris Lattnercbb56252004-11-18 02:42:27 +0000139 /// processInactiveIntervals - expire old intervals and move overlapping
140 /// ones to the active list.
141 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000142
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000143 /// assignRegOrStackSlotAtInterval - assign a register if one
144 /// is available, or spill.
145 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
146
Evan Cheng3e172252008-06-20 21:45:16 +0000147 /// findIntervalsToSpill - Determine the intervals to spill for the
148 /// specified interval. It's passed the physical registers whose spill
149 /// weight is the lowest among all the registers whose live intervals
150 /// conflict with the interval.
151 void findIntervalsToSpill(LiveInterval *cur,
152 std::vector<std::pair<unsigned,float> > &Candidates,
153 unsigned NumCands,
154 SmallVector<LiveInterval*, 8> &SpillIntervals);
155
Evan Chengc92da382007-11-03 07:20:12 +0000156 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
157 /// try allocate the definition the same register as the source register
158 /// if the register is not defined during live time of the interval. This
159 /// eliminate a copy. This is used to coalesce copies which were not
160 /// coalesced away before allocation either due to dest and src being in
161 /// different register classes or because the coalescer was overly
162 /// conservative.
163 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
164
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000165 ///
166 /// register handling helpers
167 ///
168
Chris Lattnercbb56252004-11-18 02:42:27 +0000169 /// getFreePhysReg - return a free physical register for this virtual
170 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000171 unsigned getFreePhysReg(LiveInterval* cur);
172
173 /// assignVirt2StackSlot - assigns this virtual register to a
174 /// stack slot. returns the stack slot
175 int assignVirt2StackSlot(unsigned virtReg);
176
Chris Lattnerb9805782005-08-23 22:27:31 +0000177 void ComputeRelatedRegClasses();
178
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000179 template <typename ItTy>
180 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000181 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000182 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000183 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000184 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000185 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000186 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000187 }
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000188 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000189 }
190 }
191 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000192 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000193}
194
Evan Cheng3f32d652008-06-04 09:18:41 +0000195static RegisterPass<RALinScan>
196X("linearscan-regalloc", "Linear Scan Register Allocator");
197
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000198void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000199 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000200
201 // First pass, add all reg classes to the union, and determine at least one
202 // reg class that each register is in.
203 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000204 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
205 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000206 RelatedRegClasses.insert(*RCI);
207 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
208 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000209 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000210
211 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
212 if (PRC) {
213 // Already processed this register. Just make sure we know that
214 // multiple register classes share a register.
215 RelatedRegClasses.unionSets(PRC, *RCI);
216 } else {
217 PRC = *RCI;
218 }
219 }
220 }
221
222 // Second pass, now that we know conservatively what register classes each reg
223 // belongs to, add info about aliases. We don't need to do this for targets
224 // without register aliases.
225 if (HasAliases)
Owen Anderson97382162008-08-13 23:36:23 +0000226 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
Chris Lattnerb9805782005-08-23 22:27:31 +0000227 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
228 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000229 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000230 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
231}
232
Evan Chengc92da382007-11-03 07:20:12 +0000233/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
234/// try allocate the definition the same register as the source register
235/// if the register is not defined during live time of the interval. This
236/// eliminate a copy. This is used to coalesce copies which were not
237/// coalesced away before allocation either due to dest and src being in
238/// different register classes or because the coalescer was overly
239/// conservative.
240unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000241 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000242 return Reg;
243
244 VNInfo *vni = cur.getValNumInfo(0);
245 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
246 return Reg;
247 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
248 unsigned SrcReg, DstReg;
249 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
250 return Reg;
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000251 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000252 if (!vrm_->isAssignedReg(SrcReg))
253 return Reg;
254 else
255 SrcReg = vrm_->getPhys(SrcReg);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +0000256 }
Evan Chengc92da382007-11-03 07:20:12 +0000257 if (Reg == SrcReg)
258 return Reg;
259
Evan Cheng841ee1a2008-09-18 22:38:47 +0000260 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000261 if (!RC->contains(SrcReg))
262 return Reg;
263
264 // Try to coalesce.
265 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000266 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
Bill Wendling74ab84c2008-02-26 21:11:01 +0000267 << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000268 vrm_->clearVirt(cur.reg);
269 vrm_->assignVirt2Phys(cur.reg, SrcReg);
270 ++NumCoalesce;
271 return SrcReg;
272 }
273
274 return Reg;
275}
276
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000277bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000278 mf_ = &fn;
Evan Cheng3e172252008-06-20 21:45:16 +0000279 mri_ = &fn.getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000280 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000281 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000282 tii_ = tm_->getInstrInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000283 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000284 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng3f32d652008-06-04 09:18:41 +0000285 ls_ = &getAnalysis<LiveStacks>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000286 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000287
David Greene2c17c4d2007-09-06 16:18:45 +0000288 // We don't run the coalescer here because we have no reason to
289 // interact with it. If the coalescer requires interaction, it
290 // won't do anything. If it doesn't require interaction, we assume
291 // it was run as a separate pass.
292
Chris Lattnerb9805782005-08-23 22:27:31 +0000293 // If this is the first function compiled, compute the related reg classes.
294 if (RelatedRegClasses.empty())
295 ComputeRelatedRegClasses();
296
Dan Gohman6f0d0242008-02-10 18:45:23 +0000297 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000298 vrm_.reset(new VirtRegMap(*mf_));
299 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000300
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000301 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000302
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000304
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000305 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000306 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000307 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000308
Dan Gohman51cd9d62008-06-23 23:51:16 +0000309 assert(unhandled_.empty() && "Unhandled live intervals remain!");
Chris Lattnercbb56252004-11-18 02:42:27 +0000310 fixed_.clear();
311 active_.clear();
312 inactive_.clear();
313 handled_.clear();
314
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000316}
317
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000318/// initIntervalSets - initialize the interval sets.
319///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000320void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000321{
322 assert(unhandled_.empty() && fixed_.empty() &&
323 active_.empty() && inactive_.empty() &&
324 "interval sets should be empty on initialization");
325
Owen Andersoncd1dcbd2008-08-15 18:49:41 +0000326 handled_.reserve(li_->getNumIntervals());
327
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000328 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000329 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
Evan Cheng841ee1a2008-09-18 22:38:47 +0000330 mri_->setPhysRegUsed(i->second->reg);
Owen Anderson03857b22008-08-13 21:49:13 +0000331 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000332 } else
Owen Anderson03857b22008-08-13 21:49:13 +0000333 unhandled_.push(i->second);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000334 }
335}
336
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000337void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000338{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000339 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000340 DOUT << "********** LINEAR SCAN **********\n";
341 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000342
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000344
345 while (!unhandled_.empty()) {
346 // pick the interval with the earliest start point
347 LiveInterval* cur = unhandled_.top();
348 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000349 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000350 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000351
Evan Chengf30a49d2008-04-03 16:40:27 +0000352 if (!cur->empty()) {
353 processActiveIntervals(cur->beginNumber());
354 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000355
Evan Chengf30a49d2008-04-03 16:40:27 +0000356 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
357 "Can only allocate virtual registers!");
358 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000359
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000360 // Allocating a virtual register. try to find a free
361 // physical register or spill an interval (possibly this one) in order to
362 // assign it one.
363 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000365 DEBUG(printIntervals("active", active_.begin(), active_.end()));
366 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000367 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000368
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000370 while (!active_.empty()) {
371 IntervalPtr &IP = active_.back();
372 unsigned reg = IP.first->reg;
373 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000374 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000375 "Can only allocate virtual registers!");
376 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000377 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000378 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000380
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000381 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000382 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000383 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000384 DOUT << "\tinterval " << *i->first << " expired\n");
385 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000386
Evan Cheng81a03822007-11-17 00:40:40 +0000387 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000388 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000389 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000390 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Owen Anderson03857b22008-08-13 21:49:13 +0000391 LiveInterval &cur = *i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000392 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000393 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000394 if (isPhys)
Owen Anderson03857b22008-08-13 21:49:13 +0000395 Reg = cur.reg;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000396 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000397 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000398 if (!Reg)
399 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000400 // Ignore splited live intervals.
401 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
402 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000403 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
404 I != E; ++I) {
405 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000406 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
407 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
408 if (LiveInMBBs[i] != EntryMBB)
409 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000410 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000411 }
412 }
413 }
414
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000415 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000416}
417
Chris Lattnercbb56252004-11-18 02:42:27 +0000418/// processActiveIntervals - expire old intervals and move non-overlapping ones
419/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000420void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000421{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000422 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000423
Chris Lattnercbb56252004-11-18 02:42:27 +0000424 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
425 LiveInterval *Interval = active_[i].first;
426 LiveInterval::iterator IntervalPos = active_[i].second;
427 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000428
Chris Lattnercbb56252004-11-18 02:42:27 +0000429 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
430
431 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000432 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000433 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000434 "Can only allocate virtual registers!");
435 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000436 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000437
438 // Pop off the end of the list.
439 active_[i] = active_.back();
440 active_.pop_back();
441 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000442
Chris Lattnercbb56252004-11-18 02:42:27 +0000443 } else if (IntervalPos->start > CurPoint) {
444 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000445 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000446 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000447 "Can only allocate virtual registers!");
448 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000450 // add to inactive.
451 inactive_.push_back(std::make_pair(Interval, IntervalPos));
452
453 // Pop off the end of the list.
454 active_[i] = active_.back();
455 active_.pop_back();
456 --i; --e;
457 } else {
458 // Otherwise, just update the iterator position.
459 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 }
461 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000462}
463
Chris Lattnercbb56252004-11-18 02:42:27 +0000464/// processInactiveIntervals - expire old intervals and move overlapping
465/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000466void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000467{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000468 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000469
Chris Lattnercbb56252004-11-18 02:42:27 +0000470 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
471 LiveInterval *Interval = inactive_[i].first;
472 LiveInterval::iterator IntervalPos = inactive_[i].second;
473 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000474
Chris Lattnercbb56252004-11-18 02:42:27 +0000475 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000476
Chris Lattnercbb56252004-11-18 02:42:27 +0000477 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000478 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000479
Chris Lattnercbb56252004-11-18 02:42:27 +0000480 // Pop off the end of the list.
481 inactive_[i] = inactive_.back();
482 inactive_.pop_back();
483 --i; --e;
484 } else if (IntervalPos->start <= CurPoint) {
485 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000486 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000487 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000488 "Can only allocate virtual registers!");
489 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000490 prt_->addRegUse(reg);
491 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000492 active_.push_back(std::make_pair(Interval, IntervalPos));
493
494 // Pop off the end of the list.
495 inactive_[i] = inactive_.back();
496 inactive_.pop_back();
497 --i; --e;
498 } else {
499 // Otherwise, just update the iterator position.
500 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000501 }
502 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000503}
504
Chris Lattnercbb56252004-11-18 02:42:27 +0000505/// updateSpillWeights - updates the spill weights of the specifed physical
506/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000507static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000508 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000509 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000510 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000511 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000512 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000513}
514
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000515static
516RALinScan::IntervalPtrs::iterator
517FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
518 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
519 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000520 if (I->first == LI) return I;
521 return IP.end();
522}
523
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000524static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000525 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000526 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000527 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
528 IP.second, Point);
529 if (I != IP.first->begin()) --I;
530 IP.second = I;
531 }
532}
Chris Lattnercbb56252004-11-18 02:42:27 +0000533
Evan Cheng3f32d652008-06-04 09:18:41 +0000534/// addStackInterval - Create a LiveInterval for stack if the specified live
535/// interval has been spilled.
536static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000537 LiveIntervals *li_, float &Weight,
538 VirtRegMap &vrm_) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000539 int SS = vrm_.getStackSlot(cur->reg);
540 if (SS == VirtRegMap::NO_STACK_SLOT)
541 return;
542 LiveInterval &SI = ls_->getOrCreateInterval(SS);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000543 SI.weight += Weight;
544
Evan Cheng3f32d652008-06-04 09:18:41 +0000545 VNInfo *VNI;
546 if (SI.getNumValNums())
547 VNI = SI.getValNumInfo(0);
548 else
549 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
550
551 LiveInterval &RI = li_->getInterval(cur->reg);
552 // FIXME: This may be overly conservative.
553 SI.MergeRangesInAsValue(RI, VNI);
Evan Cheng3f32d652008-06-04 09:18:41 +0000554}
555
Evan Cheng3e172252008-06-20 21:45:16 +0000556/// getConflictWeight - Return the number of conflicts between cur
557/// live interval and defs and uses of Reg weighted by loop depthes.
558static float getConflictWeight(LiveInterval *cur, unsigned Reg,
559 LiveIntervals *li_,
560 MachineRegisterInfo *mri_,
561 const MachineLoopInfo *loopInfo) {
562 float Conflicts = 0;
563 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
564 E = mri_->reg_end(); I != E; ++I) {
565 MachineInstr *MI = &*I;
566 if (cur->liveAt(li_->getInstructionIndex(MI))) {
567 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
568 Conflicts += powf(10.0f, (float)loopDepth);
569 }
570 }
571 return Conflicts;
572}
573
574/// findIntervalsToSpill - Determine the intervals to spill for the
575/// specified interval. It's passed the physical registers whose spill
576/// weight is the lowest among all the registers whose live intervals
577/// conflict with the interval.
578void RALinScan::findIntervalsToSpill(LiveInterval *cur,
579 std::vector<std::pair<unsigned,float> > &Candidates,
580 unsigned NumCands,
581 SmallVector<LiveInterval*, 8> &SpillIntervals) {
582 // We have figured out the *best* register to spill. But there are other
583 // registers that are pretty good as well (spill weight within 3%). Spill
584 // the one that has fewest defs and uses that conflict with cur.
585 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
586 SmallVector<LiveInterval*, 8> SLIs[3];
587
588 DOUT << "\tConsidering " << NumCands << " candidates: ";
589 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
590 DOUT << tri_->getName(Candidates[i].first) << " ";
591 DOUT << "\n";);
592
593 // Calculate the number of conflicts of each candidate.
594 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
595 unsigned Reg = i->first->reg;
596 unsigned PhysReg = vrm_->getPhys(Reg);
597 if (!cur->overlapsFrom(*i->first, i->second))
598 continue;
599 for (unsigned j = 0; j < NumCands; ++j) {
600 unsigned Candidate = Candidates[j].first;
601 if (tri_->regsOverlap(PhysReg, Candidate)) {
602 if (NumCands > 1)
603 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
604 SLIs[j].push_back(i->first);
605 }
606 }
607 }
608
609 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
610 unsigned Reg = i->first->reg;
611 unsigned PhysReg = vrm_->getPhys(Reg);
612 if (!cur->overlapsFrom(*i->first, i->second-1))
613 continue;
614 for (unsigned j = 0; j < NumCands; ++j) {
615 unsigned Candidate = Candidates[j].first;
616 if (tri_->regsOverlap(PhysReg, Candidate)) {
617 if (NumCands > 1)
618 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
619 SLIs[j].push_back(i->first);
620 }
621 }
622 }
623
624 // Which is the best candidate?
625 unsigned BestCandidate = 0;
626 float MinConflicts = Conflicts[0];
627 for (unsigned i = 1; i != NumCands; ++i) {
628 if (Conflicts[i] < MinConflicts) {
629 BestCandidate = i;
630 MinConflicts = Conflicts[i];
631 }
632 }
633
634 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
635 std::back_inserter(SpillIntervals));
636}
637
638namespace {
639 struct WeightCompare {
640 typedef std::pair<unsigned, float> RegWeightPair;
641 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
642 return LHS.second < RHS.second;
643 }
644 };
645}
646
647static bool weightsAreClose(float w1, float w2) {
648 if (!NewHeuristic)
649 return false;
650
651 float diff = w1 - w2;
652 if (diff <= 0.02f) // Within 0.02f
653 return true;
654 return (diff / w2) <= 0.05f; // Within 5%.
655}
656
Chris Lattnercbb56252004-11-18 02:42:27 +0000657/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
658/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000659void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000660{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000661 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000662
Evan Chengf30a49d2008-04-03 16:40:27 +0000663 // This is an implicitly defined live interval, just assign any register.
Evan Cheng841ee1a2008-09-18 22:38:47 +0000664 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000665 if (cur->empty()) {
666 unsigned physReg = cur->preference;
667 if (!physReg)
668 physReg = *RC->allocation_order_begin(*mf_);
669 DOUT << tri_->getName(physReg) << '\n';
670 // Note the register is not really in use.
671 vrm_->assignVirt2Phys(cur->reg, physReg);
Evan Chengf30a49d2008-04-03 16:40:27 +0000672 return;
673 }
674
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000675 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000676
Chris Lattnera6c17502005-08-22 20:20:42 +0000677 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000678 unsigned StartPosition = cur->beginNumber();
Chris Lattnerb9805782005-08-23 22:27:31 +0000679 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000680
681 // If this live interval is defined by a move instruction and its source is
682 // assigned a physical register that is compatible with the target register
683 // class, then we should try to assign it the same register.
684 // This can happen when the move is from a larger register class to a smaller
685 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
686 if (!cur->preference && cur->containsOneValue()) {
687 VNInfo *vni = cur->getValNumInfo(0);
688 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
689 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
690 unsigned SrcReg, DstReg;
Evan Chengf2b24ca2008-04-11 17:55:47 +0000691 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
Evan Chengc92da382007-11-03 07:20:12 +0000692 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000693 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000694 Reg = SrcReg;
695 else if (vrm_->isAssignedReg(SrcReg))
696 Reg = vrm_->getPhys(SrcReg);
697 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
698 cur->preference = Reg;
699 }
700 }
701 }
702
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000703 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000704 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000705 for (IntervalPtrs::const_iterator i = inactive_.begin(),
706 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000707 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000708 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000709 "Can only allocate virtual registers!");
Evan Cheng841ee1a2008-09-18 22:38:47 +0000710 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000711 // If this is not in a related reg class to the register we're allocating,
712 // don't check it.
713 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
714 cur->overlapsFrom(*i->first, i->second-1)) {
715 Reg = vrm_->getPhys(Reg);
716 prt_->addRegUse(Reg);
717 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000718 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000719 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000720
721 // Speculatively check to see if we can get a register right now. If not,
722 // we know we won't be able to by adding more constraints. If so, we can
723 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
724 // is very bad (it contains all callee clobbered registers for any functions
725 // with a call), so we want to avoid doing that if possible.
726 unsigned physReg = getFreePhysReg(cur);
Evan Cheng676dd7c2008-03-11 07:19:34 +0000727 unsigned BestPhysReg = physReg;
Chris Lattnera411cbc2005-08-22 20:59:30 +0000728 if (physReg) {
729 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000730 // conflict with it. Check to see if we conflict with it or any of its
731 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000732 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000733 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000734 RegAliases.insert(*AS);
735
Chris Lattnera411cbc2005-08-22 20:59:30 +0000736 bool ConflictsWithFixed = false;
737 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000738 IntervalPtr &IP = fixed_[i];
739 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000740 // Okay, this reg is on the fixed list. Check to see if we actually
741 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000742 LiveInterval *I = IP.first;
743 if (I->endNumber() > StartPosition) {
744 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
745 IP.second = II;
746 if (II != I->begin() && II->start > StartPosition)
747 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000748 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000749 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000750 break;
751 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000752 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000753 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000754 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000755
756 // Okay, the register picked by our speculative getFreePhysReg call turned
757 // out to be in use. Actually add all of the conflicting fixed registers to
758 // prt so we can do an accurate query.
759 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000760 // For every interval in fixed we overlap with, mark the register as not
761 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000762 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
763 IntervalPtr &IP = fixed_[i];
764 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000765
766 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
767 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
768 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000769 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
770 IP.second = II;
771 if (II != I->begin() && II->start > StartPosition)
772 --II;
773 if (cur->overlapsFrom(*I, II)) {
774 unsigned reg = I->reg;
775 prt_->addRegUse(reg);
776 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
777 }
778 }
779 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000780
Chris Lattnera411cbc2005-08-22 20:59:30 +0000781 // Using the newly updated prt_ object, which includes conflicts in the
782 // future, see if there are any registers available.
783 physReg = getFreePhysReg(cur);
784 }
785 }
786
Chris Lattnera6c17502005-08-22 20:20:42 +0000787 // Restore the physical register tracker, removing information about the
788 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000789 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000790
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000791 // if we find a free register, we are done: assign this virtual to
792 // the free physical register and add this interval to the active
793 // list.
794 if (physReg) {
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000795 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000796 vrm_->assignVirt2Phys(cur->reg, physReg);
797 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000798 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000799 handled_.push_back(cur);
800 return;
801 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000802 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000803
Chris Lattnera6c17502005-08-22 20:20:42 +0000804 // Compile the spill weights into an array that is better for scanning.
Evan Cheng3e172252008-06-20 21:45:16 +0000805 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
Chris Lattnera6c17502005-08-22 20:20:42 +0000806 for (std::vector<std::pair<unsigned, float> >::iterator
807 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000808 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000809
810 // for each interval in active, update spill weights.
811 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
812 i != e; ++i) {
813 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000814 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000815 "Can only allocate virtual registers!");
816 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000817 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000818 }
819
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000820 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000821
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000822 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000823 float minWeight = HUGE_VALF;
Evan Cheng3e172252008-06-20 21:45:16 +0000824 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
825
826 bool Found = false;
827 std::vector<std::pair<unsigned,float> > RegsWeights;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000828 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
829 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
830 e = RC->allocation_order_end(*mf_); i != e; ++i) {
831 unsigned reg = *i;
Evan Cheng3e172252008-06-20 21:45:16 +0000832 float regWeight = SpillWeights[reg];
833 if (minWeight > regWeight)
834 Found = true;
835 RegsWeights.push_back(std::make_pair(reg, regWeight));
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000836 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000837
838 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3e172252008-06-20 21:45:16 +0000839 if (!Found) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000840 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
841 e = RC->allocation_order_end(*mf_); i != e; ++i) {
842 unsigned reg = *i;
843 // No need to worry about if the alias register size < regsize of RC.
844 // We are going to spill all registers that alias it anyway.
Evan Cheng3e172252008-06-20 21:45:16 +0000845 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
846 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
Evan Cheng676dd7c2008-03-11 07:19:34 +0000847 }
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000848 }
Evan Cheng3e172252008-06-20 21:45:16 +0000849
850 // Sort all potential spill candidates by weight.
851 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
852 minReg = RegsWeights[0].first;
853 minWeight = RegsWeights[0].second;
854 if (minWeight == HUGE_VALF) {
855 // All registers must have inf weight. Just grab one!
856 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
Owen Andersona1566f22008-07-22 22:46:49 +0000857 if (cur->weight == HUGE_VALF ||
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000858 li_->getApproximateInstructionCount(*cur) == 0) {
Evan Cheng3e172252008-06-20 21:45:16 +0000859 // Spill a physical register around defs and uses.
860 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
Evan Cheng5e8d9de2008-09-20 01:28:05 +0000861 assignRegOrStackSlotAtInterval(cur);
862 return;
863 }
Evan Cheng3e172252008-06-20 21:45:16 +0000864 }
865
866 // Find up to 3 registers to consider as spill candidates.
867 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
868 while (LastCandidate > 1) {
869 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
870 break;
871 --LastCandidate;
872 }
873
874 DOUT << "\t\tregister(s) with min weight(s): ";
875 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
876 DOUT << tri_->getName(RegsWeights[i].first)
877 << " (" << RegsWeights[i].second << ")\n");
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000878
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000879 // if the current has the minimum weight, we need to spill it and
880 // add any added intervals back to unhandled, and restart
881 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000882 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000883 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Evan Cheng9c3c2212008-06-06 07:54:39 +0000884 float SSWeight;
Evan Chengdc377862008-09-30 15:44:16 +0000885 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000886 std::vector<LiveInterval*> added =
Evan Chengdc377862008-09-30 15:44:16 +0000887 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng9c3c2212008-06-06 07:54:39 +0000888 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000889 if (added.empty())
890 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000891
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000892 // Merge added with unhandled. Note that we know that
893 // addIntervalsForSpills returns intervals sorted by their starting
894 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000895 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000896 unhandled_.push(added[i]);
897 return;
898 }
899
Chris Lattner19828d42004-11-18 03:49:30 +0000900 ++NumBacktracks;
901
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000902 // push the current interval back to unhandled since we are going
903 // to re-run at least this iteration. Since we didn't modify it it
904 // should go back right in the front of the list
905 unhandled_.push(cur);
906
Dan Gohman6f0d0242008-02-10 18:45:23 +0000907 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000908 "did not choose a register to spill?");
Chris Lattner19828d42004-11-18 03:49:30 +0000909
Evan Cheng3e172252008-06-20 21:45:16 +0000910 // We spill all intervals aliasing the register with
911 // minimum weight, rollback to the interval with the earliest
912 // start point and let the linear scan algorithm run again
913 SmallVector<LiveInterval*, 8> spillIs;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000914
Evan Cheng3e172252008-06-20 21:45:16 +0000915 // Determine which intervals have to be spilled.
916 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
917
918 // Set of spilled vregs (used later to rollback properly)
919 SmallSet<unsigned, 8> spilled;
920
921 // The earliest start of a Spilled interval indicates up to where
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000922 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000923 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000924
Evan Cheng3e172252008-06-20 21:45:16 +0000925 // Spill live intervals of virtual regs mapped to the physical register we
Chris Lattner19828d42004-11-18 03:49:30 +0000926 // want to clear (and its aliases). We only spill those that overlap with the
927 // current interval as the rest do not affect its allocation. we also keep
928 // track of the earliest start of all spilled live intervals since this will
929 // mark our rollback point.
Evan Cheng3e172252008-06-20 21:45:16 +0000930 std::vector<LiveInterval*> added;
931 while (!spillIs.empty()) {
932 LiveInterval *sli = spillIs.back();
933 spillIs.pop_back();
934 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
935 earliestStart = std::min(earliestStart, sli->beginNumber());
936 float SSWeight;
937 std::vector<LiveInterval*> newIs =
Evan Chengdc377862008-09-30 15:44:16 +0000938 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
Evan Cheng3e172252008-06-20 21:45:16 +0000939 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
940 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
941 spilled.insert(sli->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000942 }
943
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000944 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000945
946 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000947 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000948 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000949 while (!handled_.empty()) {
950 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000951 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000952 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000953 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000954 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000955 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000956
957 // When undoing a live interval allocation we must know if it is active or
958 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000959 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000960 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000961 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000962 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000963 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000964 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000965 prt_->delRegUse(vrm_->getPhys(i->reg));
966 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000967 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000968 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000969 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000970 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000971 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000972 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000973 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000974 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000975 "Can only allocate virtual registers!");
976 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000977 unhandled_.push(i);
978 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000979
980 // It interval has a preference, it must be defined by a copy. Clear the
981 // preference now since the source interval allocation may have been undone
982 // as well.
983 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000984 }
985
Chris Lattner19828d42004-11-18 03:49:30 +0000986 // Rewind the iterators in the active, inactive, and fixed lists back to the
987 // point we reverted to.
988 RevertVectorIteratorsTo(active_, earliestStart);
989 RevertVectorIteratorsTo(inactive_, earliestStart);
990 RevertVectorIteratorsTo(fixed_, earliestStart);
991
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000992 // scan the rest and undo each interval that expired after t and
993 // insert it in active (the next iteration of the algorithm will
994 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000995 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
996 LiveInterval *HI = handled_[i];
997 if (!HI->expiredAt(earliestStart) &&
998 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000999 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +00001000 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +00001001 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +00001002 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001003 }
1004 }
1005
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001006 // merge added with unhandled
1007 for (unsigned i = 0, e = added.size(); i != e; ++i)
1008 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +00001009}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +00001010
Chris Lattnercbb56252004-11-18 02:42:27 +00001011/// getFreePhysReg - return a free physical register for this virtual register
1012/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001013unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Chris Lattnerfe424622008-02-26 22:08:41 +00001014 SmallVector<unsigned, 256> inactiveCounts;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001015 unsigned MaxInactiveCount = 0;
1016
Evan Cheng841ee1a2008-09-18 22:38:47 +00001017 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001018 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1019
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001020 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1021 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +00001022 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001023 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +00001024 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +00001025
1026 // If this is not in a related reg class to the register we're allocating,
1027 // don't check it.
Evan Cheng841ee1a2008-09-18 22:38:47 +00001028 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +00001029 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1030 reg = vrm_->getPhys(reg);
Chris Lattnerfe424622008-02-26 22:08:41 +00001031 if (inactiveCounts.size() <= reg)
1032 inactiveCounts.resize(reg+1);
Chris Lattnerb9805782005-08-23 22:27:31 +00001033 ++inactiveCounts[reg];
1034 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1035 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +00001036 }
1037
Chris Lattnerf8355d92005-08-22 16:55:22 +00001038 unsigned FreeReg = 0;
1039 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +00001040
1041 // If copy coalescer has assigned a "preferred" register, check if it's
Dale Johannesen86b49f82008-09-24 01:07:17 +00001042 // available first.
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001043 if (cur->preference) {
Dale Johannesen34d8f752008-09-20 02:03:04 +00001044 if (prt_->isRegAvail(cur->preference) &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001045 RC->contains(cur->preference)) {
Evan Cheng20b0abc2007-04-17 20:32:26 +00001046 DOUT << "\t\tassigned the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001047 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +00001048 return cur->preference;
1049 } else
1050 DOUT << "\t\tunable to assign the preferred register: "
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001051 << tri_->getName(cur->preference) << "\n";
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001052 }
Evan Cheng20b0abc2007-04-17 20:32:26 +00001053
Chris Lattnerf8355d92005-08-22 16:55:22 +00001054 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +00001055 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1056 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Evan Chengaf8c5632008-03-24 23:28:21 +00001057 assert(I != E && "No allocatable register in this register class!");
Chris Lattnerf8355d92005-08-22 16:55:22 +00001058 for (; I != E; ++I)
Dale Johannesen86b49f82008-09-24 01:07:17 +00001059 if (prt_->isRegAvail(*I)) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001060 FreeReg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001061 if (FreeReg < inactiveCounts.size())
1062 FreeRegInactiveCount = inactiveCounts[FreeReg];
1063 else
1064 FreeRegInactiveCount = 0;
Chris Lattnerf8355d92005-08-22 16:55:22 +00001065 break;
1066 }
Chris Lattnerfe424622008-02-26 22:08:41 +00001067
Chris Lattnerf8355d92005-08-22 16:55:22 +00001068 // If there are no free regs, or if this reg has the max inactive count,
1069 // return this register.
1070 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1071
1072 // Continue scanning the registers, looking for the one with the highest
1073 // inactive count. Alkis found that this reduced register pressure very
1074 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1075 // reevaluated now.
1076 for (; I != E; ++I) {
1077 unsigned Reg = *I;
Chris Lattnerfe424622008-02-26 22:08:41 +00001078 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
Dale Johannesen86b49f82008-09-24 01:07:17 +00001079 FreeRegInactiveCount < inactiveCounts[Reg]) {
Chris Lattnerf8355d92005-08-22 16:55:22 +00001080 FreeReg = Reg;
1081 FreeRegInactiveCount = inactiveCounts[Reg];
1082 if (FreeRegInactiveCount == MaxInactiveCount)
1083 break; // We found the one with the max inactive count.
1084 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001085 }
Chris Lattnerf8355d92005-08-22 16:55:22 +00001086
1087 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001088}
1089
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001090FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001091 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001092}