blob: 569a61689a24468553401e6f651cda91780dc572 [file] [log] [blame]
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001//===- subzero/src/IceRegAlloc.cpp - Linear-scan implementation -----------===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LinearScan class, which performs the
11// linear-scan register allocation after liveness analysis has been
12// performed.
13//
14//===----------------------------------------------------------------------===//
15
16#include "IceCfg.h"
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080017#include "IceCfgNode.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070018#include "IceInst.h"
19#include "IceOperand.h"
20#include "IceRegAlloc.h"
21#include "IceTargetLowering.h"
22
23namespace Ice {
24
Jim Stichnothad403532014-09-25 12:44:17 -070025namespace {
26
27// Returns true if Var has any definitions within Item's live range.
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070028// TODO(stichnot): Consider trimming the Definitions list similar to
29// how the live ranges are trimmed, since all the overlapsDefs() tests
30// are whether some variable's definitions overlap Cur, and trimming
31// is with respect Cur.start. Initial tests show no measurable
32// performance difference, so we'll keep the code simple for now.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070033bool overlapsDefs(const Cfg *Func, const Variable *Item, const Variable *Var) {
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070034 const bool UseTrimmed = true;
35 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnoth877b04e2014-10-15 15:13:06 -070036 if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var))
37 if (Item->getLiveRange().overlapsInst(FirstDef->getNumber(), UseTrimmed))
38 return true;
39 const InstDefList &Defs = VMetadata->getLatterDefinitions(Var);
Jim Stichnothad403532014-09-25 12:44:17 -070040 for (size_t i = 0; i < Defs.size(); ++i) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070041 if (Item->getLiveRange().overlapsInst(Defs[i]->getNumber(), UseTrimmed))
Jim Stichnothad403532014-09-25 12:44:17 -070042 return true;
43 }
44 return false;
45}
46
47void dumpDisableOverlap(const Cfg *Func, const Variable *Var,
48 const char *Reason) {
49 if (Func->getContext()->isVerbose(IceV_LinearScan)) {
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070050 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnothad403532014-09-25 12:44:17 -070051 Ostream &Str = Func->getContext()->getStrDump();
52 Str << "Disabling Overlap due to " << Reason << " " << *Var
53 << " LIVE=" << Var->getLiveRange() << " Defs=";
Jim Stichnoth877b04e2014-10-15 15:13:06 -070054 if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var))
55 Str << FirstDef->getNumber();
56 const InstDefList &Defs = VMetadata->getLatterDefinitions(Var);
Jim Stichnothad403532014-09-25 12:44:17 -070057 for (size_t i = 0; i < Defs.size(); ++i) {
Jim Stichnoth877b04e2014-10-15 15:13:06 -070058 Str << "," << Defs[i]->getNumber();
Jim Stichnothad403532014-09-25 12:44:17 -070059 }
60 Str << "\n";
61 }
62}
63
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070064void dumpLiveRange(const Variable *Var, const Cfg *Func) {
65 Ostream &Str = Func->getContext()->getStrDump();
66 const static size_t BufLen = 30;
67 char buf[BufLen];
68 snprintf(buf, BufLen, "%2d", Var->getRegNumTmp());
69 Str << "R=" << buf << " V=";
70 Var->dump(Func);
71 Str << " Range=" << Var->getLiveRange();
Jim Stichnothe22f8232014-10-13 16:20:59 -070072}
73
Jim Stichnothad403532014-09-25 12:44:17 -070074} // end of anonymous namespace
75
Jim Stichnoth70d0a052014-11-14 15:53:46 -080076// Prepare for full register allocation of all variables. We depend
77// on liveness analysis to have calculated live ranges.
78void LinearScan::initForGlobal() {
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080079 TimerMarker T(TimerStack::TT_initUnhandled, Func);
Jim Stichnoth70d0a052014-11-14 15:53:46 -080080 FindPreference = true;
81 FindOverlap = true;
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080082 const VarList &Vars = Func->getVariables();
83 Unhandled.reserve(Vars.size());
Jim Stichnoth70d0a052014-11-14 15:53:46 -080084 // Gather the live ranges of all variables and add them to the
85 // Unhandled set.
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080086 for (Variable *Var : Vars) {
87 // Explicitly don't consider zero-weight variables, which are
88 // meant to be spill slots.
89 if (Var->getWeight() == RegWeight::Zero)
90 continue;
91 // Don't bother if the variable has a null live range, which means
92 // it was never referenced.
93 if (Var->getLiveRange().isEmpty())
94 continue;
95 Var->untrimLiveRange();
96 Unhandled.push_back(Var);
97 if (Var->hasReg()) {
98 Var->setRegNumTmp(Var->getRegNum());
99 Var->setLiveRangeInfiniteWeight();
100 UnhandledPrecolored.push_back(Var);
101 }
102 }
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800103
104 // Build the (ordered) list of FakeKill instruction numbers.
105 Kills.clear();
106 for (CfgNode *Node : Func->getNodes()) {
107 for (auto I = Node->getInsts().begin(), E = Node->getInsts().end(); I != E;
108 ++I) {
109 if (auto Kill = llvm::dyn_cast<InstFakeKill>(I)) {
110 if (!Kill->isDeleted() && !Kill->getLinked()->isDeleted())
111 Kills.push_back(I->getNumber());
112 }
113 }
114 }
115}
116
117// Prepare for very simple register allocation of only infinite-weight
118// Variables while respecting pre-colored Variables. Some properties
119// we take advantage of:
120//
121// * Live ranges of interest consist of a single segment.
122//
123// * Live ranges of interest never span a call instruction.
124//
125// * Phi instructions are not considered because either phis have
126// already been lowered, or they don't contain any pre-colored or
127// infinite-weight Variables.
128//
129// * We don't need to renumber instructions before computing live
130// ranges because all the high-level ICE instructions are deleted
131// prior to lowering, and the low-level instructions are added in
132// monotonically increasing order.
133//
134// * There are no opportunities for register preference or allowing
135// overlap.
136//
137// Some properties we aren't (yet) taking advantage of:
138//
139// * Because live ranges are a single segment, the Unhandled set will
140// always be empty, and the live range trimming operation is
141// unnecessary.
142//
143// * Calculating overlap of single-segment live ranges could be
144// optimized a bit.
145void LinearScan::initForInfOnly() {
146 TimerMarker T(TimerStack::TT_initUnhandled, Func);
147 FindPreference = false;
148 FindOverlap = false;
149 SizeT NumVars = 0;
150 const VarList &Vars = Func->getVariables();
151
152 // Iterate across all instructions and record the begin and end of
153 // the live range for each variable that is pre-colored or infinite
154 // weight.
155 std::vector<InstNumberT> LRBegin(Vars.size(), Inst::NumberSentinel);
156 std::vector<InstNumberT> LREnd(Vars.size(), Inst::NumberSentinel);
157 for (CfgNode *Node : Func->getNodes()) {
158 for (auto Inst = Node->getInsts().begin(), E = Node->getInsts().end();
159 Inst != E; ++Inst) {
160 if (Inst->isDeleted())
161 continue;
162 if (const Variable *Var = Inst->getDest()) {
163 if (Var->hasReg() || Var->getWeight() == RegWeight::Inf) {
164 if (LRBegin[Var->getIndex()] == Inst::NumberSentinel) {
165 LRBegin[Var->getIndex()] = Inst->getNumber();
166 ++NumVars;
167 }
168 }
169 }
170 for (SizeT I = 0; I < Inst->getSrcSize(); ++I) {
171 Operand *Src = Inst->getSrc(I);
172 SizeT NumVars = Src->getNumVars();
173 for (SizeT J = 0; J < NumVars; ++J) {
174 const Variable *Var = Src->getVar(J);
175 if (Var->hasReg() || Var->getWeight() == RegWeight::Inf)
176 LREnd[Var->getIndex()] = Inst->getNumber();
177 }
178 }
179 }
180 }
181
182 Unhandled.reserve(NumVars);
183 for (SizeT i = 0; i < Vars.size(); ++i) {
184 Variable *Var = Vars[i];
185 if (LRBegin[i] != Inst::NumberSentinel) {
186 assert(LREnd[i] != Inst::NumberSentinel);
187 Unhandled.push_back(Var);
188 Var->resetLiveRange();
189 const uint32_t WeightDelta = 1;
190 Var->addLiveRange(LRBegin[i], LREnd[i], WeightDelta);
191 Var->untrimLiveRange();
192 if (Var->hasReg()) {
193 Var->setRegNumTmp(Var->getRegNum());
194 Var->setLiveRangeInfiniteWeight();
195 UnhandledPrecolored.push_back(Var);
196 }
197 --NumVars;
198 }
199 }
200 // This isn't actually a fatal condition, but it would be nice to
201 // know if we somehow pre-calculated Unhandled's size wrong.
202 assert(NumVars == 0);
203
204 // Don't build up the list of Kills because we know that no
205 // infinite-weight Variable has a live range spanning a call.
206 Kills.clear();
207}
208
209void LinearScan::init(RegAllocKind Kind) {
210 Unhandled.clear();
211 UnhandledPrecolored.clear();
212 Handled.clear();
213 Inactive.clear();
214 Active.clear();
215
216 switch (Kind) {
217 case RAK_Global:
218 initForGlobal();
219 break;
220 case RAK_InfOnly:
221 initForInfOnly();
222 break;
223 }
224
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800225 struct CompareRanges {
226 bool operator()(const Variable *L, const Variable *R) {
227 InstNumberT Lstart = L->getLiveRange().getStart();
228 InstNumberT Rstart = R->getLiveRange().getStart();
229 if (Lstart == Rstart)
230 return L->getIndex() < R->getIndex();
231 return Lstart < Rstart;
232 }
233 };
234 // Do a reverse sort so that erasing elements (from the end) is fast.
235 std::sort(Unhandled.rbegin(), Unhandled.rend(), CompareRanges());
236 std::sort(UnhandledPrecolored.rbegin(), UnhandledPrecolored.rend(),
237 CompareRanges());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800238}
239
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700240// Implements the linear-scan algorithm. Based on "Linear Scan
241// Register Allocation in the Context of SSA Form and Register
242// Constraints" by Hanspeter Mössenböck and Michael Pfeiffer,
243// ftp://ftp.ssw.uni-linz.ac.at/pub/Papers/Moe02.PDF . This
244// implementation is modified to take affinity into account and allow
245// two interfering variables to share the same register in certain
246// cases.
247//
Jim Stichnoth800dab22014-09-20 12:25:02 -0700248// Requires running Cfg::liveness(Liveness_Intervals) in
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700249// preparation. Results are assigned to Variable::RegNum for each
250// Variable.
251void LinearScan::scan(const llvm::SmallBitVector &RegMaskFull) {
Jim Stichnoth8363a062014-10-07 10:02:38 -0700252 TimerMarker T(TimerStack::TT_linearScan, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700253 assert(RegMaskFull.any()); // Sanity check
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700254 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnothc4554d72014-09-30 16:49:38 -0700255 bool Verbose = Func->getContext()->isVerbose(IceV_LinearScan);
Jim Stichnoth800dab22014-09-20 12:25:02 -0700256 Func->resetCurrentNode();
Jim Stichnothad403532014-09-25 12:44:17 -0700257 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700258
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800259 // Build a LiveRange representing the Kills list.
260 LiveRange KillsRange;
261 for (InstNumberT I : Kills)
262 KillsRange.addSegment(I, I);
263 KillsRange.untrim();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700264
265 // RegUses[I] is the number of live ranges (variables) that register
266 // I is currently assigned to. It can be greater than 1 as a result
Jim Stichnothc4554d72014-09-30 16:49:38 -0700267 // of AllowOverlap inference below.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700268 std::vector<int> RegUses(RegMaskFull.size());
269 // Unhandled is already set to all ranges in increasing order of
270 // start points.
271 assert(Active.empty());
272 assert(Inactive.empty());
273 assert(Handled.empty());
274 UnorderedRanges::iterator Next;
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800275 const TargetLowering::RegSetMask RegsInclude =
276 TargetLowering::RegSet_CallerSave;
277 const TargetLowering::RegSetMask RegsExclude = TargetLowering::RegSet_None;
278 const llvm::SmallBitVector KillsMask =
279 Func->getTarget()->getRegisterSet(RegsInclude, RegsExclude);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700280
281 while (!Unhandled.empty()) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700282 Variable *Cur = Unhandled.back();
Jim Stichnothe22f8232014-10-13 16:20:59 -0700283 Unhandled.pop_back();
Jim Stichnothc4554d72014-09-30 16:49:38 -0700284 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700285 Str << "\nConsidering ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700286 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700287 Str << "\n";
288 }
289 const llvm::SmallBitVector RegMask =
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700290 RegMaskFull & Func->getTarget()->getRegisterSetForType(Cur->getType());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800291 KillsRange.trim(Cur->getLiveRange().getStart());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700292
293 // Check for precolored ranges. If Cur is precolored, it
294 // definitely gets that register. Previously processed live
295 // ranges would have avoided that register due to it being
296 // precolored. Future processed live ranges won't evict that
297 // register because the live range has infinite weight.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700298 if (Cur->hasReg()) {
299 int32_t RegNum = Cur->getRegNum();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700300 // RegNumTmp should have already been set above.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700301 assert(Cur->getRegNumTmp() == RegNum);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700302 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700303 Str << "Precoloring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700304 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700305 Str << "\n";
306 }
307 Active.push_back(Cur);
308 assert(RegUses[RegNum] >= 0);
309 ++RegUses[RegNum];
Jim Stichnoth541ba662014-10-02 12:58:21 -0700310 assert(!UnhandledPrecolored.empty());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700311 assert(UnhandledPrecolored.back() == Cur);
Jim Stichnothe22f8232014-10-13 16:20:59 -0700312 UnhandledPrecolored.pop_back();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700313 continue;
314 }
315
316 // Check for active ranges that have expired or become inactive.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700317 for (auto I = Active.begin(), E = Active.end(); I != E; I = Next) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700318 Next = I;
319 ++Next;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700320 Variable *Item = *I;
321 Item->trimLiveRange(Cur->getLiveRange().getStart());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700322 bool Moved = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700323 if (Item->rangeEndsBefore(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700324 // Move Item from Active to Handled list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700325 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700326 Str << "Expiring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700327 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700328 Str << "\n";
329 }
Jim Stichnothe22f8232014-10-13 16:20:59 -0700330 Handled.splice(Handled.end(), Active, I);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700331 Moved = true;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700332 } else if (!Item->rangeOverlapsStart(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700333 // Move Item from Active to Inactive list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700334 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700335 Str << "Inactivating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700336 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700337 Str << "\n";
338 }
Jim Stichnothe22f8232014-10-13 16:20:59 -0700339 Inactive.splice(Inactive.end(), Active, I);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700340 Moved = true;
341 }
342 if (Moved) {
343 // Decrement Item from RegUses[].
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700344 assert(Item->hasRegTmp());
345 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700346 --RegUses[RegNum];
347 assert(RegUses[RegNum] >= 0);
348 }
349 }
350
351 // Check for inactive ranges that have expired or reactivated.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700352 for (auto I = Inactive.begin(), E = Inactive.end(); I != E; I = Next) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700353 Next = I;
354 ++Next;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700355 Variable *Item = *I;
356 Item->trimLiveRange(Cur->getLiveRange().getStart());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700357 if (Item->rangeEndsBefore(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700358 // Move Item from Inactive to Handled list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700359 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700360 Str << "Expiring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700361 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700362 Str << "\n";
363 }
Jim Stichnothe22f8232014-10-13 16:20:59 -0700364 Handled.splice(Handled.end(), Inactive, I);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700365 } else if (Item->rangeOverlapsStart(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700366 // Move Item from Inactive to Active list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700367 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700368 Str << "Reactivating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700369 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700370 Str << "\n";
371 }
Jim Stichnothe22f8232014-10-13 16:20:59 -0700372 Active.splice(Active.end(), Inactive, I);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700373 // Increment Item in RegUses[].
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700374 assert(Item->hasRegTmp());
375 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700376 assert(RegUses[RegNum] >= 0);
377 ++RegUses[RegNum];
378 }
379 }
380
381 // Calculate available registers into Free[].
382 llvm::SmallBitVector Free = RegMask;
383 for (SizeT i = 0; i < RegMask.size(); ++i) {
384 if (RegUses[i] > 0)
385 Free[i] = false;
386 }
387
Jim Stichnothad403532014-09-25 12:44:17 -0700388 // Infer register preference and allowable overlap. Only form a
389 // preference when the current Variable has an unambiguous "first"
390 // definition. The preference is some source Variable of the
391 // defining instruction that either is assigned a register that is
392 // currently free, or that is assigned a register that is not free
393 // but overlap is allowed. Overlap is allowed when the Variable
394 // under consideration is single-definition, and its definition is
395 // a simple assignment - i.e., the register gets copied/aliased
396 // but is never modified. Furthermore, overlap is only allowed
397 // when preferred Variable definition instructions do not appear
398 // within the current Variable's live range.
399 Variable *Prefer = NULL;
400 int32_t PreferReg = Variable::NoRegister;
401 bool AllowOverlap = false;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800402 if (FindPreference) {
403 if (const Inst *DefInst = VMetadata->getFirstDefinition(Cur)) {
404 assert(DefInst->getDest() == Cur);
405 bool IsAssign = DefInst->isSimpleAssign();
406 bool IsSingleDef = !VMetadata->isMultiDef(Cur);
407 for (SizeT i = 0; i < DefInst->getSrcSize(); ++i) {
408 // TODO(stichnot): Iterate through the actual Variables of the
409 // instruction, not just the source operands. This could
410 // capture Load instructions, including address mode
411 // optimization, for Prefer (but not for AllowOverlap).
412 if (Variable *SrcVar = llvm::dyn_cast<Variable>(DefInst->getSrc(i))) {
413 int32_t SrcReg = SrcVar->getRegNumTmp();
414 // Only consider source variables that have (so far) been
415 // assigned a register. That register must be one in the
416 // RegMask set, e.g. don't try to prefer the stack pointer
417 // as a result of the stacksave intrinsic.
418 if (SrcVar->hasRegTmp() && RegMask[SrcReg]) {
419 if (FindOverlap && !Free[SrcReg]) {
420 // Don't bother trying to enable AllowOverlap if the
421 // register is already free.
422 AllowOverlap =
423 IsSingleDef && IsAssign && !overlapsDefs(Func, Cur, SrcVar);
424 }
425 if (AllowOverlap || Free[SrcReg]) {
426 Prefer = SrcVar;
427 PreferReg = SrcReg;
428 }
Jim Stichnothad403532014-09-25 12:44:17 -0700429 }
430 }
431 }
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800432 if (Verbose && Prefer) {
433 Str << "Initial Prefer=" << *Prefer << " R=" << PreferReg
434 << " LIVE=" << Prefer->getLiveRange()
435 << " Overlap=" << AllowOverlap << "\n";
436 }
Jim Stichnothad403532014-09-25 12:44:17 -0700437 }
438 }
439
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700440 // Remove registers from the Free[] list where an Inactive range
441 // overlaps with the current range.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700442 for (const Variable *Item : Inactive) {
443 if (Item->rangeOverlaps(Cur)) {
444 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700445 // Don't assert(Free[RegNum]) because in theory (though
446 // probably never in practice) there could be two inactive
Jim Stichnothc4554d72014-09-30 16:49:38 -0700447 // variables that were marked with AllowOverlap.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700448 Free[RegNum] = false;
Jim Stichnothad403532014-09-25 12:44:17 -0700449 // Disable AllowOverlap if an Inactive variable, which is not
450 // Prefer, shares Prefer's register, and has a definition
451 // within Cur's live range.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700452 if (AllowOverlap && Item != Prefer && RegNum == PreferReg &&
453 overlapsDefs(Func, Cur, Item)) {
Jim Stichnothad403532014-09-25 12:44:17 -0700454 AllowOverlap = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700455 dumpDisableOverlap(Func, Item, "Inactive");
Jim Stichnothad403532014-09-25 12:44:17 -0700456 }
457 }
458 }
459
460 // Disable AllowOverlap if an Active variable, which is not
461 // Prefer, shares Prefer's register, and has a definition within
462 // Cur's live range.
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800463 if (AllowOverlap) {
464 for (const Variable *Item : Active) {
465 int32_t RegNum = Item->getRegNumTmp();
466 if (Item != Prefer && RegNum == PreferReg &&
467 overlapsDefs(Func, Cur, Item)) {
468 AllowOverlap = false;
469 dumpDisableOverlap(Func, Item, "Active");
470 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700471 }
472 }
473
Jim Stichnoth541ba662014-10-02 12:58:21 -0700474 std::vector<RegWeight> Weights(RegMask.size());
475
476 // Remove registers from the Free[] list where an Unhandled
477 // precolored range overlaps with the current range, and set those
478 // registers to infinite weight so that they aren't candidates for
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700479 // eviction. Cur->rangeEndsBefore(Item) is an early exit check
480 // that turns a guaranteed O(N^2) algorithm into expected linear
Jim Stichnoth541ba662014-10-02 12:58:21 -0700481 // complexity.
482 llvm::SmallBitVector PrecoloredUnhandledMask(RegMask.size());
483 // Note: PrecoloredUnhandledMask is only used for dumping.
Jim Stichnothe22f8232014-10-13 16:20:59 -0700484 for (auto I = UnhandledPrecolored.rbegin(), E = UnhandledPrecolored.rend();
485 I != E; ++I) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700486 Variable *Item = *I;
487 assert(Item->hasReg());
488 if (Cur->rangeEndsBefore(Item))
Jim Stichnothf44f3712014-10-01 14:05:51 -0700489 break;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700490 if (Item->rangeOverlaps(Cur)) {
491 int32_t ItemReg = Item->getRegNum(); // Note: not getRegNumTmp()
Jim Stichnoth541ba662014-10-02 12:58:21 -0700492 Weights[ItemReg].setWeight(RegWeight::Inf);
Jim Stichnothad403532014-09-25 12:44:17 -0700493 Free[ItemReg] = false;
Jim Stichnoth541ba662014-10-02 12:58:21 -0700494 PrecoloredUnhandledMask[ItemReg] = true;
Jim Stichnothad403532014-09-25 12:44:17 -0700495 // Disable AllowOverlap if the preferred register is one of
496 // these precolored unhandled overlapping ranges.
497 if (AllowOverlap && ItemReg == PreferReg) {
498 AllowOverlap = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700499 dumpDisableOverlap(Func, Item, "PrecoloredUnhandled");
Jim Stichnothad403532014-09-25 12:44:17 -0700500 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700501 }
502 }
503
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800504 // Remove scratch registers from the Free[] list, and mark their
505 // Weights[] as infinite, if KillsRange overlaps Cur's live range.
506 const bool UseTrimmed = true;
507 if (Cur->getLiveRange().overlaps(KillsRange, UseTrimmed)) {
508 Free.reset(KillsMask);
509 for (int i = KillsMask.find_first(); i != -1;
510 i = KillsMask.find_next(i)) {
511 Weights[i].setWeight(RegWeight::Inf);
512 if (PreferReg == i)
513 AllowOverlap = false;
514 }
515 }
516
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700517 // Print info about physical register availability.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700518 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700519 for (SizeT i = 0; i < RegMask.size(); ++i) {
520 if (RegMask[i]) {
521 Str << Func->getTarget()->getRegName(i, IceType_i32)
Jim Stichnothca662e92014-07-10 15:32:36 -0700522 << "(U=" << RegUses[i] << ",F=" << Free[i]
Jim Stichnoth541ba662014-10-02 12:58:21 -0700523 << ",P=" << PrecoloredUnhandledMask[i] << ") ";
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700524 }
525 }
526 Str << "\n";
527 }
528
Jim Stichnothad403532014-09-25 12:44:17 -0700529 if (Prefer && (AllowOverlap || Free[PreferReg])) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700530 // First choice: a preferred register that is either free or is
531 // allowed to overlap with its linked variable.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700532 Cur->setRegNumTmp(PreferReg);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700533 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700534 Str << "Preferring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700535 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700536 Str << "\n";
537 }
538 assert(RegUses[PreferReg] >= 0);
539 ++RegUses[PreferReg];
540 Active.push_back(Cur);
541 } else if (Free.any()) {
542 // Second choice: any free register. TODO: After explicit
543 // affinity is considered, is there a strategy better than just
544 // picking the lowest-numbered available register?
545 int32_t RegNum = Free.find_first();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700546 Cur->setRegNumTmp(RegNum);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700547 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700548 Str << "Allocating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700549 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700550 Str << "\n";
551 }
552 assert(RegUses[RegNum] >= 0);
553 ++RegUses[RegNum];
554 Active.push_back(Cur);
555 } else {
556 // Fallback: there are no free registers, so we look for the
557 // lowest-weight register and see if Cur has higher weight.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700558 // Check Active ranges.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700559 for (const Variable *Item : Active) {
560 assert(Item->rangeOverlaps(Cur));
561 int32_t RegNum = Item->getRegNumTmp();
562 assert(Item->hasRegTmp());
563 Weights[RegNum].addWeight(Item->getLiveRange().getWeight());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700564 }
565 // Same as above, but check Inactive ranges instead of Active.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700566 for (const Variable *Item : Inactive) {
567 int32_t RegNum = Item->getRegNumTmp();
568 assert(Item->hasRegTmp());
569 if (Item->rangeOverlaps(Cur))
570 Weights[RegNum].addWeight(Item->getLiveRange().getWeight());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700571 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700572
573 // All the weights are now calculated. Find the register with
574 // smallest weight.
575 int32_t MinWeightIndex = RegMask.find_first();
576 // MinWeightIndex must be valid because of the initial
577 // RegMask.any() test.
578 assert(MinWeightIndex >= 0);
579 for (SizeT i = MinWeightIndex + 1; i < Weights.size(); ++i) {
580 if (RegMask[i] && Weights[i] < Weights[MinWeightIndex])
581 MinWeightIndex = i;
582 }
583
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700584 if (Cur->getLiveRange().getWeight() <= Weights[MinWeightIndex]) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700585 // Cur doesn't have priority over any other live ranges, so
586 // don't allocate any register to it, and move it to the
587 // Handled state.
588 Handled.push_back(Cur);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700589 if (Cur->getLiveRange().getWeight().isInf()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700590 Func->setError("Unable to find a physical register for an "
591 "infinite-weight live range");
592 }
593 } else {
594 // Evict all live ranges in Active that register number
595 // MinWeightIndex is assigned to.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700596 for (auto I = Active.begin(), E = Active.end(); I != E; I = Next) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700597 Next = I;
598 ++Next;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700599 Variable *Item = *I;
600 if (Item->getRegNumTmp() == MinWeightIndex) {
Jim Stichnothc4554d72014-09-30 16:49:38 -0700601 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700602 Str << "Evicting ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700603 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700604 Str << "\n";
605 }
606 --RegUses[MinWeightIndex];
607 assert(RegUses[MinWeightIndex] >= 0);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700608 Item->setRegNumTmp(Variable::NoRegister);
Jim Stichnothe22f8232014-10-13 16:20:59 -0700609 Handled.splice(Handled.end(), Active, I);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700610 }
611 }
612 // Do the same for Inactive.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700613 for (auto I = Inactive.begin(), E = Inactive.end(); I != E; I = Next) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700614 Next = I;
615 ++Next;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700616 Variable *Item = *I;
617 // Note: The Item->rangeOverlaps(Cur) clause is not part of the
Jim Stichnoth68e28192014-07-24 08:48:15 -0700618 // description of AssignMemLoc() in the original paper. But
619 // there doesn't seem to be any need to evict an inactive
620 // live range that doesn't overlap with the live range
621 // currently being considered. It's especially bad if we
622 // would end up evicting an infinite-weight but
623 // currently-inactive live range. The most common situation
624 // for this would be a scratch register kill set for call
625 // instructions.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700626 if (Item->getRegNumTmp() == MinWeightIndex &&
627 Item->rangeOverlaps(Cur)) {
Jim Stichnothc4554d72014-09-30 16:49:38 -0700628 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700629 Str << "Evicting ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700630 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700631 Str << "\n";
632 }
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700633 Item->setRegNumTmp(Variable::NoRegister);
Jim Stichnothe22f8232014-10-13 16:20:59 -0700634 Handled.splice(Handled.end(), Inactive, I);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700635 }
636 }
637 // Assign the register to Cur.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700638 Cur->setRegNumTmp(MinWeightIndex);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700639 assert(RegUses[MinWeightIndex] >= 0);
640 ++RegUses[MinWeightIndex];
641 Active.push_back(Cur);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700642 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700643 Str << "Allocating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700644 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700645 Str << "\n";
646 }
647 }
648 }
649 dump(Func);
650 }
651 // Move anything Active or Inactive to Handled for easier handling.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700652 for (Variable *I : Active)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700653 Handled.push_back(I);
654 Active.clear();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700655 for (Variable *I : Inactive)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700656 Handled.push_back(I);
657 Inactive.clear();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700658 dump(Func);
659
660 // Finish up by assigning RegNumTmp->RegNum for each Variable.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700661 for (Variable *Item : Handled) {
662 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothc4554d72014-09-30 16:49:38 -0700663 if (Verbose) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700664 if (!Item->hasRegTmp()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700665 Str << "Not assigning ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700666 Item->dump(Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700667 Str << "\n";
668 } else {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700669 Str << (RegNum == Item->getRegNum() ? "Reassigning " : "Assigning ")
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700670 << Func->getTarget()->getRegName(RegNum, IceType_i32) << "(r"
671 << RegNum << ") to ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700672 Item->dump(Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700673 Str << "\n";
674 }
675 }
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700676 Item->setRegNum(Item->getRegNumTmp());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700677 }
678
679 // TODO: Consider running register allocation one more time, with
680 // infinite registers, for two reasons. First, evicted live ranges
681 // get a second chance for a register. Second, it allows coalescing
682 // of stack slots. If there is no time budget for the second
683 // register allocation run, each unallocated variable just gets its
684 // own slot.
685 //
686 // Another idea for coalescing stack slots is to initialize the
687 // Unhandled list with just the unallocated variables, saving time
688 // but not offering second-chance opportunities.
689}
690
691// ======================== Dump routines ======================== //
692
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700693void LinearScan::dump(Cfg *Func) const {
694 Ostream &Str = Func->getContext()->getStrDump();
695 if (!Func->getContext()->isVerbose(IceV_LinearScan))
696 return;
Jim Stichnoth800dab22014-09-20 12:25:02 -0700697 Func->resetCurrentNode();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700698 Str << "**** Current regalloc state:\n";
699 Str << "++++++ Handled:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700700 for (const Variable *Item : Handled) {
701 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700702 Str << "\n";
703 }
704 Str << "++++++ Unhandled:\n";
Jim Stichnothe22f8232014-10-13 16:20:59 -0700705 for (auto I = Unhandled.rbegin(), E = Unhandled.rend(); I != E; ++I) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700706 dumpLiveRange(*I, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700707 Str << "\n";
708 }
709 Str << "++++++ Active:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700710 for (const Variable *Item : Active) {
711 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700712 Str << "\n";
713 }
714 Str << "++++++ Inactive:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700715 for (const Variable *Item : Inactive) {
716 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700717 Str << "\n";
718 }
719}
720
721} // end of namespace Ice