summaryrefslogtreecommitdiff
path: root/deps/v8/src/compiler/greedy-allocator.cc
blob: 2da30bd2897510e720ae77f8db9b6ddb621e7052 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/greedy-allocator.h"
#include "src/compiler/register-allocator.h"

namespace v8 {
namespace internal {
namespace compiler {


#define TRACE(...)                             \
  do {                                         \
    if (FLAG_trace_alloc) PrintF(__VA_ARGS__); \
  } while (false)


const float GreedyAllocator::kAllocatedRangeMultiplier = 10.0;


namespace {


void UpdateOperands(LiveRange* range, RegisterAllocationData* data) {
  int reg_id = range->assigned_register();
  range->SetUseHints(reg_id);
  if (range->is_phi()) {
    data->GetPhiMapValueFor(range->id())->set_assigned_register(reg_id);
  }
}


LiveRange* Split(LiveRange* range, RegisterAllocationData* data,
                 LifetimePosition pos) {
  DCHECK(range->Start() < pos && pos < range->End());
  DCHECK(pos.IsStart() || pos.IsGapPosition() ||
         (data->code()
              ->GetInstructionBlock(pos.ToInstructionIndex())
              ->last_instruction_index() != pos.ToInstructionIndex()));
  LiveRange* result = data->NewChildRangeFor(range);
  range->SplitAt(pos, result, data->allocation_zone());
  return result;
}


// TODO(mtrofin): explain why splitting in gap START is always OK.
LifetimePosition GetSplitPositionForInstruction(const LiveRange* range,
                                                const InstructionSequence* code,
                                                int instruction_index) {
  LifetimePosition ret = LifetimePosition::Invalid();

  ret = LifetimePosition::GapFromInstructionIndex(instruction_index);
  if (range->Start() >= ret || ret >= range->End()) {
    return LifetimePosition::Invalid();
  }
  return ret;
}


int GetFirstGapIndex(const UseInterval* interval) {
  LifetimePosition start = interval->start();
  int ret = start.ToInstructionIndex();
  return ret;
}


int GetLastGapIndex(const UseInterval* interval) {
  LifetimePosition end = interval->end();
  return end.ToInstructionIndex();
}


// Basic heuristic for advancing the algorithm, if any other splitting heuristic
// failed.
LifetimePosition GetLastResortSplitPosition(const LiveRange* range,
                                            const InstructionSequence* code) {
  if (range->first_interval()->next() != nullptr) {
    return range->first_interval()->next()->start();
  }

  UseInterval* interval = range->first_interval();
  int first = GetFirstGapIndex(interval);
  int last = GetLastGapIndex(interval);
  if (first == last) return LifetimePosition::Invalid();

  // TODO(mtrofin:) determine why we can't just split somewhere arbitrary
  // within the range, e.g. it's middle.
  for (UsePosition* pos = range->first_pos(); pos != nullptr;
       pos = pos->next()) {
    if (pos->type() != UsePositionType::kRequiresRegister) continue;
    LifetimePosition before = GetSplitPositionForInstruction(
        range, code, pos->pos().ToInstructionIndex());
    if (before.IsValid()) return before;
    LifetimePosition after = GetSplitPositionForInstruction(
        range, code, pos->pos().ToInstructionIndex() + 1);
    if (after.IsValid()) return after;
  }
  return LifetimePosition::Invalid();
}


bool IsProgressPossible(const LiveRange* range,
                        const InstructionSequence* code) {
  return range->CanBeSpilled(range->Start()) ||
         GetLastResortSplitPosition(range, code).IsValid();
}
}  // namespace


AllocationCandidate AllocationScheduler::GetNext() {
  DCHECK(!queue_.empty());
  AllocationCandidate ret = queue_.top();
  queue_.pop();
  return ret;
}


void AllocationScheduler::Schedule(LiveRange* range) {
  TRACE("Scheduling live range %d.\n", range->id());
  queue_.push(AllocationCandidate(range));
}

GreedyAllocator::GreedyAllocator(RegisterAllocationData* data,
                                 RegisterKind kind, Zone* local_zone)
    : RegisterAllocator(data, kind),
      local_zone_(local_zone),
      allocations_(local_zone),
      scheduler_(local_zone) {}


void GreedyAllocator::AssignRangeToRegister(int reg_id, LiveRange* range) {
  TRACE("Assigning register %s to live range %d\n", RegisterName(reg_id),
        range->id());

  DCHECK(!range->HasRegisterAssigned());

  AllocateRegisterToRange(reg_id, range);

  TRACE("Assigning %s to range %d\n", RegisterName(reg_id), range->id());
  range->set_assigned_register(reg_id);
}


void GreedyAllocator::PreallocateFixedRanges() {
  allocations_.resize(num_registers());
  for (int i = 0; i < num_registers(); i++) {
    allocations_[i] = new (local_zone()) CoalescedLiveRanges(local_zone());
  }

  for (LiveRange* fixed_range : GetFixedRegisters()) {
    if (fixed_range != nullptr) {
      DCHECK_EQ(mode(), fixed_range->kind());
      DCHECK(fixed_range->IsFixed());

      int reg_nr = fixed_range->assigned_register();
      EnsureValidRangeWeight(fixed_range);
      AllocateRegisterToRange(reg_nr, fixed_range);
    }
  }
}


void GreedyAllocator::ScheduleAllocationCandidates() {
  for (auto range : data()->live_ranges()) {
    if (CanProcessRange(range) && !range->spilled()) {
      scheduler().Schedule(range);
    }
  }
}


void GreedyAllocator::TryAllocateCandidate(
    const AllocationCandidate& candidate) {
  // At this point, this is just a live range. TODO: groups.
  TryAllocateLiveRange(candidate.live_range());
}


void GreedyAllocator::TryAllocateLiveRange(LiveRange* range) {
  // TODO(mtrofin): once we introduce groups, we'll want to first try and
  // allocate at the preferred register.
  TRACE("Attempting to allocate live range %d\n", range->id());
  int free_reg = -1;
  int evictable_reg = -1;
  EnsureValidRangeWeight(range);
  DCHECK(range->weight() != LiveRange::kInvalidWeight);

  float smallest_weight = LiveRange::kMaxWeight;

  // Seek either the first free register, or, from the set of registers
  // where the maximum conflict is lower than the candidate's weight, the one
  // with the smallest such weight.
  for (int i = 0; i < num_registers(); i++) {
    float max_conflict_weight = GetMaximumConflictingWeight(i, range);
    if (max_conflict_weight == LiveRange::kInvalidWeight) {
      free_reg = i;
      break;
    }
    if (max_conflict_weight < range->weight() &&
        max_conflict_weight < smallest_weight) {
      smallest_weight = max_conflict_weight;
      evictable_reg = i;
    }
  }

  // We have a free register, so we use it.
  if (free_reg >= 0) {
    TRACE("Found free register %s for live range %d\n", RegisterName(free_reg),
          range->id());
    AssignRangeToRegister(free_reg, range);
    return;
  }

  // We found a register to perform evictions, so we evict and allocate our
  // candidate.
  if (evictable_reg >= 0) {
    TRACE("Found evictable register %s for live range %d\n",
          RegisterName(free_reg), range->id());
    EvictAndRescheduleConflicts(evictable_reg, range);
    AssignRangeToRegister(evictable_reg, range);
    return;
  }

  // The range needs to be split or spilled.
  SplitOrSpillBlockedRange(range);
}


void GreedyAllocator::EvictAndRescheduleConflicts(unsigned reg_id,
                                                  const LiveRange* range) {
  auto conflicts = current_allocations(reg_id)->GetConflicts(range);
  for (LiveRange* conflict = conflicts.Current(); conflict != nullptr;
       conflict = conflicts.RemoveCurrentAndGetNext()) {
    DCHECK(conflict->HasRegisterAssigned());
    CHECK(!conflict->IsFixed());
    conflict->UnsetAssignedRegister();
    UpdateWeightAtEviction(conflict);
    scheduler().Schedule(conflict);
    TRACE("Evicted range %d.\n", conflict->id());
  }
}


void GreedyAllocator::SplitAndSpillRangesDefinedByMemoryOperand() {
  size_t initial_range_count = data()->live_ranges().size();
  for (size_t i = 0; i < initial_range_count; ++i) {
    auto range = data()->live_ranges()[i];
    if (!CanProcessRange(range)) continue;
    if (range->HasNoSpillType()) continue;

    LifetimePosition start = range->Start();
    TRACE("Live range %d is defined by a spill operand.\n", range->id());
    auto next_pos = start;
    if (next_pos.IsGapPosition()) {
      next_pos = next_pos.NextStart();
    }
    auto pos = range->NextUsePositionRegisterIsBeneficial(next_pos);
    // If the range already has a spill operand and it doesn't need a
    // register immediately, split it and spill the first part of the range.
    if (pos == nullptr) {
      Spill(range);
    } else if (pos->pos() > range->Start().NextStart()) {
      // Do not spill live range eagerly if use position that can benefit from
      // the register is too close to the start of live range.
      auto split_pos = pos->pos();
      if (data()->IsBlockBoundary(split_pos.Start())) {
        split_pos = split_pos.Start();
      } else {
        split_pos = split_pos.PrevStart().End();
      }
      Split(range, data(), split_pos);
      Spill(range);
    }
  }
}


void GreedyAllocator::AllocateRegisters() {
  CHECK(scheduler().empty());
  CHECK(allocations_.empty());

  TRACE("Begin allocating function %s with the Greedy Allocator\n",
        data()->debug_name());

  SplitAndSpillRangesDefinedByMemoryOperand();
  PreallocateFixedRanges();
  ScheduleAllocationCandidates();

  while (!scheduler().empty()) {
    AllocationCandidate candidate = scheduler().GetNext();
    TryAllocateCandidate(candidate);
  }


  // We do not rely on the hint mechanism used by LinearScan, so no need to
  // actively update/reset operands until the end.
  for (auto range : data()->live_ranges()) {
    if (CanProcessRange(range) && range->HasRegisterAssigned()) {
      UpdateOperands(range, data());
    }
  }

  for (size_t i = 0; i < allocations_.size(); ++i) {
    if (!allocations_[i]->empty()) {
      data()->MarkAllocated(mode(), static_cast<int>(i));
    }
  }
  allocations_.clear();

  TRACE("End allocating function %s with the Greedy Allocator\n",
        data()->debug_name());
}


float GreedyAllocator::GetMaximumConflictingWeight(
    unsigned reg_id, const LiveRange* range) const {
  float ret = LiveRange::kInvalidWeight;

  auto conflicts = current_allocations(reg_id)->GetConflicts(range);
  for (LiveRange* conflict = conflicts.Current(); conflict != nullptr;
       conflict = conflicts.GetNext()) {
    DCHECK_NE(conflict->weight(), LiveRange::kInvalidWeight);
    ret = Max(ret, conflict->weight());
    if (ret == LiveRange::kMaxWeight) return ret;
  }

  return ret;
}


void GreedyAllocator::EnsureValidRangeWeight(LiveRange* range) {
  // The live range weight will be invalidated when ranges are created or split.
  // Otherwise, it is consistently updated when the range is allocated or
  // unallocated.
  if (range->weight() != LiveRange::kInvalidWeight) return;

  if (range->IsFixed()) {
    range->set_weight(LiveRange::kMaxWeight);
    return;
  }
  if (!IsProgressPossible(range, code())) {
    range->set_weight(LiveRange::kMaxWeight);
    return;
  }

  float use_count = 0.0;
  for (auto pos = range->first_pos(); pos != nullptr; pos = pos->next()) {
    ++use_count;
  }
  range->set_weight(use_count / static_cast<float>(range->GetSize()));
}


void GreedyAllocator::SpillRangeAsLastResort(LiveRange* range) {
  LifetimePosition start = range->Start();
  CHECK(range->CanBeSpilled(start));

  DCHECK(range->NextRegisterPosition(start) == nullptr);
  Spill(range);
}


void GreedyAllocator::SplitOrSpillBlockedRange(LiveRange* range) {
  // TODO(mtrofin): replace the call below with the entry point selecting
  // heuristics, once they exist, out of which GLRSP is the last one.
  auto pos = GetLastResortSplitPosition(range, code());
  if (pos.IsValid()) {
    LiveRange* tail = Split(range, data(), pos);
    DCHECK(tail != range);
    scheduler().Schedule(tail);
    scheduler().Schedule(range);
    return;
  }
  SpillRangeAsLastResort(range);
}


}  // namespace compiler
}  // namespace internal
}  // namespace v8