blob: 4ba82a06032fe65dc349c7dda1a1c37deaeb2fab [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
Jim Stichnothe34d79d2015-01-12 09:00:50 -080027// TODO(stichnot): Statically choose the size based on the target
28// being compiled.
29const size_t REGS_SIZE = 32;
30
Jim Stichnothad403532014-09-25 12:44:17 -070031// Returns true if Var has any definitions within Item's live range.
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070032// TODO(stichnot): Consider trimming the Definitions list similar to
33// how the live ranges are trimmed, since all the overlapsDefs() tests
34// are whether some variable's definitions overlap Cur, and trimming
35// is with respect Cur.start. Initial tests show no measurable
36// performance difference, so we'll keep the code simple for now.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070037bool overlapsDefs(const Cfg *Func, const Variable *Item, const Variable *Var) {
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070038 const bool UseTrimmed = true;
39 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnoth877b04e2014-10-15 15:13:06 -070040 if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var))
41 if (Item->getLiveRange().overlapsInst(FirstDef->getNumber(), UseTrimmed))
42 return true;
43 const InstDefList &Defs = VMetadata->getLatterDefinitions(Var);
Jim Stichnothad403532014-09-25 12:44:17 -070044 for (size_t i = 0; i < Defs.size(); ++i) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070045 if (Item->getLiveRange().overlapsInst(Defs[i]->getNumber(), UseTrimmed))
Jim Stichnothad403532014-09-25 12:44:17 -070046 return true;
47 }
48 return false;
49}
50
51void dumpDisableOverlap(const Cfg *Func, const Variable *Var,
52 const char *Reason) {
Karl Schimpfb6c96af2014-11-17 10:58:39 -080053 if (!ALLOW_DUMP)
54 return;
Jim Stichnothad403532014-09-25 12:44:17 -070055 if (Func->getContext()->isVerbose(IceV_LinearScan)) {
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070056 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnothad403532014-09-25 12:44:17 -070057 Ostream &Str = Func->getContext()->getStrDump();
58 Str << "Disabling Overlap due to " << Reason << " " << *Var
59 << " LIVE=" << Var->getLiveRange() << " Defs=";
Jim Stichnoth877b04e2014-10-15 15:13:06 -070060 if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var))
61 Str << FirstDef->getNumber();
62 const InstDefList &Defs = VMetadata->getLatterDefinitions(Var);
Jim Stichnothad403532014-09-25 12:44:17 -070063 for (size_t i = 0; i < Defs.size(); ++i) {
Jim Stichnoth877b04e2014-10-15 15:13:06 -070064 Str << "," << Defs[i]->getNumber();
Jim Stichnothad403532014-09-25 12:44:17 -070065 }
66 Str << "\n";
67 }
68}
69
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070070void dumpLiveRange(const Variable *Var, const Cfg *Func) {
Karl Schimpfb6c96af2014-11-17 10:58:39 -080071 if (!ALLOW_DUMP)
72 return;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070073 Ostream &Str = Func->getContext()->getStrDump();
74 const static size_t BufLen = 30;
75 char buf[BufLen];
76 snprintf(buf, BufLen, "%2d", Var->getRegNumTmp());
77 Str << "R=" << buf << " V=";
78 Var->dump(Func);
79 Str << " Range=" << Var->getLiveRange();
Jim Stichnothe22f8232014-10-13 16:20:59 -070080}
81
Jim Stichnothad403532014-09-25 12:44:17 -070082} // end of anonymous namespace
83
Jim Stichnoth70d0a052014-11-14 15:53:46 -080084// Prepare for full register allocation of all variables. We depend
85// on liveness analysis to have calculated live ranges.
86void LinearScan::initForGlobal() {
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080087 TimerMarker T(TimerStack::TT_initUnhandled, Func);
Jim Stichnoth70d0a052014-11-14 15:53:46 -080088 FindPreference = true;
89 FindOverlap = true;
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080090 const VarList &Vars = Func->getVariables();
91 Unhandled.reserve(Vars.size());
Jim Stichnoth4ead35a2014-12-03 20:30:34 -080092 UnhandledPrecolored.reserve(Vars.size());
Jim Stichnoth70d0a052014-11-14 15:53:46 -080093 // Gather the live ranges of all variables and add them to the
94 // Unhandled set.
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080095 for (Variable *Var : Vars) {
96 // Explicitly don't consider zero-weight variables, which are
97 // meant to be spill slots.
98 if (Var->getWeight() == RegWeight::Zero)
99 continue;
100 // Don't bother if the variable has a null live range, which means
101 // it was never referenced.
102 if (Var->getLiveRange().isEmpty())
103 continue;
104 Var->untrimLiveRange();
105 Unhandled.push_back(Var);
106 if (Var->hasReg()) {
107 Var->setRegNumTmp(Var->getRegNum());
108 Var->setLiveRangeInfiniteWeight();
109 UnhandledPrecolored.push_back(Var);
110 }
111 }
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800112
113 // Build the (ordered) list of FakeKill instruction numbers.
114 Kills.clear();
115 for (CfgNode *Node : Func->getNodes()) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800116 for (Inst &I : Node->getInsts()) {
117 if (auto Kill = llvm::dyn_cast<InstFakeKill>(&I)) {
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800118 if (!Kill->isDeleted() && !Kill->getLinked()->isDeleted())
Jim Stichnoth29841e82014-12-23 12:26:24 -0800119 Kills.push_back(I.getNumber());
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800120 }
121 }
122 }
123}
124
125// Prepare for very simple register allocation of only infinite-weight
126// Variables while respecting pre-colored Variables. Some properties
127// we take advantage of:
128//
129// * Live ranges of interest consist of a single segment.
130//
131// * Live ranges of interest never span a call instruction.
132//
133// * Phi instructions are not considered because either phis have
134// already been lowered, or they don't contain any pre-colored or
135// infinite-weight Variables.
136//
137// * We don't need to renumber instructions before computing live
138// ranges because all the high-level ICE instructions are deleted
139// prior to lowering, and the low-level instructions are added in
140// monotonically increasing order.
141//
142// * There are no opportunities for register preference or allowing
143// overlap.
144//
145// Some properties we aren't (yet) taking advantage of:
146//
Jim Stichnothe6d24782014-12-19 05:42:24 -0800147// * Because live ranges are a single segment, the Inactive set will
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800148// always be empty, and the live range trimming operation is
149// unnecessary.
150//
151// * Calculating overlap of single-segment live ranges could be
152// optimized a bit.
153void LinearScan::initForInfOnly() {
154 TimerMarker T(TimerStack::TT_initUnhandled, Func);
155 FindPreference = false;
156 FindOverlap = false;
157 SizeT NumVars = 0;
158 const VarList &Vars = Func->getVariables();
159
160 // Iterate across all instructions and record the begin and end of
161 // the live range for each variable that is pre-colored or infinite
162 // weight.
163 std::vector<InstNumberT> LRBegin(Vars.size(), Inst::NumberSentinel);
164 std::vector<InstNumberT> LREnd(Vars.size(), Inst::NumberSentinel);
165 for (CfgNode *Node : Func->getNodes()) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800166 for (Inst &Inst : Node->getInsts()) {
167 if (Inst.isDeleted())
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800168 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800169 if (const Variable *Var = Inst.getDest()) {
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800170 if (Var->hasReg() || Var->getWeight() == RegWeight::Inf) {
171 if (LRBegin[Var->getIndex()] == Inst::NumberSentinel) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800172 LRBegin[Var->getIndex()] = Inst.getNumber();
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800173 ++NumVars;
174 }
175 }
176 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800177 for (SizeT I = 0; I < Inst.getSrcSize(); ++I) {
178 Operand *Src = Inst.getSrc(I);
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800179 SizeT NumVars = Src->getNumVars();
180 for (SizeT J = 0; J < NumVars; ++J) {
181 const Variable *Var = Src->getVar(J);
182 if (Var->hasReg() || Var->getWeight() == RegWeight::Inf)
Jim Stichnoth29841e82014-12-23 12:26:24 -0800183 LREnd[Var->getIndex()] = Inst.getNumber();
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800184 }
185 }
186 }
187 }
188
189 Unhandled.reserve(NumVars);
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800190 UnhandledPrecolored.reserve(NumVars);
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800191 for (SizeT i = 0; i < Vars.size(); ++i) {
192 Variable *Var = Vars[i];
193 if (LRBegin[i] != Inst::NumberSentinel) {
194 assert(LREnd[i] != Inst::NumberSentinel);
195 Unhandled.push_back(Var);
196 Var->resetLiveRange();
197 const uint32_t WeightDelta = 1;
198 Var->addLiveRange(LRBegin[i], LREnd[i], WeightDelta);
199 Var->untrimLiveRange();
200 if (Var->hasReg()) {
201 Var->setRegNumTmp(Var->getRegNum());
202 Var->setLiveRangeInfiniteWeight();
203 UnhandledPrecolored.push_back(Var);
204 }
205 --NumVars;
206 }
207 }
208 // This isn't actually a fatal condition, but it would be nice to
209 // know if we somehow pre-calculated Unhandled's size wrong.
210 assert(NumVars == 0);
211
212 // Don't build up the list of Kills because we know that no
213 // infinite-weight Variable has a live range spanning a call.
214 Kills.clear();
215}
216
217void LinearScan::init(RegAllocKind Kind) {
218 Unhandled.clear();
219 UnhandledPrecolored.clear();
220 Handled.clear();
221 Inactive.clear();
222 Active.clear();
223
224 switch (Kind) {
225 case RAK_Global:
226 initForGlobal();
227 break;
228 case RAK_InfOnly:
229 initForInfOnly();
230 break;
231 }
232
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800233 struct CompareRanges {
234 bool operator()(const Variable *L, const Variable *R) {
235 InstNumberT Lstart = L->getLiveRange().getStart();
236 InstNumberT Rstart = R->getLiveRange().getStart();
237 if (Lstart == Rstart)
238 return L->getIndex() < R->getIndex();
239 return Lstart < Rstart;
240 }
241 };
242 // Do a reverse sort so that erasing elements (from the end) is fast.
243 std::sort(Unhandled.rbegin(), Unhandled.rend(), CompareRanges());
244 std::sort(UnhandledPrecolored.rbegin(), UnhandledPrecolored.rend(),
245 CompareRanges());
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800246
247 Handled.reserve(Unhandled.size());
248 Inactive.reserve(Unhandled.size());
249 Active.reserve(Unhandled.size());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800250}
251
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700252// Implements the linear-scan algorithm. Based on "Linear Scan
253// Register Allocation in the Context of SSA Form and Register
254// Constraints" by Hanspeter Mössenböck and Michael Pfeiffer,
255// ftp://ftp.ssw.uni-linz.ac.at/pub/Papers/Moe02.PDF . This
256// implementation is modified to take affinity into account and allow
257// two interfering variables to share the same register in certain
258// cases.
259//
Jim Stichnoth800dab22014-09-20 12:25:02 -0700260// Requires running Cfg::liveness(Liveness_Intervals) in
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700261// preparation. Results are assigned to Variable::RegNum for each
262// Variable.
Jim Stichnothe6d24782014-12-19 05:42:24 -0800263void LinearScan::scan(const llvm::SmallBitVector &RegMaskFull,
264 bool Randomized) {
Jim Stichnoth8363a062014-10-07 10:02:38 -0700265 TimerMarker T(TimerStack::TT_linearScan, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700266 assert(RegMaskFull.any()); // Sanity check
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700267 Ostream &Str = Func->getContext()->getStrDump();
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800268 const bool Verbose =
269 ALLOW_DUMP && Func->getContext()->isVerbose(IceV_LinearScan);
Jim Stichnoth800dab22014-09-20 12:25:02 -0700270 Func->resetCurrentNode();
Jim Stichnothad403532014-09-25 12:44:17 -0700271 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnothe6d24782014-12-19 05:42:24 -0800272 const size_t NumRegisters = RegMaskFull.size();
273 llvm::SmallBitVector PreDefinedRegisters(NumRegisters);
274 if (Randomized) {
275 for (Variable *Var : UnhandledPrecolored) {
276 PreDefinedRegisters[Var->getRegNum()] = true;
277 }
278 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700279
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800280 // Build a LiveRange representing the Kills list.
Jim Stichnoth2a7fcbb2014-12-04 11:45:03 -0800281 LiveRange KillsRange(Kills);
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800282 KillsRange.untrim();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700283
284 // RegUses[I] is the number of live ranges (variables) that register
285 // I is currently assigned to. It can be greater than 1 as a result
Jim Stichnothc4554d72014-09-30 16:49:38 -0700286 // of AllowOverlap inference below.
Jim Stichnothe34d79d2015-01-12 09:00:50 -0800287 llvm::SmallVector<int, REGS_SIZE> RegUses(NumRegisters);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700288 // Unhandled is already set to all ranges in increasing order of
289 // start points.
290 assert(Active.empty());
291 assert(Inactive.empty());
292 assert(Handled.empty());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800293 const TargetLowering::RegSetMask RegsInclude =
294 TargetLowering::RegSet_CallerSave;
295 const TargetLowering::RegSetMask RegsExclude = TargetLowering::RegSet_None;
296 const llvm::SmallBitVector KillsMask =
297 Func->getTarget()->getRegisterSet(RegsInclude, RegsExclude);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700298
299 while (!Unhandled.empty()) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700300 Variable *Cur = Unhandled.back();
Jim Stichnothe22f8232014-10-13 16:20:59 -0700301 Unhandled.pop_back();
Jim Stichnothc4554d72014-09-30 16:49:38 -0700302 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700303 Str << "\nConsidering ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700304 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700305 Str << "\n";
306 }
307 const llvm::SmallBitVector RegMask =
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700308 RegMaskFull & Func->getTarget()->getRegisterSetForType(Cur->getType());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800309 KillsRange.trim(Cur->getLiveRange().getStart());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700310
311 // Check for precolored ranges. If Cur is precolored, it
312 // definitely gets that register. Previously processed live
313 // ranges would have avoided that register due to it being
314 // precolored. Future processed live ranges won't evict that
315 // register because the live range has infinite weight.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700316 if (Cur->hasReg()) {
317 int32_t RegNum = Cur->getRegNum();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700318 // RegNumTmp should have already been set above.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700319 assert(Cur->getRegNumTmp() == RegNum);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700320 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700321 Str << "Precoloring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700322 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700323 Str << "\n";
324 }
325 Active.push_back(Cur);
326 assert(RegUses[RegNum] >= 0);
327 ++RegUses[RegNum];
Jim Stichnoth541ba662014-10-02 12:58:21 -0700328 assert(!UnhandledPrecolored.empty());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700329 assert(UnhandledPrecolored.back() == Cur);
Jim Stichnothe22f8232014-10-13 16:20:59 -0700330 UnhandledPrecolored.pop_back();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700331 continue;
332 }
333
334 // Check for active ranges that have expired or become inactive.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800335 for (SizeT I = Active.size(); I > 0; --I) {
336 const SizeT Index = I - 1;
337 Variable *Item = Active[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700338 Item->trimLiveRange(Cur->getLiveRange().getStart());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700339 bool Moved = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700340 if (Item->rangeEndsBefore(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700341 // Move Item from Active to Handled list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700342 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700343 Str << "Expiring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700344 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700345 Str << "\n";
346 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800347 moveItem(Active, Index, Handled);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700348 Moved = true;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700349 } else if (!Item->rangeOverlapsStart(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700350 // Move Item from Active to Inactive list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700351 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700352 Str << "Inactivating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700353 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700354 Str << "\n";
355 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800356 moveItem(Active, Index, Inactive);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700357 Moved = true;
358 }
359 if (Moved) {
360 // Decrement Item from RegUses[].
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700361 assert(Item->hasRegTmp());
362 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700363 --RegUses[RegNum];
364 assert(RegUses[RegNum] >= 0);
365 }
366 }
367
368 // Check for inactive ranges that have expired or reactivated.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800369 for (SizeT I = Inactive.size(); I > 0; --I) {
370 const SizeT Index = I - 1;
371 Variable *Item = Inactive[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700372 Item->trimLiveRange(Cur->getLiveRange().getStart());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700373 if (Item->rangeEndsBefore(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700374 // Move Item from Inactive to Handled list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700375 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700376 Str << "Expiring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700377 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700378 Str << "\n";
379 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800380 moveItem(Inactive, Index, Handled);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700381 } else if (Item->rangeOverlapsStart(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700382 // Move Item from Inactive to Active list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700383 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700384 Str << "Reactivating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700385 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700386 Str << "\n";
387 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800388 moveItem(Inactive, Index, Active);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700389 // Increment Item in RegUses[].
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700390 assert(Item->hasRegTmp());
391 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700392 assert(RegUses[RegNum] >= 0);
393 ++RegUses[RegNum];
394 }
395 }
396
397 // Calculate available registers into Free[].
398 llvm::SmallBitVector Free = RegMask;
399 for (SizeT i = 0; i < RegMask.size(); ++i) {
400 if (RegUses[i] > 0)
401 Free[i] = false;
402 }
403
Jim Stichnothad403532014-09-25 12:44:17 -0700404 // Infer register preference and allowable overlap. Only form a
405 // preference when the current Variable has an unambiguous "first"
406 // definition. The preference is some source Variable of the
407 // defining instruction that either is assigned a register that is
408 // currently free, or that is assigned a register that is not free
409 // but overlap is allowed. Overlap is allowed when the Variable
410 // under consideration is single-definition, and its definition is
411 // a simple assignment - i.e., the register gets copied/aliased
412 // but is never modified. Furthermore, overlap is only allowed
413 // when preferred Variable definition instructions do not appear
414 // within the current Variable's live range.
Jim Stichnothae953202014-12-20 06:17:49 -0800415 Variable *Prefer = nullptr;
Jim Stichnothad403532014-09-25 12:44:17 -0700416 int32_t PreferReg = Variable::NoRegister;
417 bool AllowOverlap = false;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800418 if (FindPreference) {
419 if (const Inst *DefInst = VMetadata->getFirstDefinition(Cur)) {
420 assert(DefInst->getDest() == Cur);
421 bool IsAssign = DefInst->isSimpleAssign();
422 bool IsSingleDef = !VMetadata->isMultiDef(Cur);
423 for (SizeT i = 0; i < DefInst->getSrcSize(); ++i) {
424 // TODO(stichnot): Iterate through the actual Variables of the
425 // instruction, not just the source operands. This could
426 // capture Load instructions, including address mode
427 // optimization, for Prefer (but not for AllowOverlap).
428 if (Variable *SrcVar = llvm::dyn_cast<Variable>(DefInst->getSrc(i))) {
429 int32_t SrcReg = SrcVar->getRegNumTmp();
430 // Only consider source variables that have (so far) been
431 // assigned a register. That register must be one in the
432 // RegMask set, e.g. don't try to prefer the stack pointer
433 // as a result of the stacksave intrinsic.
434 if (SrcVar->hasRegTmp() && RegMask[SrcReg]) {
435 if (FindOverlap && !Free[SrcReg]) {
436 // Don't bother trying to enable AllowOverlap if the
437 // register is already free.
438 AllowOverlap =
439 IsSingleDef && IsAssign && !overlapsDefs(Func, Cur, SrcVar);
440 }
441 if (AllowOverlap || Free[SrcReg]) {
442 Prefer = SrcVar;
443 PreferReg = SrcReg;
444 }
Jim Stichnothad403532014-09-25 12:44:17 -0700445 }
446 }
447 }
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800448 if (Verbose && Prefer) {
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800449 Str << "Initial Prefer=";
450 Prefer->dump(Func);
451 Str << " R=" << PreferReg << " LIVE=" << Prefer->getLiveRange()
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800452 << " Overlap=" << AllowOverlap << "\n";
453 }
Jim Stichnothad403532014-09-25 12:44:17 -0700454 }
455 }
456
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700457 // Remove registers from the Free[] list where an Inactive range
458 // overlaps with the current range.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700459 for (const Variable *Item : Inactive) {
460 if (Item->rangeOverlaps(Cur)) {
461 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700462 // Don't assert(Free[RegNum]) because in theory (though
463 // probably never in practice) there could be two inactive
Jim Stichnothc4554d72014-09-30 16:49:38 -0700464 // variables that were marked with AllowOverlap.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700465 Free[RegNum] = false;
Jim Stichnothad403532014-09-25 12:44:17 -0700466 // Disable AllowOverlap if an Inactive variable, which is not
467 // Prefer, shares Prefer's register, and has a definition
468 // within Cur's live range.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700469 if (AllowOverlap && Item != Prefer && RegNum == PreferReg &&
470 overlapsDefs(Func, Cur, Item)) {
Jim Stichnothad403532014-09-25 12:44:17 -0700471 AllowOverlap = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700472 dumpDisableOverlap(Func, Item, "Inactive");
Jim Stichnothad403532014-09-25 12:44:17 -0700473 }
474 }
475 }
476
477 // Disable AllowOverlap if an Active variable, which is not
478 // Prefer, shares Prefer's register, and has a definition within
479 // Cur's live range.
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800480 if (AllowOverlap) {
481 for (const Variable *Item : Active) {
482 int32_t RegNum = Item->getRegNumTmp();
483 if (Item != Prefer && RegNum == PreferReg &&
484 overlapsDefs(Func, Cur, Item)) {
485 AllowOverlap = false;
486 dumpDisableOverlap(Func, Item, "Active");
487 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700488 }
489 }
490
Jim Stichnothe34d79d2015-01-12 09:00:50 -0800491 llvm::SmallVector<RegWeight, REGS_SIZE> Weights(RegMask.size());
Jim Stichnoth541ba662014-10-02 12:58:21 -0700492
493 // Remove registers from the Free[] list where an Unhandled
494 // precolored range overlaps with the current range, and set those
495 // registers to infinite weight so that they aren't candidates for
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700496 // eviction. Cur->rangeEndsBefore(Item) is an early exit check
497 // that turns a guaranteed O(N^2) algorithm into expected linear
Jim Stichnoth541ba662014-10-02 12:58:21 -0700498 // complexity.
499 llvm::SmallBitVector PrecoloredUnhandledMask(RegMask.size());
500 // Note: PrecoloredUnhandledMask is only used for dumping.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800501 for (Variable *Item : reverse_range(UnhandledPrecolored)) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700502 assert(Item->hasReg());
503 if (Cur->rangeEndsBefore(Item))
Jim Stichnothf44f3712014-10-01 14:05:51 -0700504 break;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700505 if (Item->rangeOverlaps(Cur)) {
506 int32_t ItemReg = Item->getRegNum(); // Note: not getRegNumTmp()
Jim Stichnoth541ba662014-10-02 12:58:21 -0700507 Weights[ItemReg].setWeight(RegWeight::Inf);
Jim Stichnothad403532014-09-25 12:44:17 -0700508 Free[ItemReg] = false;
Jim Stichnoth541ba662014-10-02 12:58:21 -0700509 PrecoloredUnhandledMask[ItemReg] = true;
Jim Stichnothad403532014-09-25 12:44:17 -0700510 // Disable AllowOverlap if the preferred register is one of
511 // these precolored unhandled overlapping ranges.
512 if (AllowOverlap && ItemReg == PreferReg) {
513 AllowOverlap = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700514 dumpDisableOverlap(Func, Item, "PrecoloredUnhandled");
Jim Stichnothad403532014-09-25 12:44:17 -0700515 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700516 }
517 }
518
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800519 // Remove scratch registers from the Free[] list, and mark their
520 // Weights[] as infinite, if KillsRange overlaps Cur's live range.
521 const bool UseTrimmed = true;
522 if (Cur->getLiveRange().overlaps(KillsRange, UseTrimmed)) {
523 Free.reset(KillsMask);
524 for (int i = KillsMask.find_first(); i != -1;
525 i = KillsMask.find_next(i)) {
526 Weights[i].setWeight(RegWeight::Inf);
527 if (PreferReg == i)
528 AllowOverlap = false;
529 }
530 }
531
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700532 // Print info about physical register availability.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700533 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700534 for (SizeT i = 0; i < RegMask.size(); ++i) {
535 if (RegMask[i]) {
536 Str << Func->getTarget()->getRegName(i, IceType_i32)
Jim Stichnothca662e92014-07-10 15:32:36 -0700537 << "(U=" << RegUses[i] << ",F=" << Free[i]
Jim Stichnoth541ba662014-10-02 12:58:21 -0700538 << ",P=" << PrecoloredUnhandledMask[i] << ") ";
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700539 }
540 }
541 Str << "\n";
542 }
543
Jim Stichnothad403532014-09-25 12:44:17 -0700544 if (Prefer && (AllowOverlap || Free[PreferReg])) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700545 // First choice: a preferred register that is either free or is
546 // allowed to overlap with its linked variable.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700547 Cur->setRegNumTmp(PreferReg);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700548 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700549 Str << "Preferring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700550 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700551 Str << "\n";
552 }
553 assert(RegUses[PreferReg] >= 0);
554 ++RegUses[PreferReg];
555 Active.push_back(Cur);
556 } else if (Free.any()) {
557 // Second choice: any free register. TODO: After explicit
558 // affinity is considered, is there a strategy better than just
559 // picking the lowest-numbered available register?
560 int32_t RegNum = Free.find_first();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700561 Cur->setRegNumTmp(RegNum);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700562 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700563 Str << "Allocating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700564 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700565 Str << "\n";
566 }
567 assert(RegUses[RegNum] >= 0);
568 ++RegUses[RegNum];
569 Active.push_back(Cur);
570 } else {
571 // Fallback: there are no free registers, so we look for the
572 // lowest-weight register and see if Cur has higher weight.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700573 // Check Active ranges.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700574 for (const Variable *Item : Active) {
575 assert(Item->rangeOverlaps(Cur));
576 int32_t RegNum = Item->getRegNumTmp();
577 assert(Item->hasRegTmp());
578 Weights[RegNum].addWeight(Item->getLiveRange().getWeight());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700579 }
580 // Same as above, but check Inactive ranges instead of Active.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700581 for (const Variable *Item : Inactive) {
582 int32_t RegNum = Item->getRegNumTmp();
583 assert(Item->hasRegTmp());
584 if (Item->rangeOverlaps(Cur))
585 Weights[RegNum].addWeight(Item->getLiveRange().getWeight());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700586 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700587
588 // All the weights are now calculated. Find the register with
589 // smallest weight.
590 int32_t MinWeightIndex = RegMask.find_first();
591 // MinWeightIndex must be valid because of the initial
592 // RegMask.any() test.
593 assert(MinWeightIndex >= 0);
594 for (SizeT i = MinWeightIndex + 1; i < Weights.size(); ++i) {
595 if (RegMask[i] && Weights[i] < Weights[MinWeightIndex])
596 MinWeightIndex = i;
597 }
598
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700599 if (Cur->getLiveRange().getWeight() <= Weights[MinWeightIndex]) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700600 // Cur doesn't have priority over any other live ranges, so
601 // don't allocate any register to it, and move it to the
602 // Handled state.
603 Handled.push_back(Cur);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700604 if (Cur->getLiveRange().getWeight().isInf()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700605 Func->setError("Unable to find a physical register for an "
606 "infinite-weight live range");
607 }
608 } else {
609 // Evict all live ranges in Active that register number
610 // MinWeightIndex is assigned to.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800611 for (SizeT I = Active.size(); I > 0; --I) {
612 const SizeT Index = I - 1;
613 Variable *Item = Active[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700614 if (Item->getRegNumTmp() == MinWeightIndex) {
Jim Stichnothc4554d72014-09-30 16:49:38 -0700615 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700616 Str << "Evicting ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700617 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700618 Str << "\n";
619 }
620 --RegUses[MinWeightIndex];
621 assert(RegUses[MinWeightIndex] >= 0);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700622 Item->setRegNumTmp(Variable::NoRegister);
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800623 moveItem(Active, Index, Handled);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700624 }
625 }
626 // Do the same for Inactive.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800627 for (SizeT I = Inactive.size(); I > 0; --I) {
628 const SizeT Index = I - 1;
629 Variable *Item = Inactive[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700630 // Note: The Item->rangeOverlaps(Cur) clause is not part of the
Jim Stichnoth68e28192014-07-24 08:48:15 -0700631 // description of AssignMemLoc() in the original paper. But
632 // there doesn't seem to be any need to evict an inactive
633 // live range that doesn't overlap with the live range
634 // currently being considered. It's especially bad if we
635 // would end up evicting an infinite-weight but
636 // currently-inactive live range. The most common situation
637 // for this would be a scratch register kill set for call
638 // instructions.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700639 if (Item->getRegNumTmp() == MinWeightIndex &&
640 Item->rangeOverlaps(Cur)) {
Jim Stichnothc4554d72014-09-30 16:49:38 -0700641 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700642 Str << "Evicting ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700643 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700644 Str << "\n";
645 }
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700646 Item->setRegNumTmp(Variable::NoRegister);
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800647 moveItem(Inactive, Index, Handled);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700648 }
649 }
650 // Assign the register to Cur.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700651 Cur->setRegNumTmp(MinWeightIndex);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700652 assert(RegUses[MinWeightIndex] >= 0);
653 ++RegUses[MinWeightIndex];
654 Active.push_back(Cur);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700655 if (Verbose) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700656 Str << "Allocating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700657 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700658 Str << "\n";
659 }
660 }
661 }
662 dump(Func);
663 }
664 // Move anything Active or Inactive to Handled for easier handling.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700665 for (Variable *I : Active)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700666 Handled.push_back(I);
667 Active.clear();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700668 for (Variable *I : Inactive)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700669 Handled.push_back(I);
670 Inactive.clear();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700671 dump(Func);
672
Jim Stichnothe6d24782014-12-19 05:42:24 -0800673 llvm::SmallVector<int32_t, REGS_SIZE> Permutation(NumRegisters);
674 if (Randomized) {
675 Func->getTarget()->makeRandomRegisterPermutation(
676 Permutation, PreDefinedRegisters | ~RegMaskFull);
677 }
678
679 // Finish up by assigning RegNumTmp->RegNum (or a random permutation
680 // thereof) for each Variable.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700681 for (Variable *Item : Handled) {
682 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothe6d24782014-12-19 05:42:24 -0800683 int32_t AssignedRegNum = RegNum;
684
685 if (Randomized && Item->hasRegTmp() && !Item->hasReg()) {
686 AssignedRegNum = Permutation[RegNum];
687 }
Jim Stichnothc4554d72014-09-30 16:49:38 -0700688 if (Verbose) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700689 if (!Item->hasRegTmp()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700690 Str << "Not assigning ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700691 Item->dump(Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700692 Str << "\n";
693 } else {
Jim Stichnothe6d24782014-12-19 05:42:24 -0800694 Str << (AssignedRegNum == Item->getRegNum() ? "Reassigning "
695 : "Assigning ")
696 << Func->getTarget()->getRegName(AssignedRegNum, IceType_i32)
697 << "(r" << AssignedRegNum << ") to ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700698 Item->dump(Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700699 Str << "\n";
700 }
701 }
Jim Stichnothe6d24782014-12-19 05:42:24 -0800702 Item->setRegNum(AssignedRegNum);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700703 }
704
705 // TODO: Consider running register allocation one more time, with
706 // infinite registers, for two reasons. First, evicted live ranges
707 // get a second chance for a register. Second, it allows coalescing
708 // of stack slots. If there is no time budget for the second
709 // register allocation run, each unallocated variable just gets its
710 // own slot.
711 //
712 // Another idea for coalescing stack slots is to initialize the
713 // Unhandled list with just the unallocated variables, saving time
714 // but not offering second-chance opportunities.
715}
716
717// ======================== Dump routines ======================== //
718
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700719void LinearScan::dump(Cfg *Func) const {
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800720 if (!ALLOW_DUMP)
721 return;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700722 Ostream &Str = Func->getContext()->getStrDump();
723 if (!Func->getContext()->isVerbose(IceV_LinearScan))
724 return;
Jim Stichnoth800dab22014-09-20 12:25:02 -0700725 Func->resetCurrentNode();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700726 Str << "**** Current regalloc state:\n";
727 Str << "++++++ Handled:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700728 for (const Variable *Item : Handled) {
729 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700730 Str << "\n";
731 }
732 Str << "++++++ Unhandled:\n";
Jim Stichnoth7e571362015-01-09 11:43:26 -0800733 for (const Variable *Item : reverse_range(Unhandled)) {
734 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700735 Str << "\n";
736 }
737 Str << "++++++ Active:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700738 for (const Variable *Item : Active) {
739 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700740 Str << "\n";
741 }
742 Str << "++++++ Inactive:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700743 for (const Variable *Item : Inactive) {
744 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700745 Str << "\n";
746 }
747}
748
749} // end of namespace Ice