blob: 9eb4a470f298359c1ae5cbb14d9cf314bf13d737 [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// Copyright 2014 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Ben Murdochb8a8cc12014-11-26 15:28:44 +00005#include "src/compiler/linkage.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -04006#include "src/compiler/register-allocator.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +00007#include "src/string-stream.h"
8
9namespace v8 {
10namespace internal {
11namespace compiler {
12
13static inline LifetimePosition Min(LifetimePosition a, LifetimePosition b) {
14 return a.Value() < b.Value() ? a : b;
15}
16
17
18static inline LifetimePosition Max(LifetimePosition a, LifetimePosition b) {
19 return a.Value() > b.Value() ? a : b;
20}
21
22
Emily Bernierd0a1eb72015-03-24 16:35:39 -040023static void TraceAlloc(const char* msg, ...) {
24 if (FLAG_trace_alloc) {
25 va_list arguments;
26 va_start(arguments, msg);
27 base::OS::VPrint(msg, arguments);
28 va_end(arguments);
29 }
30}
31
32
33static void RemoveElement(ZoneVector<LiveRange*>* v, LiveRange* range) {
34 auto it = std::find(v->begin(), v->end(), range);
35 DCHECK(it != v->end());
36 v->erase(it);
37}
38
39
Ben Murdochb8a8cc12014-11-26 15:28:44 +000040UsePosition::UsePosition(LifetimePosition pos, InstructionOperand* operand,
41 InstructionOperand* hint)
42 : operand_(operand),
43 hint_(hint),
44 pos_(pos),
Emily Bernierd0a1eb72015-03-24 16:35:39 -040045 next_(nullptr),
Ben Murdochb8a8cc12014-11-26 15:28:44 +000046 requires_reg_(false),
47 register_beneficial_(true) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -040048 if (operand_ != nullptr && operand_->IsUnallocated()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000049 const UnallocatedOperand* unalloc = UnallocatedOperand::cast(operand_);
50 requires_reg_ = unalloc->HasRegisterPolicy();
51 register_beneficial_ = !unalloc->HasAnyPolicy();
52 }
53 DCHECK(pos_.IsValid());
54}
55
56
57bool UsePosition::HasHint() const {
Emily Bernierd0a1eb72015-03-24 16:35:39 -040058 return hint_ != nullptr && !hint_->IsUnallocated();
Ben Murdochb8a8cc12014-11-26 15:28:44 +000059}
60
61
62bool UsePosition::RequiresRegister() const { return requires_reg_; }
63
64
65bool UsePosition::RegisterIsBeneficial() const { return register_beneficial_; }
66
67
68void UseInterval::SplitAt(LifetimePosition pos, Zone* zone) {
69 DCHECK(Contains(pos) && pos.Value() != start().Value());
Emily Bernierd0a1eb72015-03-24 16:35:39 -040070 auto after = new (zone) UseInterval(pos, end_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +000071 after->next_ = next_;
72 next_ = after;
73 end_ = pos;
74}
75
76
Emily Bernierd0a1eb72015-03-24 16:35:39 -040077struct LiveRange::SpillAtDefinitionList : ZoneObject {
78 SpillAtDefinitionList(int gap_index, InstructionOperand* operand,
79 SpillAtDefinitionList* next)
80 : gap_index(gap_index), operand(operand), next(next) {}
81 const int gap_index;
82 InstructionOperand* const operand;
83 SpillAtDefinitionList* const next;
84};
85
86
Ben Murdochb8a8cc12014-11-26 15:28:44 +000087#ifdef DEBUG
88
89
90void LiveRange::Verify() const {
91 UsePosition* cur = first_pos_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -040092 while (cur != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000093 DCHECK(Start().Value() <= cur->pos().Value() &&
94 cur->pos().Value() <= End().Value());
95 cur = cur->next();
96 }
97}
98
99
100bool LiveRange::HasOverlap(UseInterval* target) const {
101 UseInterval* current_interval = first_interval_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400102 while (current_interval != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000103 // Intervals overlap if the start of one is contained in the other.
104 if (current_interval->Contains(target->start()) ||
105 target->Contains(current_interval->start())) {
106 return true;
107 }
108 current_interval = current_interval->next();
109 }
110 return false;
111}
112
113
114#endif
115
116
117LiveRange::LiveRange(int id, Zone* zone)
118 : id_(id),
119 spilled_(false),
120 is_phi_(false),
121 is_non_loop_phi_(false),
122 kind_(UNALLOCATED_REGISTERS),
123 assigned_register_(kInvalidAssignment),
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400124 last_interval_(nullptr),
125 first_interval_(nullptr),
126 first_pos_(nullptr),
127 parent_(nullptr),
128 next_(nullptr),
129 current_interval_(nullptr),
130 last_processed_use_(nullptr),
131 current_hint_operand_(nullptr),
132 spill_start_index_(kMaxInt),
133 spill_type_(SpillType::kNoSpillType),
134 spill_operand_(nullptr),
135 spills_at_definition_(nullptr) {}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000136
137
138void LiveRange::set_assigned_register(int reg, Zone* zone) {
139 DCHECK(!HasRegisterAssigned() && !IsSpilled());
140 assigned_register_ = reg;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400141 // TODO(dcarney): stop aliasing hint operands.
142 ConvertUsesToOperand(CreateAssignedOperand(zone));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000143}
144
145
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400146void LiveRange::MakeSpilled() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000147 DCHECK(!IsSpilled());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400148 DCHECK(!TopLevel()->HasNoSpillType());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000149 spilled_ = true;
150 assigned_register_ = kInvalidAssignment;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000151}
152
153
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400154void LiveRange::SpillAtDefinition(Zone* zone, int gap_index,
155 InstructionOperand* operand) {
156 DCHECK(HasNoSpillType());
157 spills_at_definition_ = new (zone)
158 SpillAtDefinitionList(gap_index, operand, spills_at_definition_);
159}
160
161
162void LiveRange::CommitSpillsAtDefinition(InstructionSequence* sequence,
163 InstructionOperand* op) {
164 auto to_spill = TopLevel()->spills_at_definition_;
165 if (to_spill == nullptr) return;
166 auto zone = sequence->zone();
167 for (; to_spill != nullptr; to_spill = to_spill->next) {
168 auto gap = sequence->GapAt(to_spill->gap_index);
169 auto move = gap->GetOrCreateParallelMove(GapInstruction::START, zone);
170 move->AddMove(to_spill->operand, op, zone);
171 }
172 TopLevel()->spills_at_definition_ = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000173}
174
175
176void LiveRange::SetSpillOperand(InstructionOperand* operand) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400177 DCHECK(HasNoSpillType());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000178 DCHECK(!operand->IsUnallocated());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400179 spill_type_ = SpillType::kSpillOperand;
180 spill_operand_ = operand;
181}
182
183
184void LiveRange::SetSpillRange(SpillRange* spill_range) {
185 DCHECK(HasNoSpillType() || HasSpillRange());
186 DCHECK_NE(spill_range, nullptr);
187 spill_type_ = SpillType::kSpillRange;
188 spill_range_ = spill_range;
189}
190
191
192void LiveRange::CommitSpillOperand(InstructionOperand* operand) {
193 DCHECK(HasSpillRange());
194 DCHECK(!operand->IsUnallocated());
195 DCHECK(!IsChild());
196 spill_type_ = SpillType::kSpillOperand;
197 spill_operand_ = operand;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000198}
199
200
201UsePosition* LiveRange::NextUsePosition(LifetimePosition start) {
202 UsePosition* use_pos = last_processed_use_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400203 if (use_pos == nullptr) use_pos = first_pos();
204 while (use_pos != nullptr && use_pos->pos().Value() < start.Value()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000205 use_pos = use_pos->next();
206 }
207 last_processed_use_ = use_pos;
208 return use_pos;
209}
210
211
212UsePosition* LiveRange::NextUsePositionRegisterIsBeneficial(
213 LifetimePosition start) {
214 UsePosition* pos = NextUsePosition(start);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400215 while (pos != nullptr && !pos->RegisterIsBeneficial()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000216 pos = pos->next();
217 }
218 return pos;
219}
220
221
222UsePosition* LiveRange::PreviousUsePositionRegisterIsBeneficial(
223 LifetimePosition start) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400224 auto pos = first_pos();
225 UsePosition* prev = nullptr;
226 while (pos != nullptr && pos->pos().Value() < start.Value()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000227 if (pos->RegisterIsBeneficial()) prev = pos;
228 pos = pos->next();
229 }
230 return prev;
231}
232
233
234UsePosition* LiveRange::NextRegisterPosition(LifetimePosition start) {
235 UsePosition* pos = NextUsePosition(start);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400236 while (pos != nullptr && !pos->RequiresRegister()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000237 pos = pos->next();
238 }
239 return pos;
240}
241
242
243bool LiveRange::CanBeSpilled(LifetimePosition pos) {
244 // We cannot spill a live range that has a use requiring a register
245 // at the current or the immediate next position.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400246 auto use_pos = NextRegisterPosition(pos);
247 if (use_pos == nullptr) return true;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000248 return use_pos->pos().Value() >
249 pos.NextInstruction().InstructionEnd().Value();
250}
251
252
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400253InstructionOperand* LiveRange::CreateAssignedOperand(Zone* zone) const {
254 InstructionOperand* op = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000255 if (HasRegisterAssigned()) {
256 DCHECK(!IsSpilled());
257 switch (Kind()) {
258 case GENERAL_REGISTERS:
259 op = RegisterOperand::Create(assigned_register(), zone);
260 break;
261 case DOUBLE_REGISTERS:
262 op = DoubleRegisterOperand::Create(assigned_register(), zone);
263 break;
264 default:
265 UNREACHABLE();
266 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400267 } else {
268 DCHECK(IsSpilled());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000269 DCHECK(!HasRegisterAssigned());
270 op = TopLevel()->GetSpillOperand();
271 DCHECK(!op->IsUnallocated());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000272 }
273 return op;
274}
275
276
277UseInterval* LiveRange::FirstSearchIntervalForPosition(
278 LifetimePosition position) const {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400279 if (current_interval_ == nullptr) return first_interval_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000280 if (current_interval_->start().Value() > position.Value()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400281 current_interval_ = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000282 return first_interval_;
283 }
284 return current_interval_;
285}
286
287
288void LiveRange::AdvanceLastProcessedMarker(
289 UseInterval* to_start_of, LifetimePosition but_not_past) const {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400290 if (to_start_of == nullptr) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000291 if (to_start_of->start().Value() > but_not_past.Value()) return;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400292 auto start = current_interval_ == nullptr ? LifetimePosition::Invalid()
293 : current_interval_->start();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000294 if (to_start_of->start().Value() > start.Value()) {
295 current_interval_ = to_start_of;
296 }
297}
298
299
300void LiveRange::SplitAt(LifetimePosition position, LiveRange* result,
301 Zone* zone) {
302 DCHECK(Start().Value() < position.Value());
303 DCHECK(result->IsEmpty());
304 // Find the last interval that ends before the position. If the
305 // position is contained in one of the intervals in the chain, we
306 // split that interval and use the first part.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400307 auto current = FirstSearchIntervalForPosition(position);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000308
309 // If the split position coincides with the beginning of a use interval
310 // we need to split use positons in a special way.
311 bool split_at_start = false;
312
313 if (current->start().Value() == position.Value()) {
314 // When splitting at start we need to locate the previous use interval.
315 current = first_interval_;
316 }
317
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400318 while (current != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000319 if (current->Contains(position)) {
320 current->SplitAt(position, zone);
321 break;
322 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400323 auto next = current->next();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000324 if (next->start().Value() >= position.Value()) {
325 split_at_start = (next->start().Value() == position.Value());
326 break;
327 }
328 current = next;
329 }
330
331 // Partition original use intervals to the two live ranges.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400332 auto before = current;
333 auto after = before->next();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000334 result->last_interval_ =
335 (last_interval_ == before)
336 ? after // Only interval in the range after split.
337 : last_interval_; // Last interval of the original range.
338 result->first_interval_ = after;
339 last_interval_ = before;
340
341 // Find the last use position before the split and the first use
342 // position after it.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400343 auto use_after = first_pos_;
344 UsePosition* use_before = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000345 if (split_at_start) {
346 // The split position coincides with the beginning of a use interval (the
347 // end of a lifetime hole). Use at this position should be attributed to
348 // the split child because split child owns use interval covering it.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400349 while (use_after != nullptr &&
350 use_after->pos().Value() < position.Value()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000351 use_before = use_after;
352 use_after = use_after->next();
353 }
354 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400355 while (use_after != nullptr &&
356 use_after->pos().Value() <= position.Value()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000357 use_before = use_after;
358 use_after = use_after->next();
359 }
360 }
361
362 // Partition original use positions to the two live ranges.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400363 if (use_before != nullptr) {
364 use_before->next_ = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000365 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400366 first_pos_ = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000367 }
368 result->first_pos_ = use_after;
369
370 // Discard cached iteration state. It might be pointing
371 // to the use that no longer belongs to this live range.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400372 last_processed_use_ = nullptr;
373 current_interval_ = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000374
375 // Link the new live range in the chain before any of the other
376 // ranges linked from the range before the split.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400377 result->parent_ = (parent_ == nullptr) ? this : parent_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000378 result->kind_ = result->parent_->kind_;
379 result->next_ = next_;
380 next_ = result;
381
382#ifdef DEBUG
383 Verify();
384 result->Verify();
385#endif
386}
387
388
389// This implements an ordering on live ranges so that they are ordered by their
390// start positions. This is needed for the correctness of the register
391// allocation algorithm. If two live ranges start at the same offset then there
392// is a tie breaker based on where the value is first used. This part of the
393// ordering is merely a heuristic.
394bool LiveRange::ShouldBeAllocatedBefore(const LiveRange* other) const {
395 LifetimePosition start = Start();
396 LifetimePosition other_start = other->Start();
397 if (start.Value() == other_start.Value()) {
398 UsePosition* pos = first_pos();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400399 if (pos == nullptr) return false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000400 UsePosition* other_pos = other->first_pos();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400401 if (other_pos == nullptr) return true;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000402 return pos->pos().Value() < other_pos->pos().Value();
403 }
404 return start.Value() < other_start.Value();
405}
406
407
408void LiveRange::ShortenTo(LifetimePosition start) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400409 TraceAlloc("Shorten live range %d to [%d\n", id_, start.Value());
410 DCHECK(first_interval_ != nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000411 DCHECK(first_interval_->start().Value() <= start.Value());
412 DCHECK(start.Value() < first_interval_->end().Value());
413 first_interval_->set_start(start);
414}
415
416
417void LiveRange::EnsureInterval(LifetimePosition start, LifetimePosition end,
418 Zone* zone) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400419 TraceAlloc("Ensure live range %d in interval [%d %d[\n", id_, start.Value(),
420 end.Value());
421 auto new_end = end;
422 while (first_interval_ != nullptr &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000423 first_interval_->start().Value() <= end.Value()) {
424 if (first_interval_->end().Value() > end.Value()) {
425 new_end = first_interval_->end();
426 }
427 first_interval_ = first_interval_->next();
428 }
429
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400430 auto new_interval = new (zone) UseInterval(start, new_end);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000431 new_interval->next_ = first_interval_;
432 first_interval_ = new_interval;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400433 if (new_interval->next() == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000434 last_interval_ = new_interval;
435 }
436}
437
438
439void LiveRange::AddUseInterval(LifetimePosition start, LifetimePosition end,
440 Zone* zone) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400441 TraceAlloc("Add to live range %d interval [%d %d[\n", id_, start.Value(),
442 end.Value());
443 if (first_interval_ == nullptr) {
444 auto interval = new (zone) UseInterval(start, end);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000445 first_interval_ = interval;
446 last_interval_ = interval;
447 } else {
448 if (end.Value() == first_interval_->start().Value()) {
449 first_interval_->set_start(start);
450 } else if (end.Value() < first_interval_->start().Value()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400451 auto interval = new (zone) UseInterval(start, end);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000452 interval->set_next(first_interval_);
453 first_interval_ = interval;
454 } else {
455 // Order of instruction's processing (see ProcessInstructions) guarantees
456 // that each new use interval either precedes or intersects with
457 // last added interval.
458 DCHECK(start.Value() < first_interval_->end().Value());
459 first_interval_->start_ = Min(start, first_interval_->start_);
460 first_interval_->end_ = Max(end, first_interval_->end_);
461 }
462 }
463}
464
465
466void LiveRange::AddUsePosition(LifetimePosition pos,
467 InstructionOperand* operand,
468 InstructionOperand* hint, Zone* zone) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400469 TraceAlloc("Add to live range %d use position %d\n", id_, pos.Value());
470 auto use_pos = new (zone) UsePosition(pos, operand, hint);
471 UsePosition* prev_hint = nullptr;
472 UsePosition* prev = nullptr;
473 auto current = first_pos_;
474 while (current != nullptr && current->pos().Value() < pos.Value()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000475 prev_hint = current->HasHint() ? current : prev_hint;
476 prev = current;
477 current = current->next();
478 }
479
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400480 if (prev == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000481 use_pos->set_next(first_pos_);
482 first_pos_ = use_pos;
483 } else {
484 use_pos->next_ = prev->next_;
485 prev->next_ = use_pos;
486 }
487
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400488 if (prev_hint == nullptr && use_pos->HasHint()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000489 current_hint_operand_ = hint;
490 }
491}
492
493
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400494void LiveRange::ConvertUsesToOperand(InstructionOperand* op) {
495 auto use_pos = first_pos();
496 while (use_pos != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000497 DCHECK(Start().Value() <= use_pos->pos().Value() &&
498 use_pos->pos().Value() <= End().Value());
499
500 if (use_pos->HasOperand()) {
501 DCHECK(op->IsRegister() || op->IsDoubleRegister() ||
502 !use_pos->RequiresRegister());
503 use_pos->operand()->ConvertTo(op->kind(), op->index());
504 }
505 use_pos = use_pos->next();
506 }
507}
508
509
510bool LiveRange::CanCover(LifetimePosition position) const {
511 if (IsEmpty()) return false;
512 return Start().Value() <= position.Value() &&
513 position.Value() < End().Value();
514}
515
516
517bool LiveRange::Covers(LifetimePosition position) {
518 if (!CanCover(position)) return false;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400519 auto start_search = FirstSearchIntervalForPosition(position);
520 for (auto interval = start_search; interval != nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000521 interval = interval->next()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400522 DCHECK(interval->next() == nullptr ||
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000523 interval->next()->start().Value() >= interval->start().Value());
524 AdvanceLastProcessedMarker(interval, position);
525 if (interval->Contains(position)) return true;
526 if (interval->start().Value() > position.Value()) return false;
527 }
528 return false;
529}
530
531
532LifetimePosition LiveRange::FirstIntersection(LiveRange* other) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400533 auto b = other->first_interval();
534 if (b == nullptr) return LifetimePosition::Invalid();
535 auto advance_last_processed_up_to = b->start();
536 auto a = FirstSearchIntervalForPosition(b->start());
537 while (a != nullptr && b != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000538 if (a->start().Value() > other->End().Value()) break;
539 if (b->start().Value() > End().Value()) break;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400540 auto cur_intersection = a->Intersect(b);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000541 if (cur_intersection.IsValid()) {
542 return cur_intersection;
543 }
544 if (a->start().Value() < b->start().Value()) {
545 a = a->next();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400546 if (a == nullptr || a->start().Value() > other->End().Value()) break;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000547 AdvanceLastProcessedMarker(a, advance_last_processed_up_to);
548 } else {
549 b = b->next();
550 }
551 }
552 return LifetimePosition::Invalid();
553}
554
555
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400556RegisterAllocator::RegisterAllocator(const RegisterConfiguration* config,
557 Zone* zone, Frame* frame,
558 InstructionSequence* code,
559 const char* debug_name)
560 : local_zone_(zone),
561 frame_(frame),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000562 code_(code),
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400563 debug_name_(debug_name),
564 config_(config),
565 phi_map_(PhiMap::key_compare(), PhiMap::allocator_type(local_zone())),
566 live_in_sets_(code->InstructionBlockCount(), nullptr, local_zone()),
567 live_ranges_(code->VirtualRegisterCount() * 2, nullptr, local_zone()),
568 fixed_live_ranges_(this->config()->num_general_registers(), nullptr,
569 local_zone()),
570 fixed_double_live_ranges_(this->config()->num_double_registers(), nullptr,
571 local_zone()),
572 unhandled_live_ranges_(local_zone()),
573 active_live_ranges_(local_zone()),
574 inactive_live_ranges_(local_zone()),
575 reusable_slots_(local_zone()),
576 spill_ranges_(local_zone()),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000577 mode_(UNALLOCATED_REGISTERS),
578 num_registers_(-1),
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400579 allocation_ok_(true) {
580 DCHECK(this->config()->num_general_registers() <=
581 RegisterConfiguration::kMaxGeneralRegisters);
582 DCHECK(this->config()->num_double_registers() <=
583 RegisterConfiguration::kMaxDoubleRegisters);
584 // TryAllocateFreeReg and AllocateBlockedReg assume this
585 // when allocating local arrays.
586 DCHECK(RegisterConfiguration::kMaxDoubleRegisters >=
587 this->config()->num_general_registers());
588 unhandled_live_ranges().reserve(
589 static_cast<size_t>(code->VirtualRegisterCount() * 2));
590 active_live_ranges().reserve(8);
591 inactive_live_ranges().reserve(8);
592 reusable_slots().reserve(8);
593 spill_ranges().reserve(8);
594 assigned_registers_ =
595 new (code_zone()) BitVector(config->num_general_registers(), code_zone());
596 assigned_double_registers_ = new (code_zone())
597 BitVector(config->num_aliased_double_registers(), code_zone());
598 frame->SetAllocatedRegisters(assigned_registers_);
599 frame->SetAllocatedDoubleRegisters(assigned_double_registers_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000600}
601
602
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400603BitVector* RegisterAllocator::ComputeLiveOut(const InstructionBlock* block) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000604 // Compute live out for the given block, except not including backward
605 // successor edges.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400606 auto live_out = new (local_zone())
607 BitVector(code()->VirtualRegisterCount(), local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000608
609 // Process all successor blocks.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400610 for (auto succ : block->successors()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000611 // Add values live on entry to the successor. Note the successor's
612 // live_in will not be computed yet for backwards edges.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400613 auto live_in = live_in_sets_[succ.ToSize()];
614 if (live_in != nullptr) live_out->Union(*live_in);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000615
616 // All phi input operands corresponding to this successor edge are live
617 // out from this block.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400618 auto successor = code()->InstructionBlockAt(succ);
619 size_t index = successor->PredecessorIndexOf(block->rpo_number());
620 DCHECK(index < successor->PredecessorCount());
621 for (auto phi : successor->phis()) {
622 live_out->Add(phi->operands()[index]);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000623 }
624 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000625 return live_out;
626}
627
628
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400629void RegisterAllocator::AddInitialIntervals(const InstructionBlock* block,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000630 BitVector* live_out) {
631 // Add an interval that includes the entire block to the live range for
632 // each live_out value.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400633 auto start =
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000634 LifetimePosition::FromInstructionIndex(block->first_instruction_index());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400635 auto end = LifetimePosition::FromInstructionIndex(
636 block->last_instruction_index()).NextInstruction();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000637 BitVector::Iterator iterator(live_out);
638 while (!iterator.Done()) {
639 int operand_index = iterator.Current();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400640 auto range = LiveRangeFor(operand_index);
641 range->AddUseInterval(start, end, local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000642 iterator.Advance();
643 }
644}
645
646
647int RegisterAllocator::FixedDoubleLiveRangeID(int index) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400648 return -index - 1 - config()->num_general_registers();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000649}
650
651
652InstructionOperand* RegisterAllocator::AllocateFixed(
653 UnallocatedOperand* operand, int pos, bool is_tagged) {
654 TraceAlloc("Allocating fixed reg for op %d\n", operand->virtual_register());
655 DCHECK(operand->HasFixedPolicy());
656 if (operand->HasFixedSlotPolicy()) {
657 operand->ConvertTo(InstructionOperand::STACK_SLOT,
658 operand->fixed_slot_index());
659 } else if (operand->HasFixedRegisterPolicy()) {
660 int reg_index = operand->fixed_register_index();
661 operand->ConvertTo(InstructionOperand::REGISTER, reg_index);
662 } else if (operand->HasFixedDoubleRegisterPolicy()) {
663 int reg_index = operand->fixed_register_index();
664 operand->ConvertTo(InstructionOperand::DOUBLE_REGISTER, reg_index);
665 } else {
666 UNREACHABLE();
667 }
668 if (is_tagged) {
669 TraceAlloc("Fixed reg is tagged at %d\n", pos);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400670 auto instr = InstructionAt(pos);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000671 if (instr->HasPointerMap()) {
672 instr->pointer_map()->RecordPointer(operand, code_zone());
673 }
674 }
675 return operand;
676}
677
678
679LiveRange* RegisterAllocator::FixedLiveRangeFor(int index) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400680 DCHECK(index < config()->num_general_registers());
681 auto result = fixed_live_ranges()[index];
682 if (result == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000683 // TODO(titzer): add a utility method to allocate a new LiveRange:
684 // The LiveRange object itself can go in this zone, but the
685 // InstructionOperand needs
686 // to go in the code zone, since it may survive register allocation.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400687 result = new (local_zone()) LiveRange(FixedLiveRangeID(index), code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000688 DCHECK(result->IsFixed());
689 result->kind_ = GENERAL_REGISTERS;
690 SetLiveRangeAssignedRegister(result, index);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400691 fixed_live_ranges()[index] = result;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000692 }
693 return result;
694}
695
696
697LiveRange* RegisterAllocator::FixedDoubleLiveRangeFor(int index) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400698 DCHECK(index < config()->num_aliased_double_registers());
699 auto result = fixed_double_live_ranges()[index];
700 if (result == nullptr) {
701 result = new (local_zone())
702 LiveRange(FixedDoubleLiveRangeID(index), code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000703 DCHECK(result->IsFixed());
704 result->kind_ = DOUBLE_REGISTERS;
705 SetLiveRangeAssignedRegister(result, index);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400706 fixed_double_live_ranges()[index] = result;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000707 }
708 return result;
709}
710
711
712LiveRange* RegisterAllocator::LiveRangeFor(int index) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400713 if (index >= static_cast<int>(live_ranges().size())) {
714 live_ranges().resize(index + 1, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000715 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400716 auto result = live_ranges()[index];
717 if (result == nullptr) {
718 result = new (local_zone()) LiveRange(index, code_zone());
719 live_ranges()[index] = result;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000720 }
721 return result;
722}
723
724
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400725GapInstruction* RegisterAllocator::GetLastGap(const InstructionBlock* block) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000726 int last_instruction = block->last_instruction_index();
727 return code()->GapAt(last_instruction - 1);
728}
729
730
731LiveRange* RegisterAllocator::LiveRangeFor(InstructionOperand* operand) {
732 if (operand->IsUnallocated()) {
733 return LiveRangeFor(UnallocatedOperand::cast(operand)->virtual_register());
734 } else if (operand->IsRegister()) {
735 return FixedLiveRangeFor(operand->index());
736 } else if (operand->IsDoubleRegister()) {
737 return FixedDoubleLiveRangeFor(operand->index());
738 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400739 return nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000740 }
741}
742
743
744void RegisterAllocator::Define(LifetimePosition position,
745 InstructionOperand* operand,
746 InstructionOperand* hint) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400747 auto range = LiveRangeFor(operand);
748 if (range == nullptr) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000749
750 if (range->IsEmpty() || range->Start().Value() > position.Value()) {
751 // Can happen if there is a definition without use.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400752 range->AddUseInterval(position, position.NextInstruction(), local_zone());
753 range->AddUsePosition(position.NextInstruction(), nullptr, nullptr,
754 local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000755 } else {
756 range->ShortenTo(position);
757 }
758
759 if (operand->IsUnallocated()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400760 auto unalloc_operand = UnallocatedOperand::cast(operand);
761 range->AddUsePosition(position, unalloc_operand, hint, local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000762 }
763}
764
765
766void RegisterAllocator::Use(LifetimePosition block_start,
767 LifetimePosition position,
768 InstructionOperand* operand,
769 InstructionOperand* hint) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400770 auto range = LiveRangeFor(operand);
771 if (range == nullptr) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000772 if (operand->IsUnallocated()) {
773 UnallocatedOperand* unalloc_operand = UnallocatedOperand::cast(operand);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400774 range->AddUsePosition(position, unalloc_operand, hint, local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000775 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400776 range->AddUseInterval(block_start, position, local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000777}
778
779
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400780void RegisterAllocator::AddGapMove(int index,
781 GapInstruction::InnerPosition position,
782 InstructionOperand* from,
783 InstructionOperand* to) {
784 auto gap = code()->GapAt(index);
785 auto move = gap->GetOrCreateParallelMove(position, code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000786 move->AddMove(from, to, code_zone());
787}
788
789
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400790static bool AreUseIntervalsIntersecting(UseInterval* interval1,
791 UseInterval* interval2) {
792 while (interval1 != nullptr && interval2 != nullptr) {
793 if (interval1->start().Value() < interval2->start().Value()) {
794 if (interval1->end().Value() > interval2->start().Value()) {
795 return true;
796 }
797 interval1 = interval1->next();
798 } else {
799 if (interval2->end().Value() > interval1->start().Value()) {
800 return true;
801 }
802 interval2 = interval2->next();
803 }
804 }
805 return false;
806}
807
808
809SpillRange::SpillRange(LiveRange* range, Zone* zone) : live_ranges_(zone) {
810 auto src = range->first_interval();
811 UseInterval* result = nullptr;
812 UseInterval* node = nullptr;
813 // Copy the nodes
814 while (src != nullptr) {
815 auto new_node = new (zone) UseInterval(src->start(), src->end());
816 if (result == nullptr) {
817 result = new_node;
818 } else {
819 node->set_next(new_node);
820 }
821 node = new_node;
822 src = src->next();
823 }
824 use_interval_ = result;
825 live_ranges().push_back(range);
826 end_position_ = node->end();
827 DCHECK(!range->HasSpillRange());
828 range->SetSpillRange(this);
829}
830
831
832bool SpillRange::IsIntersectingWith(SpillRange* other) const {
833 if (this->use_interval_ == nullptr || other->use_interval_ == nullptr ||
834 this->End().Value() <= other->use_interval_->start().Value() ||
835 other->End().Value() <= this->use_interval_->start().Value()) {
836 return false;
837 }
838 return AreUseIntervalsIntersecting(use_interval_, other->use_interval_);
839}
840
841
842bool SpillRange::TryMerge(SpillRange* other) {
843 if (Kind() != other->Kind() || IsIntersectingWith(other)) return false;
844
845 auto max = LifetimePosition::MaxPosition();
846 if (End().Value() < other->End().Value() &&
847 other->End().Value() != max.Value()) {
848 end_position_ = other->End();
849 }
850 other->end_position_ = max;
851
852 MergeDisjointIntervals(other->use_interval_);
853 other->use_interval_ = nullptr;
854
855 for (auto range : other->live_ranges()) {
856 DCHECK(range->GetSpillRange() == other);
857 range->SetSpillRange(this);
858 }
859
860 live_ranges().insert(live_ranges().end(), other->live_ranges().begin(),
861 other->live_ranges().end());
862 other->live_ranges().clear();
863
864 return true;
865}
866
867
868void SpillRange::SetOperand(InstructionOperand* op) {
869 for (auto range : live_ranges()) {
870 DCHECK(range->GetSpillRange() == this);
871 range->CommitSpillOperand(op);
872 }
873}
874
875
876void SpillRange::MergeDisjointIntervals(UseInterval* other) {
877 UseInterval* tail = nullptr;
878 auto current = use_interval_;
879 while (other != nullptr) {
880 // Make sure the 'current' list starts first
881 if (current == nullptr ||
882 current->start().Value() > other->start().Value()) {
883 std::swap(current, other);
884 }
885 // Check disjointness
886 DCHECK(other == nullptr ||
887 current->end().Value() <= other->start().Value());
888 // Append the 'current' node to the result accumulator and move forward
889 if (tail == nullptr) {
890 use_interval_ = current;
891 } else {
892 tail->set_next(current);
893 }
894 tail = current;
895 current = current->next();
896 }
897 // Other list is empty => we are done
898}
899
900
901void RegisterAllocator::ReuseSpillSlots() {
902 DCHECK(FLAG_turbo_reuse_spill_slots);
903
904 // Merge disjoint spill ranges
905 for (size_t i = 0; i < spill_ranges().size(); i++) {
906 auto range = spill_ranges()[i];
907 if (range->IsEmpty()) continue;
908 for (size_t j = i + 1; j < spill_ranges().size(); j++) {
909 auto other = spill_ranges()[j];
910 if (!other->IsEmpty()) {
911 range->TryMerge(other);
912 }
913 }
914 }
915
916 // Allocate slots for the merged spill ranges.
917 for (auto range : spill_ranges()) {
918 if (range->IsEmpty()) continue;
919 // Allocate a new operand referring to the spill slot.
920 auto kind = range->Kind();
921 int index = frame()->AllocateSpillSlot(kind == DOUBLE_REGISTERS);
922 auto op_kind = kind == DOUBLE_REGISTERS
923 ? InstructionOperand::DOUBLE_STACK_SLOT
924 : InstructionOperand::STACK_SLOT;
925 auto op = new (code_zone()) InstructionOperand(op_kind, index);
926 range->SetOperand(op);
927 }
928}
929
930
931void RegisterAllocator::CommitAssignment() {
932 for (auto range : live_ranges()) {
933 if (range == nullptr || range->IsEmpty()) continue;
934 // Register assignments were committed in set_assigned_register.
935 if (range->HasRegisterAssigned()) continue;
936 auto assigned = range->CreateAssignedOperand(code_zone());
937 range->ConvertUsesToOperand(assigned);
938 if (range->IsSpilled()) {
939 range->CommitSpillsAtDefinition(code(), assigned);
940 }
941 }
942}
943
944
945SpillRange* RegisterAllocator::AssignSpillRangeToLiveRange(LiveRange* range) {
946 DCHECK(FLAG_turbo_reuse_spill_slots);
947 auto spill_range = new (local_zone()) SpillRange(range, local_zone());
948 spill_ranges().push_back(spill_range);
949 return spill_range;
950}
951
952
953bool RegisterAllocator::TryReuseSpillForPhi(LiveRange* range) {
954 DCHECK(FLAG_turbo_reuse_spill_slots);
955 if (range->IsChild() || !range->is_phi()) return false;
956 DCHECK(range->HasNoSpillType());
957
958 auto lookup = phi_map_.find(range->id());
959 DCHECK(lookup != phi_map_.end());
960 auto phi = lookup->second.phi;
961 auto block = lookup->second.block;
962 // Count the number of spilled operands.
963 size_t spilled_count = 0;
964 LiveRange* first_op = nullptr;
965 for (size_t i = 0; i < phi->operands().size(); i++) {
966 int op = phi->operands()[i];
967 LiveRange* op_range = LiveRangeFor(op);
968 if (op_range->GetSpillRange() == nullptr) continue;
969 auto pred = code()->InstructionBlockAt(block->predecessors()[i]);
970 auto pred_end =
971 LifetimePosition::FromInstructionIndex(pred->last_instruction_index());
972 while (op_range != nullptr && !op_range->CanCover(pred_end)) {
973 op_range = op_range->next();
974 }
975 if (op_range != nullptr && op_range->IsSpilled()) {
976 spilled_count++;
977 if (first_op == nullptr) {
978 first_op = op_range->TopLevel();
979 }
980 }
981 }
982
983 // Only continue if more than half of the operands are spilled.
984 if (spilled_count * 2 <= phi->operands().size()) {
985 return false;
986 }
987
988 // Try to merge the spilled operands and count the number of merged spilled
989 // operands.
990 DCHECK(first_op != nullptr);
991 auto first_op_spill = first_op->GetSpillRange();
992 size_t num_merged = 1;
993 for (size_t i = 1; i < phi->operands().size(); i++) {
994 int op = phi->operands()[i];
995 auto op_range = LiveRangeFor(op);
996 auto op_spill = op_range->GetSpillRange();
997 if (op_spill != nullptr &&
998 (op_spill == first_op_spill || first_op_spill->TryMerge(op_spill))) {
999 num_merged++;
1000 }
1001 }
1002
1003 // Only continue if enough operands could be merged to the
1004 // same spill slot.
1005 if (num_merged * 2 <= phi->operands().size() ||
1006 AreUseIntervalsIntersecting(first_op_spill->interval(),
1007 range->first_interval())) {
1008 return false;
1009 }
1010
1011 // If the range does not need register soon, spill it to the merged
1012 // spill range.
1013 auto next_pos = range->Start();
1014 if (code()->IsGapAt(next_pos.InstructionIndex())) {
1015 next_pos = next_pos.NextInstruction();
1016 }
1017 auto pos = range->NextUsePositionRegisterIsBeneficial(next_pos);
1018 if (pos == nullptr) {
1019 auto spill_range = AssignSpillRangeToLiveRange(range->TopLevel());
1020 CHECK(first_op_spill->TryMerge(spill_range));
1021 Spill(range);
1022 return true;
1023 } else if (pos->pos().Value() > range->Start().NextInstruction().Value()) {
1024 auto spill_range = AssignSpillRangeToLiveRange(range->TopLevel());
1025 CHECK(first_op_spill->TryMerge(spill_range));
1026 SpillBetween(range, range->Start(), pos->pos());
1027 if (!AllocationOk()) return false;
1028 DCHECK(UnhandledIsSorted());
1029 return true;
1030 }
1031 return false;
1032}
1033
1034
1035void RegisterAllocator::MeetRegisterConstraints(const InstructionBlock* block) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001036 int start = block->first_instruction_index();
1037 int end = block->last_instruction_index();
1038 DCHECK_NE(-1, start);
1039 for (int i = start; i <= end; ++i) {
1040 if (code()->IsGapAt(i)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001041 Instruction* instr = nullptr;
1042 Instruction* prev_instr = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001043 if (i < end) instr = InstructionAt(i + 1);
1044 if (i > start) prev_instr = InstructionAt(i - 1);
1045 MeetConstraintsBetween(prev_instr, instr, i);
1046 if (!AllocationOk()) return;
1047 }
1048 }
1049
1050 // Meet register constraints for the instruction in the end.
1051 if (!code()->IsGapAt(end)) {
1052 MeetRegisterConstraintsForLastInstructionInBlock(block);
1053 }
1054}
1055
1056
1057void RegisterAllocator::MeetRegisterConstraintsForLastInstructionInBlock(
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001058 const InstructionBlock* block) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001059 int end = block->last_instruction_index();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001060 auto last_instruction = InstructionAt(end);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001061 for (size_t i = 0; i < last_instruction->OutputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001062 auto output_operand = last_instruction->OutputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001063 DCHECK(!output_operand->IsConstant());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001064 auto output = UnallocatedOperand::cast(output_operand);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001065 int output_vreg = output->virtual_register();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001066 auto range = LiveRangeFor(output_vreg);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001067 bool assigned = false;
1068 if (output->HasFixedPolicy()) {
1069 AllocateFixed(output, -1, false);
1070 // This value is produced on the stack, we never need to spill it.
1071 if (output->IsStackSlot()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001072 DCHECK(output->index() < 0);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001073 range->SetSpillOperand(output);
1074 range->SetSpillStartIndex(end);
1075 assigned = true;
1076 }
1077
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001078 for (auto succ : block->successors()) {
1079 const InstructionBlock* successor = code()->InstructionBlockAt(succ);
1080 DCHECK(successor->PredecessorCount() == 1);
1081 int gap_index = successor->first_instruction_index() + 1;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001082 DCHECK(code()->IsGapAt(gap_index));
1083
1084 // Create an unconstrained operand for the same virtual register
1085 // and insert a gap move from the fixed output to the operand.
1086 UnallocatedOperand* output_copy =
1087 new (code_zone()) UnallocatedOperand(UnallocatedOperand::ANY);
1088 output_copy->set_virtual_register(output_vreg);
1089
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001090 AddGapMove(gap_index, GapInstruction::START, output, output_copy);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001091 }
1092 }
1093
1094 if (!assigned) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001095 for (auto succ : block->successors()) {
1096 const InstructionBlock* successor = code()->InstructionBlockAt(succ);
1097 DCHECK(successor->PredecessorCount() == 1);
1098 int gap_index = successor->first_instruction_index() + 1;
1099 range->SpillAtDefinition(local_zone(), gap_index, output);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001100 range->SetSpillStartIndex(gap_index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001101 }
1102 }
1103 }
1104}
1105
1106
1107void RegisterAllocator::MeetConstraintsBetween(Instruction* first,
1108 Instruction* second,
1109 int gap_index) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001110 if (first != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001111 // Handle fixed temporaries.
1112 for (size_t i = 0; i < first->TempCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001113 auto temp = UnallocatedOperand::cast(first->TempAt(i));
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001114 if (temp->HasFixedPolicy()) {
1115 AllocateFixed(temp, gap_index - 1, false);
1116 }
1117 }
1118
1119 // Handle constant/fixed output operands.
1120 for (size_t i = 0; i < first->OutputCount(); i++) {
1121 InstructionOperand* output = first->OutputAt(i);
1122 if (output->IsConstant()) {
1123 int output_vreg = output->index();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001124 auto range = LiveRangeFor(output_vreg);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001125 range->SetSpillStartIndex(gap_index - 1);
1126 range->SetSpillOperand(output);
1127 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001128 auto first_output = UnallocatedOperand::cast(output);
1129 auto range = LiveRangeFor(first_output->virtual_register());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001130 bool assigned = false;
1131 if (first_output->HasFixedPolicy()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001132 auto output_copy = first_output->CopyUnconstrained(code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001133 bool is_tagged = HasTaggedValue(first_output->virtual_register());
1134 AllocateFixed(first_output, gap_index, is_tagged);
1135
1136 // This value is produced on the stack, we never need to spill it.
1137 if (first_output->IsStackSlot()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001138 DCHECK(first_output->index() < 0);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001139 range->SetSpillOperand(first_output);
1140 range->SetSpillStartIndex(gap_index - 1);
1141 assigned = true;
1142 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001143 AddGapMove(gap_index, GapInstruction::START, first_output,
1144 output_copy);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001145 }
1146
1147 // Make sure we add a gap move for spilling (if we have not done
1148 // so already).
1149 if (!assigned) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001150 range->SpillAtDefinition(local_zone(), gap_index, first_output);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001151 range->SetSpillStartIndex(gap_index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001152 }
1153 }
1154 }
1155 }
1156
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001157 if (second != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001158 // Handle fixed input operands of second instruction.
1159 for (size_t i = 0; i < second->InputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001160 auto input = second->InputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001161 if (input->IsImmediate()) continue; // Ignore immediates.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001162 auto cur_input = UnallocatedOperand::cast(input);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001163 if (cur_input->HasFixedPolicy()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001164 auto input_copy = cur_input->CopyUnconstrained(code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001165 bool is_tagged = HasTaggedValue(cur_input->virtual_register());
1166 AllocateFixed(cur_input, gap_index + 1, is_tagged);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001167 AddGapMove(gap_index, GapInstruction::END, input_copy, cur_input);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001168 }
1169 }
1170
1171 // Handle "output same as input" for second instruction.
1172 for (size_t i = 0; i < second->OutputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001173 auto output = second->OutputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001174 if (!output->IsUnallocated()) continue;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001175 auto second_output = UnallocatedOperand::cast(output);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001176 if (second_output->HasSameAsInputPolicy()) {
1177 DCHECK(i == 0); // Only valid for first output.
1178 UnallocatedOperand* cur_input =
1179 UnallocatedOperand::cast(second->InputAt(0));
1180 int output_vreg = second_output->virtual_register();
1181 int input_vreg = cur_input->virtual_register();
1182
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001183 auto input_copy = cur_input->CopyUnconstrained(code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001184 cur_input->set_virtual_register(second_output->virtual_register());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001185 AddGapMove(gap_index, GapInstruction::END, input_copy, cur_input);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001186
1187 if (HasTaggedValue(input_vreg) && !HasTaggedValue(output_vreg)) {
1188 int index = gap_index + 1;
1189 Instruction* instr = InstructionAt(index);
1190 if (instr->HasPointerMap()) {
1191 instr->pointer_map()->RecordPointer(input_copy, code_zone());
1192 }
1193 } else if (!HasTaggedValue(input_vreg) && HasTaggedValue(output_vreg)) {
1194 // The input is assumed to immediately have a tagged representation,
1195 // before the pointer map can be used. I.e. the pointer map at the
1196 // instruction will include the output operand (whose value at the
1197 // beginning of the instruction is equal to the input operand). If
1198 // this is not desired, then the pointer map at this instruction needs
1199 // to be adjusted manually.
1200 }
1201 }
1202 }
1203 }
1204}
1205
1206
1207bool RegisterAllocator::IsOutputRegisterOf(Instruction* instr, int index) {
1208 for (size_t i = 0; i < instr->OutputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001209 auto output = instr->OutputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001210 if (output->IsRegister() && output->index() == index) return true;
1211 }
1212 return false;
1213}
1214
1215
1216bool RegisterAllocator::IsOutputDoubleRegisterOf(Instruction* instr,
1217 int index) {
1218 for (size_t i = 0; i < instr->OutputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001219 auto output = instr->OutputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001220 if (output->IsDoubleRegister() && output->index() == index) return true;
1221 }
1222 return false;
1223}
1224
1225
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001226void RegisterAllocator::ProcessInstructions(const InstructionBlock* block,
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001227 BitVector* live) {
1228 int block_start = block->first_instruction_index();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001229 auto block_start_position =
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001230 LifetimePosition::FromInstructionIndex(block_start);
1231
1232 for (int index = block->last_instruction_index(); index >= block_start;
1233 index--) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001234 auto curr_position = LifetimePosition::FromInstructionIndex(index);
1235 auto instr = InstructionAt(index);
1236 DCHECK(instr != nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001237 if (instr->IsGapMoves()) {
1238 // Process the moves of the gap instruction, making their sources live.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001239 auto gap = code()->GapAt(index);
1240 const GapInstruction::InnerPosition kPositions[] = {
1241 GapInstruction::END, GapInstruction::START};
1242 for (auto position : kPositions) {
1243 auto move = gap->GetParallelMove(position);
1244 if (move == nullptr) continue;
1245 if (position == GapInstruction::END) {
1246 curr_position = curr_position.InstructionEnd();
1247 } else {
1248 curr_position = curr_position.InstructionStart();
1249 }
1250 auto move_ops = move->move_operands();
1251 for (auto cur = move_ops->begin(); cur != move_ops->end(); ++cur) {
1252 auto from = cur->source();
1253 auto to = cur->destination();
1254 auto hint = to;
1255 if (to->IsUnallocated()) {
1256 int to_vreg = UnallocatedOperand::cast(to)->virtual_register();
1257 auto to_range = LiveRangeFor(to_vreg);
1258 if (to_range->is_phi()) {
1259 DCHECK(!FLAG_turbo_delay_ssa_decon);
1260 if (to_range->is_non_loop_phi()) {
1261 hint = to_range->current_hint_operand();
1262 }
1263 } else {
1264 if (live->Contains(to_vreg)) {
1265 Define(curr_position, to, from);
1266 live->Remove(to_vreg);
1267 } else {
1268 cur->Eliminate();
1269 continue;
1270 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001271 }
1272 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001273 Define(curr_position, to, from);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001274 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001275 Use(block_start_position, curr_position, from, hint);
1276 if (from->IsUnallocated()) {
1277 live->Add(UnallocatedOperand::cast(from)->virtual_register());
1278 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001279 }
1280 }
1281 } else {
1282 // Process output, inputs, and temps of this non-gap instruction.
1283 for (size_t i = 0; i < instr->OutputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001284 auto output = instr->OutputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001285 if (output->IsUnallocated()) {
1286 int out_vreg = UnallocatedOperand::cast(output)->virtual_register();
1287 live->Remove(out_vreg);
1288 } else if (output->IsConstant()) {
1289 int out_vreg = output->index();
1290 live->Remove(out_vreg);
1291 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001292 Define(curr_position, output, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001293 }
1294
1295 if (instr->ClobbersRegisters()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001296 for (int i = 0; i < config()->num_general_registers(); ++i) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001297 if (!IsOutputRegisterOf(instr, i)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001298 auto range = FixedLiveRangeFor(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001299 range->AddUseInterval(curr_position, curr_position.InstructionEnd(),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001300 local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001301 }
1302 }
1303 }
1304
1305 if (instr->ClobbersDoubleRegisters()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001306 for (int i = 0; i < config()->num_aliased_double_registers(); ++i) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001307 if (!IsOutputDoubleRegisterOf(instr, i)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001308 auto range = FixedDoubleLiveRangeFor(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001309 range->AddUseInterval(curr_position, curr_position.InstructionEnd(),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001310 local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001311 }
1312 }
1313 }
1314
1315 for (size_t i = 0; i < instr->InputCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001316 auto input = instr->InputAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001317 if (input->IsImmediate()) continue; // Ignore immediates.
1318 LifetimePosition use_pos;
1319 if (input->IsUnallocated() &&
1320 UnallocatedOperand::cast(input)->IsUsedAtStart()) {
1321 use_pos = curr_position;
1322 } else {
1323 use_pos = curr_position.InstructionEnd();
1324 }
1325
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001326 Use(block_start_position, use_pos, input, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001327 if (input->IsUnallocated()) {
1328 live->Add(UnallocatedOperand::cast(input)->virtual_register());
1329 }
1330 }
1331
1332 for (size_t i = 0; i < instr->TempCount(); i++) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001333 auto temp = instr->TempAt(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001334 if (instr->ClobbersTemps()) {
1335 if (temp->IsRegister()) continue;
1336 if (temp->IsUnallocated()) {
1337 UnallocatedOperand* temp_unalloc = UnallocatedOperand::cast(temp);
1338 if (temp_unalloc->HasFixedPolicy()) {
1339 continue;
1340 }
1341 }
1342 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001343 Use(block_start_position, curr_position.InstructionEnd(), temp,
1344 nullptr);
1345 Define(curr_position, temp, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001346 }
1347 }
1348 }
1349}
1350
1351
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001352void RegisterAllocator::ResolvePhis(const InstructionBlock* block) {
1353 for (auto phi : block->phis()) {
1354 if (FLAG_turbo_reuse_spill_slots) {
1355 auto res = phi_map_.insert(
1356 std::make_pair(phi->virtual_register(), PhiMapValue(phi, block)));
1357 DCHECK(res.second);
1358 USE(res);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001359 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001360 auto output = phi->output();
1361 int phi_vreg = phi->virtual_register();
1362 if (!FLAG_turbo_delay_ssa_decon) {
1363 for (size_t i = 0; i < phi->operands().size(); ++i) {
1364 InstructionBlock* cur_block =
1365 code()->InstructionBlockAt(block->predecessors()[i]);
1366 AddGapMove(cur_block->last_instruction_index() - 1, GapInstruction::END,
1367 phi->inputs()[i], output);
1368 DCHECK(!InstructionAt(cur_block->last_instruction_index())
1369 ->HasPointerMap());
1370 }
1371 }
1372 auto live_range = LiveRangeFor(phi_vreg);
1373 int gap_index = block->first_instruction_index();
1374 live_range->SpillAtDefinition(local_zone(), gap_index, output);
1375 live_range->SetSpillStartIndex(gap_index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001376 // We use the phi-ness of some nodes in some later heuristics.
1377 live_range->set_is_phi(true);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001378 live_range->set_is_non_loop_phi(!block->IsLoopHeader());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001379 }
1380}
1381
1382
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001383void RegisterAllocator::MeetRegisterConstraints() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001384 for (auto block : code()->instruction_blocks()) {
1385 MeetRegisterConstraints(block);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001386 }
1387}
1388
1389
1390void RegisterAllocator::ResolvePhis() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001391 // Process the blocks in reverse order.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001392 for (auto i = code()->instruction_blocks().rbegin();
1393 i != code()->instruction_blocks().rend(); ++i) {
1394 ResolvePhis(*i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001395 }
1396}
1397
1398
1399ParallelMove* RegisterAllocator::GetConnectingParallelMove(
1400 LifetimePosition pos) {
1401 int index = pos.InstructionIndex();
1402 if (code()->IsGapAt(index)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001403 auto gap = code()->GapAt(index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001404 return gap->GetOrCreateParallelMove(
1405 pos.IsInstructionStart() ? GapInstruction::START : GapInstruction::END,
1406 code_zone());
1407 }
1408 int gap_pos = pos.IsInstructionStart() ? (index - 1) : (index + 1);
1409 return code()->GapAt(gap_pos)->GetOrCreateParallelMove(
1410 (gap_pos < index) ? GapInstruction::AFTER : GapInstruction::BEFORE,
1411 code_zone());
1412}
1413
1414
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001415const InstructionBlock* RegisterAllocator::GetInstructionBlock(
1416 LifetimePosition pos) {
1417 return code()->GetInstructionBlock(pos.InstructionIndex());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001418}
1419
1420
1421void RegisterAllocator::ConnectRanges() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001422 for (auto first_range : live_ranges()) {
1423 if (first_range == nullptr || first_range->IsChild()) continue;
1424 auto second_range = first_range->next();
1425 while (second_range != nullptr) {
1426 auto pos = second_range->Start();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001427 if (!second_range->IsSpilled()) {
1428 // Add gap move if the two live ranges touch and there is no block
1429 // boundary.
1430 if (first_range->End().Value() == pos.Value()) {
1431 bool should_insert = true;
1432 if (IsBlockBoundary(pos)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001433 should_insert =
1434 CanEagerlyResolveControlFlow(GetInstructionBlock(pos));
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001435 }
1436 if (should_insert) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001437 auto move = GetConnectingParallelMove(pos);
1438 auto prev_operand = first_range->CreateAssignedOperand(code_zone());
1439 auto cur_operand = second_range->CreateAssignedOperand(code_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001440 move->AddMove(prev_operand, cur_operand, code_zone());
1441 }
1442 }
1443 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001444 first_range = second_range;
1445 second_range = second_range->next();
1446 }
1447 }
1448}
1449
1450
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001451bool RegisterAllocator::CanEagerlyResolveControlFlow(
1452 const InstructionBlock* block) const {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001453 if (block->PredecessorCount() != 1) return false;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001454 return block->predecessors()[0].IsNext(block->rpo_number());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001455}
1456
1457
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001458namespace {
1459
1460class LiveRangeBound {
1461 public:
1462 explicit LiveRangeBound(const LiveRange* range)
1463 : range_(range), start_(range->Start()), end_(range->End()) {
1464 DCHECK(!range->IsEmpty());
1465 }
1466
1467 bool CanCover(LifetimePosition position) {
1468 return start_.Value() <= position.Value() &&
1469 position.Value() < end_.Value();
1470 }
1471
1472 const LiveRange* const range_;
1473 const LifetimePosition start_;
1474 const LifetimePosition end_;
1475
1476 private:
1477 DISALLOW_COPY_AND_ASSIGN(LiveRangeBound);
1478};
1479
1480
1481struct FindResult {
1482 const LiveRange* cur_cover_;
1483 const LiveRange* pred_cover_;
1484};
1485
1486
1487class LiveRangeBoundArray {
1488 public:
1489 LiveRangeBoundArray() : length_(0), start_(nullptr) {}
1490
1491 bool ShouldInitialize() { return start_ == nullptr; }
1492
1493 void Initialize(Zone* zone, const LiveRange* const range) {
1494 size_t length = 0;
1495 for (auto i = range; i != nullptr; i = i->next()) length++;
1496 start_ = zone->NewArray<LiveRangeBound>(static_cast<int>(length));
1497 length_ = length;
1498 auto curr = start_;
1499 for (auto i = range; i != nullptr; i = i->next(), ++curr) {
1500 new (curr) LiveRangeBound(i);
1501 }
1502 }
1503
1504 LiveRangeBound* Find(const LifetimePosition position) const {
1505 size_t left_index = 0;
1506 size_t right_index = length_;
1507 while (true) {
1508 size_t current_index = left_index + (right_index - left_index) / 2;
1509 DCHECK(right_index > current_index);
1510 auto bound = &start_[current_index];
1511 if (bound->start_.Value() <= position.Value()) {
1512 if (position.Value() < bound->end_.Value()) return bound;
1513 DCHECK(left_index < current_index);
1514 left_index = current_index;
1515 } else {
1516 right_index = current_index;
1517 }
1518 }
1519 }
1520
1521 LiveRangeBound* FindPred(const InstructionBlock* pred) {
1522 auto pred_end =
1523 LifetimePosition::FromInstructionIndex(pred->last_instruction_index());
1524 return Find(pred_end);
1525 }
1526
1527 LiveRangeBound* FindSucc(const InstructionBlock* succ) {
1528 auto succ_start =
1529 LifetimePosition::FromInstructionIndex(succ->first_instruction_index());
1530 return Find(succ_start);
1531 }
1532
1533 void Find(const InstructionBlock* block, const InstructionBlock* pred,
1534 FindResult* result) const {
1535 auto pred_end =
1536 LifetimePosition::FromInstructionIndex(pred->last_instruction_index());
1537 auto bound = Find(pred_end);
1538 result->pred_cover_ = bound->range_;
1539 auto cur_start = LifetimePosition::FromInstructionIndex(
1540 block->first_instruction_index());
1541 // Common case.
1542 if (bound->CanCover(cur_start)) {
1543 result->cur_cover_ = bound->range_;
1544 return;
1545 }
1546 result->cur_cover_ = Find(cur_start)->range_;
1547 DCHECK(result->pred_cover_ != nullptr && result->cur_cover_ != nullptr);
1548 }
1549
1550 private:
1551 size_t length_;
1552 LiveRangeBound* start_;
1553
1554 DISALLOW_COPY_AND_ASSIGN(LiveRangeBoundArray);
1555};
1556
1557
1558class LiveRangeFinder {
1559 public:
1560 explicit LiveRangeFinder(const RegisterAllocator& allocator)
1561 : allocator_(allocator),
1562 bounds_length_(static_cast<int>(allocator.live_ranges().size())),
1563 bounds_(allocator.local_zone()->NewArray<LiveRangeBoundArray>(
1564 bounds_length_)) {
1565 for (int i = 0; i < bounds_length_; ++i) {
1566 new (&bounds_[i]) LiveRangeBoundArray();
1567 }
1568 }
1569
1570 LiveRangeBoundArray* ArrayFor(int operand_index) {
1571 DCHECK(operand_index < bounds_length_);
1572 auto range = allocator_.live_ranges()[operand_index];
1573 DCHECK(range != nullptr && !range->IsEmpty());
1574 auto array = &bounds_[operand_index];
1575 if (array->ShouldInitialize()) {
1576 array->Initialize(allocator_.local_zone(), range);
1577 }
1578 return array;
1579 }
1580
1581 private:
1582 const RegisterAllocator& allocator_;
1583 const int bounds_length_;
1584 LiveRangeBoundArray* const bounds_;
1585
1586 DISALLOW_COPY_AND_ASSIGN(LiveRangeFinder);
1587};
1588
1589} // namespace
1590
1591
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001592void RegisterAllocator::ResolveControlFlow() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001593 // Lazily linearize live ranges in memory for fast lookup.
1594 LiveRangeFinder finder(*this);
1595 for (auto block : code()->instruction_blocks()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001596 if (CanEagerlyResolveControlFlow(block)) continue;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001597 if (FLAG_turbo_delay_ssa_decon) {
1598 // resolve phis
1599 for (auto phi : block->phis()) {
1600 auto* block_bound =
1601 finder.ArrayFor(phi->virtual_register())->FindSucc(block);
1602 auto phi_output =
1603 block_bound->range_->CreateAssignedOperand(code_zone());
1604 phi->output()->ConvertTo(phi_output->kind(), phi_output->index());
1605 size_t pred_index = 0;
1606 for (auto pred : block->predecessors()) {
1607 const InstructionBlock* pred_block = code()->InstructionBlockAt(pred);
1608 auto* pred_bound = finder.ArrayFor(phi->operands()[pred_index])
1609 ->FindPred(pred_block);
1610 auto pred_op = pred_bound->range_->CreateAssignedOperand(code_zone());
1611 phi->inputs()[pred_index] = pred_op;
1612 ResolveControlFlow(block, phi_output, pred_block, pred_op);
1613 pred_index++;
1614 }
1615 }
1616 }
1617 auto live = live_in_sets_[block->rpo_number().ToInt()];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001618 BitVector::Iterator iterator(live);
1619 while (!iterator.Done()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001620 auto* array = finder.ArrayFor(iterator.Current());
1621 for (auto pred : block->predecessors()) {
1622 FindResult result;
1623 const auto* pred_block = code()->InstructionBlockAt(pred);
1624 array->Find(block, pred_block, &result);
1625 if (result.cur_cover_ == result.pred_cover_ ||
1626 result.cur_cover_->IsSpilled())
1627 continue;
1628 auto pred_op = result.pred_cover_->CreateAssignedOperand(code_zone());
1629 auto cur_op = result.cur_cover_->CreateAssignedOperand(code_zone());
1630 ResolveControlFlow(block, cur_op, pred_block, pred_op);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001631 }
1632 iterator.Advance();
1633 }
1634 }
1635}
1636
1637
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001638void RegisterAllocator::ResolveControlFlow(const InstructionBlock* block,
1639 InstructionOperand* cur_op,
1640 const InstructionBlock* pred,
1641 InstructionOperand* pred_op) {
1642 if (pred_op->Equals(cur_op)) return;
1643 int gap_index;
1644 GapInstruction::InnerPosition position;
1645 if (block->PredecessorCount() == 1) {
1646 gap_index = block->first_instruction_index();
1647 position = GapInstruction::START;
1648 } else {
1649 DCHECK(pred->SuccessorCount() == 1);
1650 DCHECK(!InstructionAt(pred->last_instruction_index())->HasPointerMap());
1651 gap_index = pred->last_instruction_index() - 1;
1652 position = GapInstruction::END;
1653 }
1654 AddGapMove(gap_index, position, pred_op, cur_op);
1655}
1656
1657
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001658void RegisterAllocator::BuildLiveRanges() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001659 // Process the blocks in reverse order.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001660 for (int block_id = code()->InstructionBlockCount() - 1; block_id >= 0;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001661 --block_id) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001662 auto block =
1663 code()->InstructionBlockAt(BasicBlock::RpoNumber::FromInt(block_id));
1664 auto live = ComputeLiveOut(block);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001665 // Initially consider all live_out values live for the entire block. We
1666 // will shorten these intervals if necessary.
1667 AddInitialIntervals(block, live);
1668
1669 // Process the instructions in reverse order, generating and killing
1670 // live values.
1671 ProcessInstructions(block, live);
1672 // All phi output operands are killed by this block.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001673 for (auto phi : block->phis()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001674 // The live range interval already ends at the first instruction of the
1675 // block.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001676 int phi_vreg = phi->virtual_register();
1677 live->Remove(phi_vreg);
1678 if (!FLAG_turbo_delay_ssa_decon) {
1679 InstructionOperand* hint = nullptr;
1680 InstructionOperand* phi_operand = nullptr;
1681 auto gap =
1682 GetLastGap(code()->InstructionBlockAt(block->predecessors()[0]));
1683 auto move =
1684 gap->GetOrCreateParallelMove(GapInstruction::END, code_zone());
1685 for (int j = 0; j < move->move_operands()->length(); ++j) {
1686 auto to = move->move_operands()->at(j).destination();
1687 if (to->IsUnallocated() &&
1688 UnallocatedOperand::cast(to)->virtual_register() == phi_vreg) {
1689 hint = move->move_operands()->at(j).source();
1690 phi_operand = to;
1691 break;
1692 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001693 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001694 DCHECK(hint != nullptr);
1695 auto block_start = LifetimePosition::FromInstructionIndex(
1696 block->first_instruction_index());
1697 Define(block_start, phi_operand, hint);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001698 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001699 }
1700
1701 // Now live is live_in for this block except not including values live
1702 // out on backward successor edges.
1703 live_in_sets_[block_id] = live;
1704
1705 if (block->IsLoopHeader()) {
1706 // Add a live range stretching from the first loop instruction to the last
1707 // for each value live on entry to the header.
1708 BitVector::Iterator iterator(live);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001709 auto start = LifetimePosition::FromInstructionIndex(
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001710 block->first_instruction_index());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001711 auto end = LifetimePosition::FromInstructionIndex(
1712 code()->LastLoopInstructionIndex(block)).NextInstruction();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001713 while (!iterator.Done()) {
1714 int operand_index = iterator.Current();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001715 auto range = LiveRangeFor(operand_index);
1716 range->EnsureInterval(start, end, local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001717 iterator.Advance();
1718 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001719 // Insert all values into the live in sets of all blocks in the loop.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001720 for (int i = block->rpo_number().ToInt() + 1;
1721 i < block->loop_end().ToInt(); ++i) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001722 live_in_sets_[i]->Union(*live);
1723 }
1724 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001725 }
1726
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001727 for (auto range : live_ranges()) {
1728 if (range == nullptr) continue;
1729 range->kind_ = RequiredRegisterKind(range->id());
1730 // TODO(bmeurer): This is a horrible hack to make sure that for constant
1731 // live ranges, every use requires the constant to be in a register.
1732 // Without this hack, all uses with "any" policy would get the constant
1733 // operand assigned.
1734 if (range->HasSpillOperand() && range->GetSpillOperand()->IsConstant()) {
1735 for (auto pos = range->first_pos(); pos != nullptr; pos = pos->next_) {
1736 pos->register_beneficial_ = true;
1737 // TODO(dcarney): should the else case assert requires_reg_ == false?
1738 // Can't mark phis as needing a register.
1739 if (!code()
1740 ->InstructionAt(pos->pos().InstructionIndex())
1741 ->IsGapMoves()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001742 pos->requires_reg_ = true;
1743 }
1744 }
1745 }
1746 }
1747}
1748
1749
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001750bool RegisterAllocator::ExistsUseWithoutDefinition() {
1751 bool found = false;
1752 BitVector::Iterator iterator(live_in_sets_[0]);
1753 while (!iterator.Done()) {
1754 found = true;
1755 int operand_index = iterator.Current();
1756 PrintF("Register allocator error: live v%d reached first block.\n",
1757 operand_index);
1758 LiveRange* range = LiveRangeFor(operand_index);
1759 PrintF(" (first use is at %d)\n", range->first_pos()->pos().Value());
1760 if (debug_name() == nullptr) {
1761 PrintF("\n");
1762 } else {
1763 PrintF(" (function: %s)\n", debug_name());
1764 }
1765 iterator.Advance();
1766 }
1767 return found;
1768}
1769
1770
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001771bool RegisterAllocator::SafePointsAreInOrder() const {
1772 int safe_point = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001773 for (auto map : *code()->pointer_maps()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001774 if (safe_point > map->instruction_position()) return false;
1775 safe_point = map->instruction_position();
1776 }
1777 return true;
1778}
1779
1780
1781void RegisterAllocator::PopulatePointerMaps() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001782 DCHECK(SafePointsAreInOrder());
1783
1784 // Iterate over all safe point positions and record a pointer
1785 // for all spilled live ranges at this point.
1786 int last_range_start = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001787 auto pointer_maps = code()->pointer_maps();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001788 PointerMapDeque::const_iterator first_it = pointer_maps->begin();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001789 for (LiveRange* range : live_ranges()) {
1790 if (range == nullptr) continue;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001791 // Iterate over the first parts of multi-part live ranges.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001792 if (range->IsChild()) continue;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001793 // Skip non-reference values.
1794 if (!HasTaggedValue(range->id())) continue;
1795 // Skip empty live ranges.
1796 if (range->IsEmpty()) continue;
1797
1798 // Find the extent of the range and its children.
1799 int start = range->Start().InstructionIndex();
1800 int end = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001801 for (auto cur = range; cur != nullptr; cur = cur->next()) {
1802 auto this_end = cur->End();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001803 if (this_end.InstructionIndex() > end) end = this_end.InstructionIndex();
1804 DCHECK(cur->Start().InstructionIndex() >= start);
1805 }
1806
1807 // Most of the ranges are in order, but not all. Keep an eye on when they
1808 // step backwards and reset the first_it so we don't miss any safe points.
1809 if (start < last_range_start) first_it = pointer_maps->begin();
1810 last_range_start = start;
1811
1812 // Step across all the safe points that are before the start of this range,
1813 // recording how far we step in order to save doing this for the next range.
1814 for (; first_it != pointer_maps->end(); ++first_it) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001815 auto map = *first_it;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001816 if (map->instruction_position() >= start) break;
1817 }
1818
1819 // Step through the safe points to see whether they are in the range.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001820 for (auto it = first_it; it != pointer_maps->end(); ++it) {
1821 auto map = *it;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001822 int safe_point = map->instruction_position();
1823
1824 // The safe points are sorted so we can stop searching here.
1825 if (safe_point - 1 > end) break;
1826
1827 // Advance to the next active range that covers the current
1828 // safe point position.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001829 auto safe_point_pos = LifetimePosition::FromInstructionIndex(safe_point);
1830 auto cur = range;
1831 while (cur != nullptr && !cur->Covers(safe_point_pos)) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001832 cur = cur->next();
1833 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001834 if (cur == nullptr) continue;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001835
1836 // Check if the live range is spilled and the safe point is after
1837 // the spill position.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001838 if (range->HasSpillOperand() &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001839 safe_point >= range->spill_start_index() &&
1840 !range->GetSpillOperand()->IsConstant()) {
1841 TraceAlloc("Pointer for range %d (spilled at %d) at safe point %d\n",
1842 range->id(), range->spill_start_index(), safe_point);
1843 map->RecordPointer(range->GetSpillOperand(), code_zone());
1844 }
1845
1846 if (!cur->IsSpilled()) {
1847 TraceAlloc(
1848 "Pointer in register for range %d (start at %d) "
1849 "at safe point %d\n",
1850 cur->id(), cur->Start().Value(), safe_point);
1851 InstructionOperand* operand = cur->CreateAssignedOperand(code_zone());
1852 DCHECK(!operand->IsStackSlot());
1853 map->RecordPointer(operand, code_zone());
1854 }
1855 }
1856 }
1857}
1858
1859
1860void RegisterAllocator::AllocateGeneralRegisters() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001861 num_registers_ = config()->num_general_registers();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001862 mode_ = GENERAL_REGISTERS;
1863 AllocateRegisters();
1864}
1865
1866
1867void RegisterAllocator::AllocateDoubleRegisters() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001868 num_registers_ = config()->num_aliased_double_registers();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001869 mode_ = DOUBLE_REGISTERS;
1870 AllocateRegisters();
1871}
1872
1873
1874void RegisterAllocator::AllocateRegisters() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001875 DCHECK(unhandled_live_ranges().empty());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001876
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001877 for (auto range : live_ranges()) {
1878 if (range == nullptr) continue;
1879 if (range->Kind() == mode_) {
1880 AddToUnhandledUnsorted(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001881 }
1882 }
1883 SortUnhandled();
1884 DCHECK(UnhandledIsSorted());
1885
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001886 DCHECK(reusable_slots().empty());
1887 DCHECK(active_live_ranges().empty());
1888 DCHECK(inactive_live_ranges().empty());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001889
1890 if (mode_ == DOUBLE_REGISTERS) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001891 for (int i = 0; i < config()->num_aliased_double_registers(); ++i) {
1892 auto current = fixed_double_live_ranges()[i];
1893 if (current != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001894 AddToInactive(current);
1895 }
1896 }
1897 } else {
1898 DCHECK(mode_ == GENERAL_REGISTERS);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001899 for (auto current : fixed_live_ranges()) {
1900 if (current != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001901 AddToInactive(current);
1902 }
1903 }
1904 }
1905
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001906 while (!unhandled_live_ranges().empty()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001907 DCHECK(UnhandledIsSorted());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001908 auto current = unhandled_live_ranges().back();
1909 unhandled_live_ranges().pop_back();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001910 DCHECK(UnhandledIsSorted());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001911 auto position = current->Start();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001912#ifdef DEBUG
1913 allocation_finger_ = position;
1914#endif
1915 TraceAlloc("Processing interval %d start=%d\n", current->id(),
1916 position.Value());
1917
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001918 if (!current->HasNoSpillType()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001919 TraceAlloc("Live range %d already has a spill operand\n", current->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001920 auto next_pos = position;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001921 if (code()->IsGapAt(next_pos.InstructionIndex())) {
1922 next_pos = next_pos.NextInstruction();
1923 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001924 auto pos = current->NextUsePositionRegisterIsBeneficial(next_pos);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001925 // If the range already has a spill operand and it doesn't need a
1926 // register immediately, split it and spill the first part of the range.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001927 if (pos == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001928 Spill(current);
1929 continue;
1930 } else if (pos->pos().Value() >
1931 current->Start().NextInstruction().Value()) {
1932 // Do not spill live range eagerly if use position that can benefit from
1933 // the register is too close to the start of live range.
1934 SpillBetween(current, current->Start(), pos->pos());
1935 if (!AllocationOk()) return;
1936 DCHECK(UnhandledIsSorted());
1937 continue;
1938 }
1939 }
1940
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001941 if (FLAG_turbo_reuse_spill_slots) {
1942 if (TryReuseSpillForPhi(current)) {
1943 continue;
1944 }
1945 if (!AllocationOk()) return;
1946 }
1947
1948 for (size_t i = 0; i < active_live_ranges().size(); ++i) {
1949 auto cur_active = active_live_ranges()[i];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001950 if (cur_active->End().Value() <= position.Value()) {
1951 ActiveToHandled(cur_active);
1952 --i; // The live range was removed from the list of active live ranges.
1953 } else if (!cur_active->Covers(position)) {
1954 ActiveToInactive(cur_active);
1955 --i; // The live range was removed from the list of active live ranges.
1956 }
1957 }
1958
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001959 for (size_t i = 0; i < inactive_live_ranges().size(); ++i) {
1960 auto cur_inactive = inactive_live_ranges()[i];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001961 if (cur_inactive->End().Value() <= position.Value()) {
1962 InactiveToHandled(cur_inactive);
1963 --i; // Live range was removed from the list of inactive live ranges.
1964 } else if (cur_inactive->Covers(position)) {
1965 InactiveToActive(cur_inactive);
1966 --i; // Live range was removed from the list of inactive live ranges.
1967 }
1968 }
1969
1970 DCHECK(!current->HasRegisterAssigned() && !current->IsSpilled());
1971
1972 bool result = TryAllocateFreeReg(current);
1973 if (!AllocationOk()) return;
1974
1975 if (!result) AllocateBlockedReg(current);
1976 if (!AllocationOk()) return;
1977
1978 if (current->HasRegisterAssigned()) {
1979 AddToActive(current);
1980 }
1981 }
1982
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001983 reusable_slots().clear();
1984 active_live_ranges().clear();
1985 inactive_live_ranges().clear();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001986}
1987
1988
1989const char* RegisterAllocator::RegisterName(int allocation_index) {
1990 if (mode_ == GENERAL_REGISTERS) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001991 return config()->general_register_name(allocation_index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001992 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001993 return config()->double_register_name(allocation_index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001994 }
1995}
1996
1997
1998bool RegisterAllocator::HasTaggedValue(int virtual_register) const {
1999 return code()->IsReference(virtual_register);
2000}
2001
2002
2003RegisterKind RegisterAllocator::RequiredRegisterKind(
2004 int virtual_register) const {
2005 return (code()->IsDouble(virtual_register)) ? DOUBLE_REGISTERS
2006 : GENERAL_REGISTERS;
2007}
2008
2009
2010void RegisterAllocator::AddToActive(LiveRange* range) {
2011 TraceAlloc("Add live range %d to active\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002012 active_live_ranges().push_back(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002013}
2014
2015
2016void RegisterAllocator::AddToInactive(LiveRange* range) {
2017 TraceAlloc("Add live range %d to inactive\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002018 inactive_live_ranges().push_back(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002019}
2020
2021
2022void RegisterAllocator::AddToUnhandledSorted(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002023 if (range == nullptr || range->IsEmpty()) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002024 DCHECK(!range->HasRegisterAssigned() && !range->IsSpilled());
2025 DCHECK(allocation_finger_.Value() <= range->Start().Value());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002026 for (int i = static_cast<int>(unhandled_live_ranges().size() - 1); i >= 0;
2027 --i) {
2028 auto cur_range = unhandled_live_ranges().at(i);
2029 if (!range->ShouldBeAllocatedBefore(cur_range)) continue;
2030 TraceAlloc("Add live range %d to unhandled at %d\n", range->id(), i + 1);
2031 auto it = unhandled_live_ranges().begin() + (i + 1);
2032 unhandled_live_ranges().insert(it, range);
2033 DCHECK(UnhandledIsSorted());
2034 return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002035 }
2036 TraceAlloc("Add live range %d to unhandled at start\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002037 unhandled_live_ranges().insert(unhandled_live_ranges().begin(), range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002038 DCHECK(UnhandledIsSorted());
2039}
2040
2041
2042void RegisterAllocator::AddToUnhandledUnsorted(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002043 if (range == nullptr || range->IsEmpty()) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002044 DCHECK(!range->HasRegisterAssigned() && !range->IsSpilled());
2045 TraceAlloc("Add live range %d to unhandled unsorted at end\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002046 unhandled_live_ranges().push_back(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002047}
2048
2049
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002050static bool UnhandledSortHelper(LiveRange* a, LiveRange* b) {
2051 DCHECK(!a->ShouldBeAllocatedBefore(b) || !b->ShouldBeAllocatedBefore(a));
2052 if (a->ShouldBeAllocatedBefore(b)) return false;
2053 if (b->ShouldBeAllocatedBefore(a)) return true;
2054 return a->id() < b->id();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002055}
2056
2057
2058// Sort the unhandled live ranges so that the ranges to be processed first are
2059// at the end of the array list. This is convenient for the register allocation
2060// algorithm because it is efficient to remove elements from the end.
2061void RegisterAllocator::SortUnhandled() {
2062 TraceAlloc("Sort unhandled\n");
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002063 std::sort(unhandled_live_ranges().begin(), unhandled_live_ranges().end(),
2064 &UnhandledSortHelper);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002065}
2066
2067
2068bool RegisterAllocator::UnhandledIsSorted() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002069 size_t len = unhandled_live_ranges().size();
2070 for (size_t i = 1; i < len; i++) {
2071 auto a = unhandled_live_ranges().at(i - 1);
2072 auto b = unhandled_live_ranges().at(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002073 if (a->Start().Value() < b->Start().Value()) return false;
2074 }
2075 return true;
2076}
2077
2078
2079void RegisterAllocator::FreeSpillSlot(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002080 DCHECK(!FLAG_turbo_reuse_spill_slots);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002081 // Check that we are the last range.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002082 if (range->next() != nullptr) return;
2083 if (!range->TopLevel()->HasSpillOperand()) return;
2084 auto spill_operand = range->TopLevel()->GetSpillOperand();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002085 if (spill_operand->IsConstant()) return;
2086 if (spill_operand->index() >= 0) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002087 reusable_slots().push_back(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002088 }
2089}
2090
2091
2092InstructionOperand* RegisterAllocator::TryReuseSpillSlot(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002093 DCHECK(!FLAG_turbo_reuse_spill_slots);
2094 if (reusable_slots().empty()) return nullptr;
2095 if (reusable_slots().front()->End().Value() >
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002096 range->TopLevel()->Start().Value()) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002097 return nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002098 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002099 auto result = reusable_slots().front()->TopLevel()->GetSpillOperand();
2100 reusable_slots().erase(reusable_slots().begin());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002101 return result;
2102}
2103
2104
2105void RegisterAllocator::ActiveToHandled(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002106 RemoveElement(&active_live_ranges(), range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002107 TraceAlloc("Moving live range %d from active to handled\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002108 if (!FLAG_turbo_reuse_spill_slots) FreeSpillSlot(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002109}
2110
2111
2112void RegisterAllocator::ActiveToInactive(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002113 RemoveElement(&active_live_ranges(), range);
2114 inactive_live_ranges().push_back(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002115 TraceAlloc("Moving live range %d from active to inactive\n", range->id());
2116}
2117
2118
2119void RegisterAllocator::InactiveToHandled(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002120 RemoveElement(&inactive_live_ranges(), range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002121 TraceAlloc("Moving live range %d from inactive to handled\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002122 if (!FLAG_turbo_reuse_spill_slots) FreeSpillSlot(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002123}
2124
2125
2126void RegisterAllocator::InactiveToActive(LiveRange* range) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002127 RemoveElement(&inactive_live_ranges(), range);
2128 active_live_ranges().push_back(range);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002129 TraceAlloc("Moving live range %d from inactive to active\n", range->id());
2130}
2131
2132
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002133bool RegisterAllocator::TryAllocateFreeReg(LiveRange* current) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002134 LifetimePosition free_until_pos[RegisterConfiguration::kMaxDoubleRegisters];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002135
2136 for (int i = 0; i < num_registers_; i++) {
2137 free_until_pos[i] = LifetimePosition::MaxPosition();
2138 }
2139
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002140 for (auto cur_active : active_live_ranges()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002141 free_until_pos[cur_active->assigned_register()] =
2142 LifetimePosition::FromInstructionIndex(0);
2143 }
2144
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002145 for (auto cur_inactive : inactive_live_ranges()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002146 DCHECK(cur_inactive->End().Value() > current->Start().Value());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002147 auto next_intersection = cur_inactive->FirstIntersection(current);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002148 if (!next_intersection.IsValid()) continue;
2149 int cur_reg = cur_inactive->assigned_register();
2150 free_until_pos[cur_reg] = Min(free_until_pos[cur_reg], next_intersection);
2151 }
2152
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002153 auto hint = current->FirstHint();
2154 if (hint != nullptr && (hint->IsRegister() || hint->IsDoubleRegister())) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002155 int register_index = hint->index();
2156 TraceAlloc(
2157 "Found reg hint %s (free until [%d) for live range %d (end %d[).\n",
2158 RegisterName(register_index), free_until_pos[register_index].Value(),
2159 current->id(), current->End().Value());
2160
2161 // The desired register is free until the end of the current live range.
2162 if (free_until_pos[register_index].Value() >= current->End().Value()) {
2163 TraceAlloc("Assigning preferred reg %s to live range %d\n",
2164 RegisterName(register_index), current->id());
2165 SetLiveRangeAssignedRegister(current, register_index);
2166 return true;
2167 }
2168 }
2169
2170 // Find the register which stays free for the longest time.
2171 int reg = 0;
2172 for (int i = 1; i < RegisterCount(); ++i) {
2173 if (free_until_pos[i].Value() > free_until_pos[reg].Value()) {
2174 reg = i;
2175 }
2176 }
2177
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002178 auto pos = free_until_pos[reg];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002179
2180 if (pos.Value() <= current->Start().Value()) {
2181 // All registers are blocked.
2182 return false;
2183 }
2184
2185 if (pos.Value() < current->End().Value()) {
2186 // Register reg is available at the range start but becomes blocked before
2187 // the range end. Split current at position where it becomes blocked.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002188 auto tail = SplitRangeAt(current, pos);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002189 if (!AllocationOk()) return false;
2190 AddToUnhandledSorted(tail);
2191 }
2192
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002193 // Register reg is available at the range start and is free until
2194 // the range end.
2195 DCHECK(pos.Value() >= current->End().Value());
2196 TraceAlloc("Assigning free reg %s to live range %d\n", RegisterName(reg),
2197 current->id());
2198 SetLiveRangeAssignedRegister(current, reg);
2199
2200 return true;
2201}
2202
2203
2204void RegisterAllocator::AllocateBlockedReg(LiveRange* current) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002205 auto register_use = current->NextRegisterPosition(current->Start());
2206 if (register_use == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002207 // There is no use in the current live range that requires a register.
2208 // We can just spill it.
2209 Spill(current);
2210 return;
2211 }
2212
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002213 LifetimePosition use_pos[RegisterConfiguration::kMaxDoubleRegisters];
2214 LifetimePosition block_pos[RegisterConfiguration::kMaxDoubleRegisters];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002215
2216 for (int i = 0; i < num_registers_; i++) {
2217 use_pos[i] = block_pos[i] = LifetimePosition::MaxPosition();
2218 }
2219
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002220 for (auto range : active_live_ranges()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002221 int cur_reg = range->assigned_register();
2222 if (range->IsFixed() || !range->CanBeSpilled(current->Start())) {
2223 block_pos[cur_reg] = use_pos[cur_reg] =
2224 LifetimePosition::FromInstructionIndex(0);
2225 } else {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002226 auto next_use =
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002227 range->NextUsePositionRegisterIsBeneficial(current->Start());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002228 if (next_use == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002229 use_pos[cur_reg] = range->End();
2230 } else {
2231 use_pos[cur_reg] = next_use->pos();
2232 }
2233 }
2234 }
2235
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002236 for (auto range : inactive_live_ranges()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002237 DCHECK(range->End().Value() > current->Start().Value());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002238 auto next_intersection = range->FirstIntersection(current);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002239 if (!next_intersection.IsValid()) continue;
2240 int cur_reg = range->assigned_register();
2241 if (range->IsFixed()) {
2242 block_pos[cur_reg] = Min(block_pos[cur_reg], next_intersection);
2243 use_pos[cur_reg] = Min(block_pos[cur_reg], use_pos[cur_reg]);
2244 } else {
2245 use_pos[cur_reg] = Min(use_pos[cur_reg], next_intersection);
2246 }
2247 }
2248
2249 int reg = 0;
2250 for (int i = 1; i < RegisterCount(); ++i) {
2251 if (use_pos[i].Value() > use_pos[reg].Value()) {
2252 reg = i;
2253 }
2254 }
2255
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002256 auto pos = use_pos[reg];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002257
2258 if (pos.Value() < register_use->pos().Value()) {
2259 // All registers are blocked before the first use that requires a register.
2260 // Spill starting part of live range up to that use.
2261 SpillBetween(current, current->Start(), register_use->pos());
2262 return;
2263 }
2264
2265 if (block_pos[reg].Value() < current->End().Value()) {
2266 // Register becomes blocked before the current range end. Split before that
2267 // position.
2268 LiveRange* tail = SplitBetween(current, current->Start(),
2269 block_pos[reg].InstructionStart());
2270 if (!AllocationOk()) return;
2271 AddToUnhandledSorted(tail);
2272 }
2273
2274 // Register reg is not blocked for the whole range.
2275 DCHECK(block_pos[reg].Value() >= current->End().Value());
2276 TraceAlloc("Assigning blocked reg %s to live range %d\n", RegisterName(reg),
2277 current->id());
2278 SetLiveRangeAssignedRegister(current, reg);
2279
2280 // This register was not free. Thus we need to find and spill
2281 // parts of active and inactive live regions that use the same register
2282 // at the same lifetime positions as current.
2283 SplitAndSpillIntersecting(current);
2284}
2285
2286
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002287static const InstructionBlock* GetContainingLoop(
2288 const InstructionSequence* sequence, const InstructionBlock* block) {
2289 auto index = block->loop_header();
2290 if (!index.IsValid()) return nullptr;
2291 return sequence->InstructionBlockAt(index);
2292}
2293
2294
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002295LifetimePosition RegisterAllocator::FindOptimalSpillingPos(
2296 LiveRange* range, LifetimePosition pos) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002297 auto block = GetInstructionBlock(pos.InstructionStart());
2298 auto loop_header =
2299 block->IsLoopHeader() ? block : GetContainingLoop(code(), block);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002300
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002301 if (loop_header == nullptr) return pos;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002302
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002303 auto prev_use = range->PreviousUsePositionRegisterIsBeneficial(pos);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002304
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002305 while (loop_header != nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002306 // We are going to spill live range inside the loop.
2307 // If possible try to move spilling position backwards to loop header.
2308 // This will reduce number of memory moves on the back edge.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002309 auto loop_start = LifetimePosition::FromInstructionIndex(
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002310 loop_header->first_instruction_index());
2311
2312 if (range->Covers(loop_start)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002313 if (prev_use == nullptr || prev_use->pos().Value() < loop_start.Value()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002314 // No register beneficial use inside the loop before the pos.
2315 pos = loop_start;
2316 }
2317 }
2318
2319 // Try hoisting out to an outer loop.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002320 loop_header = GetContainingLoop(code(), loop_header);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002321 }
2322
2323 return pos;
2324}
2325
2326
2327void RegisterAllocator::SplitAndSpillIntersecting(LiveRange* current) {
2328 DCHECK(current->HasRegisterAssigned());
2329 int reg = current->assigned_register();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002330 auto split_pos = current->Start();
2331 for (size_t i = 0; i < active_live_ranges().size(); ++i) {
2332 auto range = active_live_ranges()[i];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002333 if (range->assigned_register() == reg) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002334 auto next_pos = range->NextRegisterPosition(current->Start());
2335 auto spill_pos = FindOptimalSpillingPos(range, split_pos);
2336 if (next_pos == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002337 SpillAfter(range, spill_pos);
2338 } else {
2339 // When spilling between spill_pos and next_pos ensure that the range
2340 // remains spilled at least until the start of the current live range.
2341 // This guarantees that we will not introduce new unhandled ranges that
2342 // start before the current range as this violates allocation invariant
2343 // and will lead to an inconsistent state of active and inactive
2344 // live-ranges: ranges are allocated in order of their start positions,
2345 // ranges are retired from active/inactive when the start of the
2346 // current live-range is larger than their end.
2347 SpillBetweenUntil(range, spill_pos, current->Start(), next_pos->pos());
2348 }
2349 if (!AllocationOk()) return;
2350 ActiveToHandled(range);
2351 --i;
2352 }
2353 }
2354
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002355 for (size_t i = 0; i < inactive_live_ranges().size(); ++i) {
2356 auto range = inactive_live_ranges()[i];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002357 DCHECK(range->End().Value() > current->Start().Value());
2358 if (range->assigned_register() == reg && !range->IsFixed()) {
2359 LifetimePosition next_intersection = range->FirstIntersection(current);
2360 if (next_intersection.IsValid()) {
2361 UsePosition* next_pos = range->NextRegisterPosition(current->Start());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002362 if (next_pos == nullptr) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002363 SpillAfter(range, split_pos);
2364 } else {
2365 next_intersection = Min(next_intersection, next_pos->pos());
2366 SpillBetween(range, split_pos, next_intersection);
2367 }
2368 if (!AllocationOk()) return;
2369 InactiveToHandled(range);
2370 --i;
2371 }
2372 }
2373 }
2374}
2375
2376
2377bool RegisterAllocator::IsBlockBoundary(LifetimePosition pos) {
2378 return pos.IsInstructionStart() &&
2379 InstructionAt(pos.InstructionIndex())->IsBlockStart();
2380}
2381
2382
2383LiveRange* RegisterAllocator::SplitRangeAt(LiveRange* range,
2384 LifetimePosition pos) {
2385 DCHECK(!range->IsFixed());
2386 TraceAlloc("Splitting live range %d at %d\n", range->id(), pos.Value());
2387
2388 if (pos.Value() <= range->Start().Value()) return range;
2389
2390 // We can't properly connect liveranges if split occured at the end
2391 // of control instruction.
2392 DCHECK(pos.IsInstructionStart() ||
2393 !InstructionAt(pos.InstructionIndex())->IsControl());
2394
2395 int vreg = GetVirtualRegister();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002396 if (!AllocationOk()) return nullptr;
2397 auto result = LiveRangeFor(vreg);
2398 range->SplitAt(pos, result, local_zone());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002399 return result;
2400}
2401
2402
2403LiveRange* RegisterAllocator::SplitBetween(LiveRange* range,
2404 LifetimePosition start,
2405 LifetimePosition end) {
2406 DCHECK(!range->IsFixed());
2407 TraceAlloc("Splitting live range %d in position between [%d, %d]\n",
2408 range->id(), start.Value(), end.Value());
2409
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002410 auto split_pos = FindOptimalSplitPos(start, end);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002411 DCHECK(split_pos.Value() >= start.Value());
2412 return SplitRangeAt(range, split_pos);
2413}
2414
2415
2416LifetimePosition RegisterAllocator::FindOptimalSplitPos(LifetimePosition start,
2417 LifetimePosition end) {
2418 int start_instr = start.InstructionIndex();
2419 int end_instr = end.InstructionIndex();
2420 DCHECK(start_instr <= end_instr);
2421
2422 // We have no choice
2423 if (start_instr == end_instr) return end;
2424
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002425 auto start_block = GetInstructionBlock(start);
2426 auto end_block = GetInstructionBlock(end);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002427
2428 if (end_block == start_block) {
2429 // The interval is split in the same basic block. Split at the latest
2430 // possible position.
2431 return end;
2432 }
2433
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002434 auto block = end_block;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002435 // Find header of outermost loop.
2436 // TODO(titzer): fix redundancy below.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002437 while (GetContainingLoop(code(), block) != nullptr &&
2438 GetContainingLoop(code(), block)->rpo_number().ToInt() >
2439 start_block->rpo_number().ToInt()) {
2440 block = GetContainingLoop(code(), block);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002441 }
2442
2443 // We did not find any suitable outer loop. Split at the latest possible
2444 // position unless end_block is a loop header itself.
2445 if (block == end_block && !end_block->IsLoopHeader()) return end;
2446
2447 return LifetimePosition::FromInstructionIndex(
2448 block->first_instruction_index());
2449}
2450
2451
2452void RegisterAllocator::SpillAfter(LiveRange* range, LifetimePosition pos) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002453 auto second_part = SplitRangeAt(range, pos);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002454 if (!AllocationOk()) return;
2455 Spill(second_part);
2456}
2457
2458
2459void RegisterAllocator::SpillBetween(LiveRange* range, LifetimePosition start,
2460 LifetimePosition end) {
2461 SpillBetweenUntil(range, start, start, end);
2462}
2463
2464
2465void RegisterAllocator::SpillBetweenUntil(LiveRange* range,
2466 LifetimePosition start,
2467 LifetimePosition until,
2468 LifetimePosition end) {
2469 CHECK(start.Value() < end.Value());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002470 auto second_part = SplitRangeAt(range, start);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002471 if (!AllocationOk()) return;
2472
2473 if (second_part->Start().Value() < end.Value()) {
2474 // The split result intersects with [start, end[.
2475 // Split it at position between ]start+1, end[, spill the middle part
2476 // and put the rest to unhandled.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002477 auto third_part = SplitBetween(
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002478 second_part, Max(second_part->Start().InstructionEnd(), until),
2479 end.PrevInstruction().InstructionEnd());
2480 if (!AllocationOk()) return;
2481
2482 DCHECK(third_part != second_part);
2483
2484 Spill(second_part);
2485 AddToUnhandledSorted(third_part);
2486 } else {
2487 // The split result does not intersect with [start, end[.
2488 // Nothing to spill. Just put it to unhandled as whole.
2489 AddToUnhandledSorted(second_part);
2490 }
2491}
2492
2493
2494void RegisterAllocator::Spill(LiveRange* range) {
2495 DCHECK(!range->IsSpilled());
2496 TraceAlloc("Spilling live range %d\n", range->id());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002497 auto first = range->TopLevel();
2498 if (first->HasNoSpillType()) {
2499 if (FLAG_turbo_reuse_spill_slots) {
2500 AssignSpillRangeToLiveRange(first);
2501 } else {
2502 auto op = TryReuseSpillSlot(range);
2503 if (op == nullptr) {
2504 // Allocate a new operand referring to the spill slot.
2505 RegisterKind kind = range->Kind();
2506 int index = frame()->AllocateSpillSlot(kind == DOUBLE_REGISTERS);
2507 auto op_kind = kind == DOUBLE_REGISTERS
2508 ? InstructionOperand::DOUBLE_STACK_SLOT
2509 : InstructionOperand::STACK_SLOT;
2510 op = new (code_zone()) InstructionOperand(op_kind, index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002511 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002512 first->SetSpillOperand(op);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002513 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002514 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002515 range->MakeSpilled();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002516}
2517
2518
2519int RegisterAllocator::RegisterCount() const { return num_registers_; }
2520
2521
2522#ifdef DEBUG
2523
2524
2525void RegisterAllocator::Verify() const {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002526 for (auto current : live_ranges()) {
2527 if (current != nullptr) current->Verify();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002528 }
2529}
2530
2531
2532#endif
2533
2534
2535void RegisterAllocator::SetLiveRangeAssignedRegister(LiveRange* range,
2536 int reg) {
2537 if (range->Kind() == DOUBLE_REGISTERS) {
2538 assigned_double_registers_->Add(reg);
2539 } else {
2540 DCHECK(range->Kind() == GENERAL_REGISTERS);
2541 assigned_registers_->Add(reg);
2542 }
2543 range->set_assigned_register(reg, code_zone());
2544}
2545
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002546} // namespace compiler
2547} // namespace internal
2548} // namespace v8