blob: c70ff9524328d237e0eb48f85cc097c3446c1c22 [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 Lattner3c3fe462005-09-21 04:19:09 +000015#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000016#include "PhysRegTracker.h"
17#include "VirtRegMap.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000018#include "llvm/Function.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000019#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000024#include "llvm/CodeGen/RegAllocRegistry.h"
David Greene2c17c4d2007-09-06 16:18:45 +000025#include "llvm/CodeGen/RegisterCoalescer.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000026#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000027#include "llvm/Target/TargetMachine.h"
Evan Chengc92da382007-11-03 07:20:12 +000028#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000029#include "llvm/ADT/EquivalenceClasses.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/Statistic.h"
31#include "llvm/ADT/STLExtras.h"
Chris Lattnerb9805782005-08-23 22:27:31 +000032#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000033#include "llvm/Support/Compiler.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000034#include <algorithm>
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +000035#include <set>
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +000036#include <queue>
Duraid Madina30059612005-12-28 04:55:42 +000037#include <memory>
Jeff Cohen97af7512006-12-02 02:22:01 +000038#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000039using namespace llvm;
40
Chris Lattnercd3245a2006-12-19 22:41:21 +000041STATISTIC(NumIters , "Number of iterations performed");
42STATISTIC(NumBacktracks, "Number of times we had to backtrack");
Evan Chengc92da382007-11-03 07:20:12 +000043STATISTIC(NumCoalesce, "Number of copies coalesced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000044
45static RegisterRegAlloc
46linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
48
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000049namespace {
Bill Wendlinge23e00d2007-05-08 19:02:46 +000050 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000051 static char ID;
Bill Wendlinge23e00d2007-05-08 19:02:46 +000052 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000053
Chris Lattnercbb56252004-11-18 02:42:27 +000054 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
56 private:
Chris Lattnerb9805782005-08-23 22:27:31 +000057 /// RelatedRegClasses - This structure is built the first time a function is
58 /// compiled, and keeps track of which register classes have registers that
59 /// belong to multiple classes or have aliases that are in other classes.
60 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
61 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
62
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000063 MachineFunction* mf_;
64 const TargetMachine* tm_;
Dan Gohman6f0d0242008-02-10 18:45:23 +000065 const TargetRegisterInfo* tri_;
Evan Chengc92da382007-11-03 07:20:12 +000066 const TargetInstrInfo* tii_;
Chris Lattner84bc5422007-12-31 04:13:23 +000067 MachineRegisterInfo *reginfo_;
Evan Chengc92da382007-11-03 07:20:12 +000068 BitVector allocatableRegs_;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 LiveIntervals* li_;
Evan Cheng22f07ff2007-12-11 02:09:15 +000070 const MachineLoopInfo *loopInfo;
Chris Lattnercbb56252004-11-18 02:42:27 +000071
72 /// handled_ - Intervals are added to the handled_ set in the order of their
73 /// start value. This is uses for backtracking.
74 std::vector<LiveInterval*> handled_;
75
76 /// fixed_ - Intervals that correspond to machine registers.
77 ///
78 IntervalPtrs fixed_;
79
80 /// active_ - Intervals that are currently being processed, and which have a
81 /// live range active for the current point.
82 IntervalPtrs active_;
83
84 /// inactive_ - Intervals that are currently being processed, but which have
85 /// a hold at the current point.
86 IntervalPtrs inactive_;
87
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 typedef std::priority_queue<LiveInterval*,
Chris Lattnercbb56252004-11-18 02:42:27 +000089 std::vector<LiveInterval*>,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000090 greater_ptr<LiveInterval> > IntervalHeap;
91 IntervalHeap unhandled_;
92 std::auto_ptr<PhysRegTracker> prt_;
93 std::auto_ptr<VirtRegMap> vrm_;
94 std::auto_ptr<Spiller> spiller_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000095
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000096 public:
97 virtual const char* getPassName() const {
98 return "Linear Scan Register Allocator";
99 }
100
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000102 AU.addRequired<LiveIntervals>();
David Greene2c17c4d2007-09-06 16:18:45 +0000103 // Make sure PassManager knows which analyses to make available
104 // to coalescing and which analyses coalescing invalidates.
105 AU.addRequiredTransitive<RegisterCoalescer>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000106 AU.addRequired<MachineLoopInfo>();
Bill Wendling67d65bb2008-01-04 20:54:55 +0000107 AU.addPreserved<MachineLoopInfo>();
108 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000109 MachineFunctionPass::getAnalysisUsage(AU);
110 }
111
112 /// runOnMachineFunction - register allocate the whole function
113 bool runOnMachineFunction(MachineFunction&);
114
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 private:
116 /// linearScan - the linear scan algorithm
117 void linearScan();
118
Chris Lattnercbb56252004-11-18 02:42:27 +0000119 /// initIntervalSets - initialize the interval sets.
120 ///
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000121 void initIntervalSets();
122
Chris Lattnercbb56252004-11-18 02:42:27 +0000123 /// processActiveIntervals - expire old intervals and move non-overlapping
124 /// ones to the inactive list.
125 void processActiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000126
Chris Lattnercbb56252004-11-18 02:42:27 +0000127 /// processInactiveIntervals - expire old intervals and move overlapping
128 /// ones to the active list.
129 void processInactiveIntervals(unsigned CurPoint);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 /// assignRegOrStackSlotAtInterval - assign a register if one
132 /// is available, or spill.
133 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
134
Evan Chengc92da382007-11-03 07:20:12 +0000135 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
136 /// try allocate the definition the same register as the source register
137 /// if the register is not defined during live time of the interval. This
138 /// eliminate a copy. This is used to coalesce copies which were not
139 /// coalesced away before allocation either due to dest and src being in
140 /// different register classes or because the coalescer was overly
141 /// conservative.
142 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
143
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000144 ///
145 /// register handling helpers
146 ///
147
Chris Lattnercbb56252004-11-18 02:42:27 +0000148 /// getFreePhysReg - return a free physical register for this virtual
149 /// register interval if we have one, otherwise return 0.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150 unsigned getFreePhysReg(LiveInterval* cur);
151
152 /// assignVirt2StackSlot - assigns this virtual register to a
153 /// stack slot. returns the stack slot
154 int assignVirt2StackSlot(unsigned virtReg);
155
Chris Lattnerb9805782005-08-23 22:27:31 +0000156 void ComputeRelatedRegClasses();
157
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000158 template <typename ItTy>
159 void printIntervals(const char* const str, ItTy i, ItTy e) const {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000160 if (str) DOUT << str << " intervals:\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000161 for (; i != e; ++i) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000162 DOUT << "\t" << *i->first << " -> ";
Chris Lattnercbb56252004-11-18 02:42:27 +0000163 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000164 if (TargetRegisterInfo::isVirtualRegister(reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000165 reg = vrm_->getPhys(reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000166 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000167 DOUT << tri_->getName(reg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000168 }
169 }
170 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000171 char RALinScan::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000172}
173
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000174void RALinScan::ComputeRelatedRegClasses() {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000175 const TargetRegisterInfo &TRI = *tri_;
Chris Lattnerb9805782005-08-23 22:27:31 +0000176
177 // First pass, add all reg classes to the union, and determine at least one
178 // reg class that each register is in.
179 bool HasAliases = false;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000180 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
181 E = TRI.regclass_end(); RCI != E; ++RCI) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000182 RelatedRegClasses.insert(*RCI);
183 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
184 I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000185 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
Chris Lattnerb9805782005-08-23 22:27:31 +0000186
187 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
188 if (PRC) {
189 // Already processed this register. Just make sure we know that
190 // multiple register classes share a register.
191 RelatedRegClasses.unionSets(PRC, *RCI);
192 } else {
193 PRC = *RCI;
194 }
195 }
196 }
197
198 // Second pass, now that we know conservatively what register classes each reg
199 // belongs to, add info about aliases. We don't need to do this for targets
200 // without register aliases.
201 if (HasAliases)
202 for (std::map<unsigned, const TargetRegisterClass*>::iterator
203 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
204 I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000205 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
Chris Lattnerb9805782005-08-23 22:27:31 +0000206 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
207}
208
Evan Chengc92da382007-11-03 07:20:12 +0000209/// attemptTrivialCoalescing - If a simple interval is defined by a copy,
210/// try allocate the definition the same register as the source register
211/// if the register is not defined during live time of the interval. This
212/// eliminate a copy. This is used to coalesce copies which were not
213/// coalesced away before allocation either due to dest and src being in
214/// different register classes or because the coalescer was overly
215/// conservative.
216unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
Evan Cheng9aeaf752007-11-04 08:32:21 +0000217 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
Evan Chengc92da382007-11-03 07:20:12 +0000218 return Reg;
219
220 VNInfo *vni = cur.getValNumInfo(0);
221 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
222 return Reg;
223 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
224 unsigned SrcReg, DstReg;
225 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
226 return Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000227 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000228 if (!vrm_->isAssignedReg(SrcReg))
229 return Reg;
230 else
231 SrcReg = vrm_->getPhys(SrcReg);
232 if (Reg == SrcReg)
233 return Reg;
234
Chris Lattner84bc5422007-12-31 04:13:23 +0000235 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
Evan Chengc92da382007-11-03 07:20:12 +0000236 if (!RC->contains(SrcReg))
237 return Reg;
238
239 // Try to coalesce.
240 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000241 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg) << '\n';
Evan Chengc92da382007-11-03 07:20:12 +0000242 vrm_->clearVirt(cur.reg);
243 vrm_->assignVirt2Phys(cur.reg, SrcReg);
244 ++NumCoalesce;
245 return SrcReg;
246 }
247
248 return Reg;
249}
250
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000251bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 mf_ = &fn;
253 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000254 tri_ = tm_->getRegisterInfo();
Evan Chengc92da382007-11-03 07:20:12 +0000255 tii_ = tm_->getInstrInfo();
Chris Lattner84bc5422007-12-31 04:13:23 +0000256 reginfo_ = &mf_->getRegInfo();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000257 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000258 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000259 loopInfo = &getAnalysis<MachineLoopInfo>();
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000260
David Greene2c17c4d2007-09-06 16:18:45 +0000261 // We don't run the coalescer here because we have no reason to
262 // interact with it. If the coalescer requires interaction, it
263 // won't do anything. If it doesn't require interaction, we assume
264 // it was run as a separate pass.
265
Chris Lattnerb9805782005-08-23 22:27:31 +0000266 // If this is the first function compiled, compute the related reg classes.
267 if (RelatedRegClasses.empty())
268 ComputeRelatedRegClasses();
269
Dan Gohman6f0d0242008-02-10 18:45:23 +0000270 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000271 vrm_.reset(new VirtRegMap(*mf_));
272 if (!spiller_.get()) spiller_.reset(createSpiller());
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000273
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000274 initIntervalSets();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000275
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000276 linearScan();
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000277
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000278 // Rewrite spill code and update the PhysRegsUsed set.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000279 spiller_->runOnMachineFunction(*mf_, *vrm_);
Chris Lattner510a3ea2004-09-30 02:02:33 +0000280 vrm_.reset(); // Free the VirtRegMap
Chris Lattnercbb56252004-11-18 02:42:27 +0000281
Chris Lattnercbb56252004-11-18 02:42:27 +0000282 while (!unhandled_.empty()) unhandled_.pop();
283 fixed_.clear();
284 active_.clear();
285 inactive_.clear();
286 handled_.clear();
287
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000288 return true;
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000289}
290
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000291/// initIntervalSets - initialize the interval sets.
292///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000293void RALinScan::initIntervalSets()
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000294{
295 assert(unhandled_.empty() && fixed_.empty() &&
296 active_.empty() && inactive_.empty() &&
297 "interval sets should be empty on initialization");
298
299 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000300 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000301 reginfo_->setPhysRegUsed(i->second.reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000302 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
Chris Lattnerb0f31bf2005-01-23 22:45:13 +0000303 } else
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000304 unhandled_.push(&i->second);
305 }
306}
307
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000308void RALinScan::linearScan()
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +0000309{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000310 // linear scan algorithm
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000311 DOUT << "********** LINEAR SCAN **********\n";
312 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000313
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000314 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000315
316 while (!unhandled_.empty()) {
317 // pick the interval with the earliest start point
318 LiveInterval* cur = unhandled_.top();
319 unhandled_.pop();
Evan Cheng11923cc2007-10-16 21:09:14 +0000320 ++NumIters;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000321 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000322
Chris Lattnercbb56252004-11-18 02:42:27 +0000323 processActiveIntervals(cur->beginNumber());
324 processInactiveIntervals(cur->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000325
Dan Gohman6f0d0242008-02-10 18:45:23 +0000326 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000327 "Can only allocate virtual registers!");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000328
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000329 // Allocating a virtual register. try to find a free
330 // physical register or spill an interval (possibly this one) in order to
331 // assign it one.
332 assignRegOrStackSlotAtInterval(cur);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000333
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000334 DEBUG(printIntervals("active", active_.begin(), active_.end()));
335 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000337
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000338 // expire any remaining active intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000339 while (!active_.empty()) {
340 IntervalPtr &IP = active_.back();
341 unsigned reg = IP.first->reg;
342 DOUT << "\tinterval " << *IP.first << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000343 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000344 "Can only allocate virtual registers!");
345 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000346 prt_->delRegUse(reg);
Evan Cheng11923cc2007-10-16 21:09:14 +0000347 active_.pop_back();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 }
Alkis Evlogimenos7d629b52004-01-07 09:20:58 +0000349
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 // expire any remaining inactive intervals
Evan Cheng11923cc2007-10-16 21:09:14 +0000351 DEBUG(for (IntervalPtrs::reverse_iterator
Bill Wendling87075ca2007-11-15 00:40:48 +0000352 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
Evan Cheng11923cc2007-10-16 21:09:14 +0000353 DOUT << "\tinterval " << *i->first << " expired\n");
354 inactive_.clear();
Alkis Evlogimenosb7be1152004-01-13 20:42:08 +0000355
Evan Cheng81a03822007-11-17 00:40:40 +0000356 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000357 MachineFunction::iterator EntryMBB = mf_->begin();
Evan Chenga5bfc972007-10-17 06:53:44 +0000358 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000359 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
Evan Chengc92da382007-11-03 07:20:12 +0000360 LiveInterval &cur = i->second;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000361 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000362 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
Evan Cheng81a03822007-11-17 00:40:40 +0000363 if (isPhys)
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000364 Reg = i->second.reg;
365 else if (vrm_->isAssignedReg(cur.reg))
Evan Chengc92da382007-11-03 07:20:12 +0000366 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000367 if (!Reg)
368 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000369 // Ignore splited live intervals.
370 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
371 continue;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000372 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
373 I != E; ++I) {
374 const LiveRange &LR = *I;
Evan Cheng3f4b80e2007-10-17 02:12:22 +0000375 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
376 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
377 if (LiveInMBBs[i] != EntryMBB)
378 LiveInMBBs[i]->addLiveIn(Reg);
Evan Chenga5bfc972007-10-17 06:53:44 +0000379 LiveInMBBs.clear();
Evan Cheng9fc508f2007-02-16 09:05:02 +0000380 }
381 }
382 }
383
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000384 DOUT << *vrm_;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000385}
386
Chris Lattnercbb56252004-11-18 02:42:27 +0000387/// processActiveIntervals - expire old intervals and move non-overlapping ones
388/// to the inactive list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000389void RALinScan::processActiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000390{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000391 DOUT << "\tprocessing active intervals:\n";
Chris Lattner23b71c12004-11-18 01:29:39 +0000392
Chris Lattnercbb56252004-11-18 02:42:27 +0000393 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
394 LiveInterval *Interval = active_[i].first;
395 LiveInterval::iterator IntervalPos = active_[i].second;
396 unsigned reg = Interval->reg;
Alkis Evlogimenosed543732004-09-01 22:52:29 +0000397
Chris Lattnercbb56252004-11-18 02:42:27 +0000398 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
399
400 if (IntervalPos == Interval->end()) { // Remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000401 DOUT << "\t\tinterval " << *Interval << " expired\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000402 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000403 "Can only allocate virtual registers!");
404 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000405 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000406
407 // Pop off the end of the list.
408 active_[i] = active_.back();
409 active_.pop_back();
410 --i; --e;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000411
Chris Lattnercbb56252004-11-18 02:42:27 +0000412 } else if (IntervalPos->start > CurPoint) {
413 // Move inactive intervals to inactive list.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000414 DOUT << "\t\tinterval " << *Interval << " inactive\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000415 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000416 "Can only allocate virtual registers!");
417 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000418 prt_->delRegUse(reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000419 // add to inactive.
420 inactive_.push_back(std::make_pair(Interval, IntervalPos));
421
422 // Pop off the end of the list.
423 active_[i] = active_.back();
424 active_.pop_back();
425 --i; --e;
426 } else {
427 // Otherwise, just update the iterator position.
428 active_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000429 }
430 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000431}
432
Chris Lattnercbb56252004-11-18 02:42:27 +0000433/// processInactiveIntervals - expire old intervals and move overlapping
434/// ones to the active list.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000435void RALinScan::processInactiveIntervals(unsigned CurPoint)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000436{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000437 DOUT << "\tprocessing inactive intervals:\n";
Chris Lattner365b95f2004-11-18 04:13:02 +0000438
Chris Lattnercbb56252004-11-18 02:42:27 +0000439 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
440 LiveInterval *Interval = inactive_[i].first;
441 LiveInterval::iterator IntervalPos = inactive_[i].second;
442 unsigned reg = Interval->reg;
Chris Lattner23b71c12004-11-18 01:29:39 +0000443
Chris Lattnercbb56252004-11-18 02:42:27 +0000444 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000445
Chris Lattnercbb56252004-11-18 02:42:27 +0000446 if (IntervalPos == Interval->end()) { // remove expired intervals.
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000447 DOUT << "\t\tinterval " << *Interval << " expired\n";
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000448
Chris Lattnercbb56252004-11-18 02:42:27 +0000449 // Pop off the end of the list.
450 inactive_[i] = inactive_.back();
451 inactive_.pop_back();
452 --i; --e;
453 } else if (IntervalPos->start <= CurPoint) {
454 // move re-activated intervals in active list
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000455 DOUT << "\t\tinterval " << *Interval << " active\n";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000456 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000457 "Can only allocate virtual registers!");
458 reg = vrm_->getPhys(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 prt_->addRegUse(reg);
460 // add to active
Chris Lattnercbb56252004-11-18 02:42:27 +0000461 active_.push_back(std::make_pair(Interval, IntervalPos));
462
463 // Pop off the end of the list.
464 inactive_[i] = inactive_.back();
465 inactive_.pop_back();
466 --i; --e;
467 } else {
468 // Otherwise, just update the iterator position.
469 inactive_[i].second = IntervalPos;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000470 }
471 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000472}
473
Chris Lattnercbb56252004-11-18 02:42:27 +0000474/// updateSpillWeights - updates the spill weights of the specifed physical
475/// register and its weight.
Misha Brukmanedf128a2005-04-21 22:36:52 +0000476static void updateSpillWeights(std::vector<float> &Weights,
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000477 unsigned reg, float weight,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000478 const TargetRegisterInfo *TRI) {
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000479 Weights[reg] += weight;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000480 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000481 Weights[*as] += weight;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000482}
483
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000484static
485RALinScan::IntervalPtrs::iterator
486FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
487 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
488 I != E; ++I)
Chris Lattnercbb56252004-11-18 02:42:27 +0000489 if (I->first == LI) return I;
490 return IP.end();
491}
492
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000493static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
Chris Lattner19828d42004-11-18 03:49:30 +0000494 for (unsigned i = 0, e = V.size(); i != e; ++i) {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000495 RALinScan::IntervalPtr &IP = V[i];
Chris Lattner19828d42004-11-18 03:49:30 +0000496 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
497 IP.second, Point);
498 if (I != IP.first->begin()) --I;
499 IP.second = I;
500 }
501}
Chris Lattnercbb56252004-11-18 02:42:27 +0000502
Chris Lattnercbb56252004-11-18 02:42:27 +0000503/// assignRegOrStackSlotAtInterval - assign a register if one is available, or
504/// spill.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000505void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000506{
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000507 DOUT << "\tallocating current interval: ";
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000508
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 PhysRegTracker backupPrt = *prt_;
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000510
Chris Lattnera6c17502005-08-22 20:20:42 +0000511 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
Chris Lattner365b95f2004-11-18 04:13:02 +0000512 unsigned StartPosition = cur->beginNumber();
Chris Lattner84bc5422007-12-31 04:13:23 +0000513 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000514 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
Evan Chengc92da382007-11-03 07:20:12 +0000515
516 // If this live interval is defined by a move instruction and its source is
517 // assigned a physical register that is compatible with the target register
518 // class, then we should try to assign it the same register.
519 // This can happen when the move is from a larger register class to a smaller
520 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
521 if (!cur->preference && cur->containsOneValue()) {
522 VNInfo *vni = cur->getValNumInfo(0);
523 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
524 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
525 unsigned SrcReg, DstReg;
526 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
527 unsigned Reg = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000528 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
Evan Chengc92da382007-11-03 07:20:12 +0000529 Reg = SrcReg;
530 else if (vrm_->isAssignedReg(SrcReg))
531 Reg = vrm_->getPhys(SrcReg);
532 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
533 cur->preference = Reg;
534 }
535 }
536 }
537
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000538 // for every interval in inactive we overlap with, mark the
Chris Lattnera6c17502005-08-22 20:20:42 +0000539 // register as not free and update spill weights.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 for (IntervalPtrs::const_iterator i = inactive_.begin(),
541 e = inactive_.end(); i != e; ++i) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000542 unsigned Reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000543 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
Chris Lattnerb9805782005-08-23 22:27:31 +0000544 "Can only allocate virtual registers!");
Chris Lattner84bc5422007-12-31 04:13:23 +0000545 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000546 // If this is not in a related reg class to the register we're allocating,
547 // don't check it.
548 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
549 cur->overlapsFrom(*i->first, i->second-1)) {
550 Reg = vrm_->getPhys(Reg);
551 prt_->addRegUse(Reg);
552 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000553 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000555
556 // Speculatively check to see if we can get a register right now. If not,
557 // we know we won't be able to by adding more constraints. If so, we can
558 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
559 // is very bad (it contains all callee clobbered registers for any functions
560 // with a call), so we want to avoid doing that if possible.
561 unsigned physReg = getFreePhysReg(cur);
562 if (physReg) {
563 // We got a register. However, if it's in the fixed_ list, we might
Chris Lattnere836ad62005-08-30 21:03:36 +0000564 // conflict with it. Check to see if we conflict with it or any of its
565 // aliases.
Evan Chengc92da382007-11-03 07:20:12 +0000566 SmallSet<unsigned, 8> RegAliases;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000567 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
Chris Lattnere836ad62005-08-30 21:03:36 +0000568 RegAliases.insert(*AS);
569
Chris Lattnera411cbc2005-08-22 20:59:30 +0000570 bool ConflictsWithFixed = false;
571 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
Jim Laskeye719d9f2006-10-24 14:35:25 +0000572 IntervalPtr &IP = fixed_[i];
573 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000574 // Okay, this reg is on the fixed list. Check to see if we actually
575 // conflict.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000576 LiveInterval *I = IP.first;
577 if (I->endNumber() > StartPosition) {
578 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
579 IP.second = II;
580 if (II != I->begin() && II->start > StartPosition)
581 --II;
Chris Lattnere836ad62005-08-30 21:03:36 +0000582 if (cur->overlapsFrom(*I, II)) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000583 ConflictsWithFixed = true;
Chris Lattnere836ad62005-08-30 21:03:36 +0000584 break;
585 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000586 }
Chris Lattnerf348e3a2004-11-18 04:33:31 +0000587 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000588 }
Chris Lattnera411cbc2005-08-22 20:59:30 +0000589
590 // Okay, the register picked by our speculative getFreePhysReg call turned
591 // out to be in use. Actually add all of the conflicting fixed registers to
592 // prt so we can do an accurate query.
593 if (ConflictsWithFixed) {
Chris Lattnerb9805782005-08-23 22:27:31 +0000594 // For every interval in fixed we overlap with, mark the register as not
595 // free and update spill weights.
Chris Lattnera411cbc2005-08-22 20:59:30 +0000596 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
597 IntervalPtr &IP = fixed_[i];
598 LiveInterval *I = IP.first;
Chris Lattnerb9805782005-08-23 22:27:31 +0000599
600 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
601 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
602 I->endNumber() > StartPosition) {
Chris Lattnera411cbc2005-08-22 20:59:30 +0000603 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
604 IP.second = II;
605 if (II != I->begin() && II->start > StartPosition)
606 --II;
607 if (cur->overlapsFrom(*I, II)) {
608 unsigned reg = I->reg;
609 prt_->addRegUse(reg);
610 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
611 }
612 }
613 }
Alkis Evlogimenos169cfd02003-12-21 05:43:40 +0000614
Chris Lattnera411cbc2005-08-22 20:59:30 +0000615 // Using the newly updated prt_ object, which includes conflicts in the
616 // future, see if there are any registers available.
617 physReg = getFreePhysReg(cur);
618 }
619 }
620
Chris Lattnera6c17502005-08-22 20:20:42 +0000621 // Restore the physical register tracker, removing information about the
622 // future.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000623 *prt_ = backupPrt;
Chris Lattnera6c17502005-08-22 20:20:42 +0000624
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000625 // if we find a free register, we are done: assign this virtual to
626 // the free physical register and add this interval to the active
627 // list.
628 if (physReg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000629 DOUT << tri_->getName(physReg) << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000630 vrm_->assignVirt2Phys(cur->reg, physReg);
631 prt_->addRegUse(physReg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000632 active_.push_back(std::make_pair(cur, cur->begin()));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000633 handled_.push_back(cur);
634 return;
635 }
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000636 DOUT << "no free registers\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000637
Chris Lattnera6c17502005-08-22 20:20:42 +0000638 // Compile the spill weights into an array that is better for scanning.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000639 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0);
Chris Lattnera6c17502005-08-22 20:20:42 +0000640 for (std::vector<std::pair<unsigned, float> >::iterator
641 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
Dan Gohman6f0d0242008-02-10 18:45:23 +0000642 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000643
644 // for each interval in active, update spill weights.
645 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
646 i != e; ++i) {
647 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000648 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnera6c17502005-08-22 20:20:42 +0000649 "Can only allocate virtual registers!");
650 reg = vrm_->getPhys(reg);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000651 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
Chris Lattnera6c17502005-08-22 20:20:42 +0000652 }
653
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000654 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000655
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000656 // Find a register to spill.
Jim Laskey7902c752006-11-07 12:25:45 +0000657 float minWeight = HUGE_VALF;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000658 unsigned minReg = cur->preference; // Try the preferred register first.
659
660 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
661 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
662 e = RC->allocation_order_end(*mf_); i != e; ++i) {
663 unsigned reg = *i;
664 if (minWeight > SpillWeights[reg]) {
665 minWeight = SpillWeights[reg];
666 minReg = reg;
667 }
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000668 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000669
670 // If we didn't find a register that is spillable, try aliases?
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000671 if (!minReg) {
672 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
673 e = RC->allocation_order_end(*mf_); i != e; ++i) {
674 unsigned reg = *i;
675 // No need to worry about if the alias register size < regsize of RC.
676 // We are going to spill all registers that alias it anyway.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000677 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
Evan Cheng3b6d56c2006-05-12 19:07:46 +0000678 if (minWeight > SpillWeights[*as]) {
679 minWeight = SpillWeights[*as];
680 minReg = *as;
681 }
682 }
683 }
684
685 // All registers must have inf weight. Just grab one!
686 if (!minReg)
687 minReg = *RC->allocation_order_begin(*mf_);
688 }
Chris Lattnerc8e2c552006-03-25 23:00:56 +0000689
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000690 DOUT << "\t\tregister with min weight: "
Dan Gohman6f0d0242008-02-10 18:45:23 +0000691 << tri_->getName(minReg) << " (" << minWeight << ")\n";
Alkis Evlogimenos3bf564a2003-12-23 18:00:33 +0000692
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000693 // if the current has the minimum weight, we need to spill it and
694 // add any added intervals back to unhandled, and restart
695 // linearscan.
Jim Laskey7902c752006-11-07 12:25:45 +0000696 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000697 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000698 std::vector<LiveInterval*> added =
Evan Cheng81a03822007-11-17 00:40:40 +0000699 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000700 if (added.empty())
701 return; // Early exit if all spills were folded.
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000702
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000703 // Merge added with unhandled. Note that we know that
704 // addIntervalsForSpills returns intervals sorted by their starting
705 // point.
Alkis Evlogimenos53eb3732004-07-22 08:14:44 +0000706 for (unsigned i = 0, e = added.size(); i != e; ++i)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000707 unhandled_.push(added[i]);
708 return;
709 }
710
Chris Lattner19828d42004-11-18 03:49:30 +0000711 ++NumBacktracks;
712
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000713 // push the current interval back to unhandled since we are going
714 // to re-run at least this iteration. Since we didn't modify it it
715 // should go back right in the front of the list
716 unhandled_.push(cur);
717
718 // otherwise we spill all intervals aliasing the register with
719 // minimum weight, rollback to the interval with the earliest
720 // start point and let the linear scan algorithm run again
721 std::vector<LiveInterval*> added;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000722 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000723 "did not choose a register to spill?");
Dan Gohman6f0d0242008-02-10 18:45:23 +0000724 BitVector toSpill(tri_->getNumRegs());
Chris Lattner19828d42004-11-18 03:49:30 +0000725
726 // We are going to spill minReg and all its aliases.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000727 toSpill[minReg] = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000728 for (const unsigned* as = tri_->getAliasSet(minReg); *as; ++as)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000729 toSpill[*as] = true;
730
731 // the earliest start of a spilled interval indicates up to where
732 // in handled we need to roll back
Chris Lattner23b71c12004-11-18 01:29:39 +0000733 unsigned earliestStart = cur->beginNumber();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000734
735 // set of spilled vregs (used later to rollback properly)
Evan Chengc92da382007-11-03 07:20:12 +0000736 SmallSet<unsigned, 32> spilled;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000737
Chris Lattner19828d42004-11-18 03:49:30 +0000738 // spill live intervals of virtual regs mapped to the physical register we
739 // want to clear (and its aliases). We only spill those that overlap with the
740 // current interval as the rest do not affect its allocation. we also keep
741 // track of the earliest start of all spilled live intervals since this will
742 // mark our rollback point.
743 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000744 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000745 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000746 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000747 cur->overlapsFrom(*i->first, i->second)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000748 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000749 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000750 std::vector<LiveInterval*> newIs =
Evan Cheng81a03822007-11-17 00:40:40 +0000751 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000752 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
753 spilled.insert(reg);
754 }
755 }
Chris Lattner19828d42004-11-18 03:49:30 +0000756 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
Chris Lattnercbb56252004-11-18 02:42:27 +0000757 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000758 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000759 toSpill[vrm_->getPhys(reg)] &&
Chris Lattner19828d42004-11-18 03:49:30 +0000760 cur->overlapsFrom(*i->first, i->second-1)) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000761 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000762 earliestStart = std::min(earliestStart, i->first->beginNumber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000763 std::vector<LiveInterval*> newIs =
Evan Cheng81a03822007-11-17 00:40:40 +0000764 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000765 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
766 spilled.insert(reg);
767 }
768 }
769
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000770 DOUT << "\t\trolling back to: " << earliestStart << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000771
772 // Scan handled in reverse order up to the earliest start of a
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000773 // spilled live interval and undo each one, restoring the state of
Chris Lattnercbb56252004-11-18 02:42:27 +0000774 // unhandled.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000775 while (!handled_.empty()) {
776 LiveInterval* i = handled_.back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000777 // If this interval starts before t we are done.
Chris Lattner23b71c12004-11-18 01:29:39 +0000778 if (i->beginNumber() < earliestStart)
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000779 break;
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000780 DOUT << "\t\t\tundo changes for: " << *i << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000781 handled_.pop_back();
Chris Lattnercbb56252004-11-18 02:42:27 +0000782
783 // When undoing a live interval allocation we must know if it is active or
784 // inactive to properly update the PhysRegTracker and the VirtRegMap.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000785 IntervalPtrs::iterator it;
Chris Lattnercbb56252004-11-18 02:42:27 +0000786 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000787 active_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000788 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000789 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000790 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000791 prt_->delRegUse(vrm_->getPhys(i->reg));
792 vrm_->clearVirt(i->reg);
Chris Lattnercbb56252004-11-18 02:42:27 +0000793 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000794 inactive_.erase(it);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000795 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000796 if (!spilled.count(i->reg))
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000797 unhandled_.push(i);
Chris Lattnerffab4222006-02-23 06:44:17 +0000798 vrm_->clearVirt(i->reg);
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000799 } else {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000800 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000801 "Can only allocate virtual registers!");
802 vrm_->clearVirt(i->reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000803 unhandled_.push(i);
804 }
Evan Cheng9aeaf752007-11-04 08:32:21 +0000805
806 // It interval has a preference, it must be defined by a copy. Clear the
807 // preference now since the source interval allocation may have been undone
808 // as well.
809 i->preference = 0;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000810 }
811
Chris Lattner19828d42004-11-18 03:49:30 +0000812 // Rewind the iterators in the active, inactive, and fixed lists back to the
813 // point we reverted to.
814 RevertVectorIteratorsTo(active_, earliestStart);
815 RevertVectorIteratorsTo(inactive_, earliestStart);
816 RevertVectorIteratorsTo(fixed_, earliestStart);
817
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000818 // scan the rest and undo each interval that expired after t and
819 // insert it in active (the next iteration of the algorithm will
820 // put it in inactive if required)
Chris Lattnercbb56252004-11-18 02:42:27 +0000821 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
822 LiveInterval *HI = handled_[i];
823 if (!HI->expiredAt(earliestStart) &&
824 HI->expiredAt(cur->beginNumber())) {
Bill Wendling54fcc7f2006-11-17 00:50:36 +0000825 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
Chris Lattnercbb56252004-11-18 02:42:27 +0000826 active_.push_back(std::make_pair(HI, HI->begin()));
Dan Gohman6f0d0242008-02-10 18:45:23 +0000827 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
Chris Lattnerffab4222006-02-23 06:44:17 +0000828 prt_->addRegUse(vrm_->getPhys(HI->reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000829 }
830 }
831
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000832 // merge added with unhandled
833 for (unsigned i = 0, e = added.size(); i != e; ++i)
834 unhandled_.push(added[i]);
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000835}
Alkis Evlogimenosf5eaf162004-02-06 18:08:18 +0000836
Chris Lattnercbb56252004-11-18 02:42:27 +0000837/// getFreePhysReg - return a free physical register for this virtual register
838/// interval if we have one, otherwise return 0.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000839unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000840 std::vector<unsigned> inactiveCounts(tri_->getNumRegs(), 0);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000841 unsigned MaxInactiveCount = 0;
842
Chris Lattner84bc5422007-12-31 04:13:23 +0000843 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000844 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
845
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000846 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
847 i != e; ++i) {
Chris Lattnercbb56252004-11-18 02:42:27 +0000848 unsigned reg = i->first->reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000849 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
Chris Lattnerc8b9f332004-11-18 06:01:45 +0000850 "Can only allocate virtual registers!");
Chris Lattnerb9805782005-08-23 22:27:31 +0000851
852 // If this is not in a related reg class to the register we're allocating,
853 // don't check it.
Chris Lattner84bc5422007-12-31 04:13:23 +0000854 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
Chris Lattnerb9805782005-08-23 22:27:31 +0000855 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
856 reg = vrm_->getPhys(reg);
857 ++inactiveCounts[reg];
858 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
859 }
Alkis Evlogimenos84f5bcb2004-09-02 21:23:32 +0000860 }
861
Chris Lattnerf8355d92005-08-22 16:55:22 +0000862 unsigned FreeReg = 0;
863 unsigned FreeRegInactiveCount = 0;
Evan Cheng20b0abc2007-04-17 20:32:26 +0000864
865 // If copy coalescer has assigned a "preferred" register, check if it's
866 // available first.
867 if (cur->preference)
868 if (prt_->isRegAvail(cur->preference)) {
869 DOUT << "\t\tassigned the preferred register: "
Dan Gohman6f0d0242008-02-10 18:45:23 +0000870 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +0000871 return cur->preference;
872 } else
873 DOUT << "\t\tunable to assign the preferred register: "
Dan Gohman6f0d0242008-02-10 18:45:23 +0000874 << tri_->getName(cur->preference) << "\n";
Evan Cheng20b0abc2007-04-17 20:32:26 +0000875
Chris Lattnerf8355d92005-08-22 16:55:22 +0000876 // Scan for the first available register.
Evan Cheng92efbfc2007-04-25 07:18:20 +0000877 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
878 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
Chris Lattnerf8355d92005-08-22 16:55:22 +0000879 for (; I != E; ++I)
880 if (prt_->isRegAvail(*I)) {
881 FreeReg = *I;
882 FreeRegInactiveCount = inactiveCounts[FreeReg];
883 break;
884 }
885
886 // If there are no free regs, or if this reg has the max inactive count,
887 // return this register.
888 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
889
890 // Continue scanning the registers, looking for the one with the highest
891 // inactive count. Alkis found that this reduced register pressure very
892 // slightly on X86 (in rev 1.94 of this file), though this should probably be
893 // reevaluated now.
894 for (; I != E; ++I) {
895 unsigned Reg = *I;
896 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
897 FreeReg = Reg;
898 FreeRegInactiveCount = inactiveCounts[Reg];
899 if (FreeRegInactiveCount == MaxInactiveCount)
900 break; // We found the one with the max inactive count.
901 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000902 }
Chris Lattnerf8355d92005-08-22 16:55:22 +0000903
904 return FreeReg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000905}
906
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000907FunctionPass* llvm::createLinearScanRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000908 return new RALinScan();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000909}