blob: 2a9c88506d142ad6b2b9715cd90fd4b7f42734b9 [file] [log] [blame]
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "register_allocator.h"
18
Ian Rogersc7dd2952014-10-21 23:31:19 -070019#include <sstream>
20
Ian Rogerse77493c2014-08-20 15:08:45 -070021#include "base/bit_vector-inl.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010022#include "code_generator.h"
23#include "ssa_liveness_analysis.h"
24
25namespace art {
26
27static constexpr size_t kMaxLifetimePosition = -1;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010028static constexpr size_t kDefaultNumberOfSpillSlots = 4;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010029
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010030RegisterAllocator::RegisterAllocator(ArenaAllocator* allocator,
31 CodeGenerator* codegen,
32 const SsaLivenessAnalysis& liveness)
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010033 : allocator_(allocator),
34 codegen_(codegen),
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010035 liveness_(liveness),
Nicolas Geoffray39468442014-09-02 15:17:15 +010036 unhandled_core_intervals_(allocator, 0),
37 unhandled_fp_intervals_(allocator, 0),
38 unhandled_(nullptr),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010039 handled_(allocator, 0),
40 active_(allocator, 0),
41 inactive_(allocator, 0),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010042 physical_core_register_intervals_(allocator, codegen->GetNumberOfCoreRegisters()),
43 physical_fp_register_intervals_(allocator, codegen->GetNumberOfFloatingPointRegisters()),
Nicolas Geoffray39468442014-09-02 15:17:15 +010044 temp_intervals_(allocator, 4),
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010045 spill_slots_(allocator, kDefaultNumberOfSpillSlots),
Nicolas Geoffray39468442014-09-02 15:17:15 +010046 safepoints_(allocator, 0),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010047 processing_core_registers_(false),
48 number_of_registers_(-1),
49 registers_array_(nullptr),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010050 blocked_core_registers_(codegen->GetBlockedCoreRegisters()),
51 blocked_fp_registers_(codegen->GetBlockedFloatingPointRegisters()),
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +010052 reserved_out_slots_(0),
53 maximum_number_of_live_registers_(0) {
Nicolas Geoffray71175b72014-10-09 22:13:55 +010054 codegen->SetupBlockedRegisters();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010055 physical_core_register_intervals_.SetSize(codegen->GetNumberOfCoreRegisters());
56 physical_fp_register_intervals_.SetSize(codegen->GetNumberOfFloatingPointRegisters());
Nicolas Geoffray39468442014-09-02 15:17:15 +010057 // Always reserve for the current method and the graph's max out registers.
58 // TODO: compute it instead.
59 reserved_out_slots_ = 1 + codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010060}
61
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010062bool RegisterAllocator::CanAllocateRegistersFor(const HGraph& graph,
63 InstructionSet instruction_set) {
64 if (!Supports(instruction_set)) {
65 return false;
66 }
67 for (size_t i = 0, e = graph.GetBlocks().Size(); i < e; ++i) {
68 for (HInstructionIterator it(graph.GetBlocks().Get(i)->GetInstructions());
69 !it.Done();
70 it.Advance()) {
71 HInstruction* current = it.Current();
Nicolas Geoffray412f10c2014-06-19 10:00:34 +010072 if (current->GetType() == Primitive::kPrimLong && instruction_set != kX86_64) return false;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010073 if ((current->GetType() == Primitive::kPrimFloat || current->GetType() == Primitive::kPrimDouble)
74 && instruction_set != kX86_64) {
75 return false;
76 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010077 }
78 }
79 return true;
80}
81
82static bool ShouldProcess(bool processing_core_registers, LiveInterval* interval) {
Nicolas Geoffray39468442014-09-02 15:17:15 +010083 if (interval == nullptr) return false;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010084 bool is_core_register = (interval->GetType() != Primitive::kPrimDouble)
85 && (interval->GetType() != Primitive::kPrimFloat);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010086 return processing_core_registers == is_core_register;
87}
88
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010089void RegisterAllocator::AllocateRegisters() {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010090 AllocateRegistersInternal();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010091 Resolve();
92
93 if (kIsDebugBuild) {
94 processing_core_registers_ = true;
95 ValidateInternal(true);
96 processing_core_registers_ = false;
97 ValidateInternal(true);
98 }
99}
100
101void RegisterAllocator::BlockRegister(Location location,
102 size_t start,
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100103 size_t end) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100104 int reg = location.reg();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100105 DCHECK(location.IsRegister() || location.IsFpuRegister());
106 LiveInterval* interval = location.IsRegister()
107 ? physical_core_register_intervals_.Get(reg)
108 : physical_fp_register_intervals_.Get(reg);
109 Primitive::Type type = location.IsRegister()
110 ? Primitive::kPrimInt
111 : Primitive::kPrimDouble;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100112 if (interval == nullptr) {
113 interval = LiveInterval::MakeFixedInterval(allocator_, reg, type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100114 if (location.IsRegister()) {
115 physical_core_register_intervals_.Put(reg, interval);
116 } else {
117 physical_fp_register_intervals_.Put(reg, interval);
118 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100119 }
120 DCHECK(interval->GetRegister() == reg);
121 interval->AddRange(start, end);
122}
123
124void RegisterAllocator::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100125 // Iterate post-order, to ensure the list is sorted, and the last added interval
126 // is the one with the lowest start position.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100127 for (HLinearPostOrderIterator it(liveness_); !it.Done(); it.Advance()) {
128 HBasicBlock* block = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800129 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
130 back_it.Advance()) {
131 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100132 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800133 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
134 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100135 }
136 }
137
Nicolas Geoffray39468442014-09-02 15:17:15 +0100138 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
139 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_);
140 processing_core_registers_ = true;
141 unhandled_ = &unhandled_core_intervals_;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100142 for (size_t i = 0, e = physical_core_register_intervals_.Size(); i < e; ++i) {
143 LiveInterval* fixed = physical_core_register_intervals_.Get(i);
144 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700145 // Fixed interval is added to inactive_ instead of unhandled_.
146 // It's also the only type of inactive interval whose start position
147 // can be after the current interval during linear scan.
148 // Fixed interval is never split and never moves to unhandled_.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100149 inactive_.Add(fixed);
150 }
151 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100152 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100153
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100154 size_t saved_maximum_number_of_live_registers = maximum_number_of_live_registers_;
155 maximum_number_of_live_registers_ = 0;
156
Nicolas Geoffray39468442014-09-02 15:17:15 +0100157 inactive_.Reset();
158 active_.Reset();
159 handled_.Reset();
160
161 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
162 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_);
163 processing_core_registers_ = false;
164 unhandled_ = &unhandled_fp_intervals_;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100165 for (size_t i = 0, e = physical_fp_register_intervals_.Size(); i < e; ++i) {
166 LiveInterval* fixed = physical_fp_register_intervals_.Get(i);
167 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700168 // Fixed interval is added to inactive_ instead of unhandled_.
169 // It's also the only type of inactive interval whose start position
170 // can be after the current interval during linear scan.
171 // Fixed interval is never split and never moves to unhandled_.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100172 inactive_.Add(fixed);
173 }
174 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100175 LinearScan();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100176 maximum_number_of_live_registers_ += saved_maximum_number_of_live_registers;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100177}
178
179void RegisterAllocator::ProcessInstruction(HInstruction* instruction) {
180 LocationSummary* locations = instruction->GetLocations();
181 size_t position = instruction->GetLifetimePosition();
182
183 if (locations == nullptr) return;
184
185 // Create synthesized intervals for temporaries.
186 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
187 Location temp = locations->GetTemp(i);
188 if (temp.IsRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100189 BlockRegister(temp, position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100190 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100191 DCHECK(temp.IsUnallocated());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100192 LiveInterval* interval = LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimInt);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100193 temp_intervals_.Add(interval);
194 interval->AddRange(position, position + 1);
195 unhandled_core_intervals_.Add(interval);
196 }
197 }
198
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100199 bool core_register = (instruction->GetType() != Primitive::kPrimDouble)
200 && (instruction->GetType() != Primitive::kPrimFloat);
201
Nicolas Geoffray39468442014-09-02 15:17:15 +0100202 if (locations->CanCall()) {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100203 if (!instruction->IsSuspendCheck()) {
204 codegen_->MarkNotLeaf();
205 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100206 safepoints_.Add(instruction);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100207 if (locations->OnlyCallsOnSlowPath()) {
208 // We add a synthesized range at this position to record the live registers
209 // at this position. Ideally, we could just update the safepoints when locations
210 // are updated, but we currently need to know the full stack size before updating
211 // locations (because of parameters and the fact that we don't have a frame pointer).
212 // And knowing the full stack size requires to know the maximum number of live
213 // registers at calls in slow paths.
214 // By adding the following interval in the algorithm, we can compute this
215 // maximum before updating locations.
216 LiveInterval* interval = LiveInterval::MakeSlowPathInterval(allocator_, instruction);
217 interval->AddRange(position, position + 1);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100218 unhandled_core_intervals_.Add(interval);
219 unhandled_fp_intervals_.Add(interval);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100220 }
221 }
222
223 if (locations->WillCall()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100224 // Block all registers.
225 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100226 BlockRegister(Location::RegisterLocation(i),
Nicolas Geoffray39468442014-09-02 15:17:15 +0100227 position,
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100228 position + 1);
229 }
230 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
231 BlockRegister(Location::FpuRegisterLocation(i),
232 position,
233 position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100234 }
235 }
236
237 for (size_t i = 0; i < instruction->InputCount(); ++i) {
238 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100239 if (input.IsRegister() || input.IsFpuRegister()) {
240 BlockRegister(input, position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100241 }
242 }
243
Nicolas Geoffray39468442014-09-02 15:17:15 +0100244 LiveInterval* current = instruction->GetLiveInterval();
245 if (current == nullptr) return;
246
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100247 GrowableArray<LiveInterval*>& unhandled = core_register
248 ? unhandled_core_intervals_
249 : unhandled_fp_intervals_;
250
Nicolas Geoffray76905622014-09-25 14:39:26 +0100251 DCHECK(unhandled.IsEmpty() || current->StartsBeforeOrAt(unhandled.Peek()));
Nicolas Geoffray39468442014-09-02 15:17:15 +0100252 // Some instructions define their output in fixed register/stack slot. We need
253 // to ensure we know these locations before doing register allocation. For a
254 // given register, we create an interval that covers these locations. The register
255 // will be unavailable at these locations when trying to allocate one for an
256 // interval.
257 //
258 // The backwards walking ensures the ranges are ordered on increasing start positions.
259 Location output = locations->Out();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100260 if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100261 // Shift the interval's start by one to account for the blocked register.
262 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100263 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100264 BlockRegister(output, position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100265 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
266 current->SetSpillSlot(output.GetStackIndex());
267 }
268
269 // If needed, add interval to the list of unhandled intervals.
270 if (current->HasSpillSlot() || instruction->IsConstant()) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100271 // Split just before first register use.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100272 size_t first_register_use = current->FirstRegisterUse();
273 if (first_register_use != kNoLifetime) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100274 LiveInterval* split = Split(current, first_register_use - 1);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000275 // Don't add directly to `unhandled`, it needs to be sorted and the start
Nicolas Geoffray39468442014-09-02 15:17:15 +0100276 // of this new interval might be after intervals already in the list.
277 AddSorted(&unhandled, split);
278 } else {
279 // Nothing to do, we won't allocate a register for this value.
280 }
281 } else {
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000282 // Don't add directly to `unhandled`, temp or safepoint intervals
283 // for this instruction may have been added, and those can be
284 // processed first.
285 AddSorted(&unhandled, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100286 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100287}
288
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100289class AllRangesIterator : public ValueObject {
290 public:
291 explicit AllRangesIterator(LiveInterval* interval)
292 : current_interval_(interval),
293 current_range_(interval->GetFirstRange()) {}
294
295 bool Done() const { return current_interval_ == nullptr; }
296 LiveRange* CurrentRange() const { return current_range_; }
297 LiveInterval* CurrentInterval() const { return current_interval_; }
298
299 void Advance() {
300 current_range_ = current_range_->GetNext();
301 if (current_range_ == nullptr) {
302 current_interval_ = current_interval_->GetNextSibling();
303 if (current_interval_ != nullptr) {
304 current_range_ = current_interval_->GetFirstRange();
305 }
306 }
307 }
308
309 private:
310 LiveInterval* current_interval_;
311 LiveRange* current_range_;
312
313 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
314};
315
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100316bool RegisterAllocator::ValidateInternal(bool log_fatal_on_failure) const {
317 // To simplify unit testing, we eagerly create the array of intervals, and
318 // call the helper method.
319 GrowableArray<LiveInterval*> intervals(allocator_, 0);
320 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
321 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
322 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
323 intervals.Add(instruction->GetLiveInterval());
324 }
325 }
326
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100327 if (processing_core_registers_) {
328 for (size_t i = 0, e = physical_core_register_intervals_.Size(); i < e; ++i) {
329 LiveInterval* fixed = physical_core_register_intervals_.Get(i);
330 if (fixed != nullptr) {
331 intervals.Add(fixed);
332 }
333 }
334 } else {
335 for (size_t i = 0, e = physical_fp_register_intervals_.Size(); i < e; ++i) {
336 LiveInterval* fixed = physical_fp_register_intervals_.Get(i);
337 if (fixed != nullptr) {
338 intervals.Add(fixed);
339 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100340 }
341 }
342
Nicolas Geoffray39468442014-09-02 15:17:15 +0100343 for (size_t i = 0, e = temp_intervals_.Size(); i < e; ++i) {
344 LiveInterval* temp = temp_intervals_.Get(i);
345 if (ShouldProcess(processing_core_registers_, temp)) {
346 intervals.Add(temp);
347 }
348 }
349
350 return ValidateIntervals(intervals, spill_slots_.Size(), reserved_out_slots_, *codegen_,
351 allocator_, processing_core_registers_, log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100352}
353
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100354bool RegisterAllocator::ValidateIntervals(const GrowableArray<LiveInterval*>& intervals,
355 size_t number_of_spill_slots,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100356 size_t number_of_out_slots,
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100357 const CodeGenerator& codegen,
358 ArenaAllocator* allocator,
359 bool processing_core_registers,
360 bool log_fatal_on_failure) {
361 size_t number_of_registers = processing_core_registers
362 ? codegen.GetNumberOfCoreRegisters()
363 : codegen.GetNumberOfFloatingPointRegisters();
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100364 GrowableArray<ArenaBitVector*> liveness_of_values(
365 allocator, number_of_registers + number_of_spill_slots);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100366
367 // Allocate a bit vector per register. A live interval that has a register
368 // allocated will populate the associated bit vector based on its live ranges.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100369 for (size_t i = 0; i < number_of_registers + number_of_spill_slots; ++i) {
370 liveness_of_values.Add(new (allocator) ArenaBitVector(allocator, 0, true));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100371 }
372
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100373 for (size_t i = 0, e = intervals.Size(); i < e; ++i) {
374 for (AllRangesIterator it(intervals.Get(i)); !it.Done(); it.Advance()) {
375 LiveInterval* current = it.CurrentInterval();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100376 HInstruction* defined_by = current->GetParent()->GetDefinedBy();
377 if (current->GetParent()->HasSpillSlot()
378 // Parameters have their own stack slot.
379 && !(defined_by != nullptr && defined_by->IsParameterValue())) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100380 BitVector* liveness_of_spill_slot = liveness_of_values.Get(number_of_registers
381 + current->GetParent()->GetSpillSlot() / kVRegSize
382 - number_of_out_slots);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100383 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
384 if (liveness_of_spill_slot->IsBitSet(j)) {
385 if (log_fatal_on_failure) {
386 std::ostringstream message;
387 message << "Spill slot conflict at " << j;
388 LOG(FATAL) << message.str();
389 } else {
390 return false;
391 }
392 } else {
393 liveness_of_spill_slot->SetBit(j);
394 }
395 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100396 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100397
398 if (current->HasRegister()) {
399 BitVector* liveness_of_register = liveness_of_values.Get(current->GetRegister());
400 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
401 if (liveness_of_register->IsBitSet(j)) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100402 if (log_fatal_on_failure) {
403 std::ostringstream message;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100404 message << "Register conflict at " << j << " ";
405 if (defined_by != nullptr) {
406 message << "(" << defined_by->DebugName() << ")";
407 }
408 message << "for ";
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100409 if (processing_core_registers) {
410 codegen.DumpCoreRegister(message, current->GetRegister());
411 } else {
412 codegen.DumpFloatingPointRegister(message, current->GetRegister());
413 }
414 LOG(FATAL) << message.str();
415 } else {
416 return false;
417 }
418 } else {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100419 liveness_of_register->SetBit(j);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100420 }
421 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100422 }
423 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100424 }
425 return true;
426}
427
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100428void RegisterAllocator::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100429 interval->Dump(stream);
430 stream << ": ";
431 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100432 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100433 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100434 } else {
435 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100436 }
437 } else {
438 stream << "spilled";
439 }
440 stream << std::endl;
441}
442
Mingyao Yang296bd602014-10-06 16:47:28 -0700443void RegisterAllocator::DumpAllIntervals(std::ostream& stream) const {
444 stream << "inactive: " << std::endl;
445 for (size_t i = 0; i < inactive_.Size(); i ++) {
446 DumpInterval(stream, inactive_.Get(i));
447 }
448 stream << "active: " << std::endl;
449 for (size_t i = 0; i < active_.Size(); i ++) {
450 DumpInterval(stream, active_.Get(i));
451 }
452 stream << "unhandled: " << std::endl;
453 auto unhandled = (unhandled_ != nullptr) ?
454 unhandled_ : &unhandled_core_intervals_;
455 for (size_t i = 0; i < unhandled->Size(); i ++) {
456 DumpInterval(stream, unhandled->Get(i));
457 }
458 stream << "handled: " << std::endl;
459 for (size_t i = 0; i < handled_.Size(); i ++) {
460 DumpInterval(stream, handled_.Get(i));
461 }
462}
463
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100464// By the book implementation of a linear scan register allocator.
465void RegisterAllocator::LinearScan() {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100466 while (!unhandled_->IsEmpty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100467 // (1) Remove interval with the lowest start position from unhandled.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100468 LiveInterval* current = unhandled_->Pop();
469 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100470 DCHECK(unhandled_->IsEmpty() || unhandled_->Peek()->GetStart() >= current->GetStart());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100471 size_t position = current->GetStart();
472
Mingyao Yang296bd602014-10-06 16:47:28 -0700473 // Remember the inactive_ size here since the ones moved to inactive_ from
474 // active_ below shouldn't need to be re-checked.
475 size_t inactive_intervals_to_handle = inactive_.Size();
476
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100477 // (2) Remove currently active intervals that are dead at this position.
478 // Move active intervals that have a lifetime hole at this position
479 // to inactive.
480 for (size_t i = 0; i < active_.Size(); ++i) {
481 LiveInterval* interval = active_.Get(i);
482 if (interval->IsDeadAt(position)) {
483 active_.Delete(interval);
484 --i;
485 handled_.Add(interval);
486 } else if (!interval->Covers(position)) {
487 active_.Delete(interval);
488 --i;
489 inactive_.Add(interval);
490 }
491 }
492
493 // (3) Remove currently inactive intervals that are dead at this position.
494 // Move inactive intervals that cover this position to active.
Mingyao Yang296bd602014-10-06 16:47:28 -0700495 for (size_t i = 0; i < inactive_intervals_to_handle; ++i) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100496 LiveInterval* interval = inactive_.Get(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700497 DCHECK(interval->GetStart() < position || interval->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100498 if (interval->IsDeadAt(position)) {
499 inactive_.Delete(interval);
500 --i;
Mingyao Yang296bd602014-10-06 16:47:28 -0700501 --inactive_intervals_to_handle;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100502 handled_.Add(interval);
503 } else if (interval->Covers(position)) {
504 inactive_.Delete(interval);
505 --i;
Mingyao Yang296bd602014-10-06 16:47:28 -0700506 --inactive_intervals_to_handle;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100507 active_.Add(interval);
508 }
509 }
510
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100511 if (current->IsSlowPathSafepoint()) {
512 // Synthesized interval to record the maximum number of live registers
513 // at safepoints. No need to allocate a register for it.
514 maximum_number_of_live_registers_ =
515 std::max(maximum_number_of_live_registers_, active_.Size());
516 continue;
517 }
518
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100519 // (4) Try to find an available register.
520 bool success = TryAllocateFreeReg(current);
521
522 // (5) If no register could be found, we need to spill.
523 if (!success) {
524 success = AllocateBlockedReg(current);
525 }
526
527 // (6) If the interval had a register allocated, add it to the list of active
528 // intervals.
529 if (success) {
530 active_.Add(current);
531 }
532 }
533}
534
535// Find a free register. If multiple are found, pick the register that
536// is free the longest.
537bool RegisterAllocator::TryAllocateFreeReg(LiveInterval* current) {
538 size_t* free_until = registers_array_;
539
540 // First set all registers to be free.
541 for (size_t i = 0; i < number_of_registers_; ++i) {
542 free_until[i] = kMaxLifetimePosition;
543 }
544
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100545 // For each active interval, set its register to not free.
546 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
547 LiveInterval* interval = active_.Get(i);
548 DCHECK(interval->HasRegister());
549 free_until[interval->GetRegister()] = 0;
550 }
551
Mingyao Yang296bd602014-10-06 16:47:28 -0700552 // For each inactive interval, set its register to be free until
553 // the next intersection with `current`.
554 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
555 LiveInterval* inactive = inactive_.Get(i);
556 // Temp/Slow-path-safepoint interval has no holes.
557 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
558 if (!current->IsSplit() && !inactive->IsFixed()) {
559 // Neither current nor inactive are fixed.
560 // Thanks to SSA, a non-split interval starting in a hole of an
561 // inactive interval should never intersect with that inactive interval.
562 // Only if it's not fixed though, because fixed intervals don't come from SSA.
563 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
564 continue;
565 }
566
567 DCHECK(inactive->HasRegister());
568 if (free_until[inactive->GetRegister()] == 0) {
569 // Already used by some active interval. No need to intersect.
570 continue;
571 }
572 size_t next_intersection = inactive->FirstIntersectionWith(current);
573 if (next_intersection != kNoLifetime) {
574 free_until[inactive->GetRegister()] =
575 std::min(free_until[inactive->GetRegister()], next_intersection);
576 }
577 }
578
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100579 int reg = -1;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100580 if (current->HasRegister()) {
581 // Some instructions have a fixed register output.
582 reg = current->GetRegister();
583 DCHECK_NE(free_until[reg], 0u);
584 } else {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100585 int hint = current->FindFirstRegisterHint(free_until);
586 if (hint != kNoRegister) {
587 DCHECK(!IsBlocked(hint));
588 reg = hint;
589 } else {
590 // Pick the register that is free the longest.
591 for (size_t i = 0; i < number_of_registers_; ++i) {
592 if (IsBlocked(i)) continue;
593 if (reg == -1 || free_until[i] > free_until[reg]) {
594 reg = i;
595 if (free_until[i] == kMaxLifetimePosition) break;
596 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100597 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100598 }
599 }
600
601 // If we could not find a register, we need to spill.
602 if (reg == -1 || free_until[reg] == 0) {
603 return false;
604 }
605
606 current->SetRegister(reg);
607 if (!current->IsDeadAt(free_until[reg])) {
608 // If the register is only available for a subset of live ranges
609 // covered by `current`, split `current` at the position where
610 // the register is not available anymore.
611 LiveInterval* split = Split(current, free_until[reg]);
612 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100613 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100614 }
615 return true;
616}
617
618bool RegisterAllocator::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100619 return processing_core_registers_
620 ? blocked_core_registers_[reg]
621 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100622}
623
624// Find the register that is used the last, and spill the interval
625// that holds it. If the first use of `current` is after that register
626// we spill `current` instead.
627bool RegisterAllocator::AllocateBlockedReg(LiveInterval* current) {
628 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffray412f10c2014-06-19 10:00:34 +0100629 if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100630 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100631 return false;
632 }
633
634 // First set all registers as not being used.
635 size_t* next_use = registers_array_;
636 for (size_t i = 0; i < number_of_registers_; ++i) {
637 next_use[i] = kMaxLifetimePosition;
638 }
639
640 // For each active interval, find the next use of its register after the
641 // start of current.
642 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
643 LiveInterval* active = active_.Get(i);
644 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100645 if (active->IsFixed()) {
646 next_use[active->GetRegister()] = current->GetStart();
647 } else {
648 size_t use = active->FirstRegisterUseAfter(current->GetStart());
649 if (use != kNoLifetime) {
650 next_use[active->GetRegister()] = use;
651 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100652 }
653 }
654
655 // For each inactive interval, find the next use of its register after the
656 // start of current.
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100657 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
658 LiveInterval* inactive = inactive_.Get(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700659 // Temp/Slow-path-safepoint interval has no holes.
660 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
661 if (!current->IsSplit() && !inactive->IsFixed()) {
662 // Neither current nor inactive are fixed.
663 // Thanks to SSA, a non-split interval starting in a hole of an
664 // inactive interval should never intersect with that inactive interval.
665 // Only if it's not fixed though, because fixed intervals don't come from SSA.
666 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
667 continue;
668 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100669 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100670 size_t next_intersection = inactive->FirstIntersectionWith(current);
671 if (next_intersection != kNoLifetime) {
672 if (inactive->IsFixed()) {
673 next_use[inactive->GetRegister()] =
674 std::min(next_intersection, next_use[inactive->GetRegister()]);
675 } else {
676 size_t use = inactive->FirstRegisterUseAfter(current->GetStart());
677 if (use != kNoLifetime) {
678 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
679 }
680 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100681 }
682 }
683
684 // Pick the register that is used the last.
685 int reg = -1;
686 for (size_t i = 0; i < number_of_registers_; ++i) {
687 if (IsBlocked(i)) continue;
688 if (reg == -1 || next_use[i] > next_use[reg]) {
689 reg = i;
690 if (next_use[i] == kMaxLifetimePosition) break;
691 }
692 }
693
694 if (first_register_use >= next_use[reg]) {
695 // If the first use of that instruction is after the last use of the found
696 // register, we split this interval just before its first register use.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100697 AllocateSpillSlotFor(current);
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100698 LiveInterval* split = Split(current, first_register_use - 1);
699 DCHECK_NE(current, split) << "There is not enough registers available for "
700 << split->GetParent()->GetDefinedBy()->DebugName();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100701 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100702 return false;
703 } else {
704 // Use this register and spill the active and inactives interval that
705 // have that register.
706 current->SetRegister(reg);
707
708 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
709 LiveInterval* active = active_.Get(i);
710 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100711 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100712 LiveInterval* split = Split(active, current->GetStart());
713 active_.DeleteAt(i);
714 handled_.Add(active);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100715 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100716 break;
717 }
718 }
719
Mingyao Yang296bd602014-10-06 16:47:28 -0700720 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100721 LiveInterval* inactive = inactive_.Get(i);
722 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700723 if (!current->IsSplit() && !inactive->IsFixed()) {
724 // Neither current nor inactive are fixed.
725 // Thanks to SSA, a non-split interval starting in a hole of an
726 // inactive interval should never intersect with that inactive interval.
727 // Only if it's not fixed though, because fixed intervals don't come from SSA.
728 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
729 continue;
730 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100731 size_t next_intersection = inactive->FirstIntersectionWith(current);
732 if (next_intersection != kNoLifetime) {
733 if (inactive->IsFixed()) {
734 LiveInterval* split = Split(current, next_intersection);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100735 AddSorted(unhandled_, split);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100736 } else {
Mingyao Yang296bd602014-10-06 16:47:28 -0700737 LiveInterval* split = Split(inactive, next_intersection);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100738 inactive_.DeleteAt(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700739 --i;
740 --e;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100741 handled_.Add(inactive);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100742 AddSorted(unhandled_, split);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100743 }
744 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100745 }
746 }
747
748 return true;
749 }
750}
751
Nicolas Geoffray39468442014-09-02 15:17:15 +0100752void RegisterAllocator::AddSorted(GrowableArray<LiveInterval*>* array, LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100753 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100754 size_t insert_at = 0;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100755 for (size_t i = array->Size(); i > 0; --i) {
756 LiveInterval* current = array->Get(i - 1);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100757 if (current->StartsAfter(interval)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100758 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100759 break;
760 }
761 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100762 array->InsertAt(insert_at, interval);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100763}
764
765LiveInterval* RegisterAllocator::Split(LiveInterval* interval, size_t position) {
766 DCHECK(position >= interval->GetStart());
767 DCHECK(!interval->IsDeadAt(position));
768 if (position == interval->GetStart()) {
769 // Spill slot will be allocated when handling `interval` again.
770 interval->ClearRegister();
771 return interval;
772 } else {
773 LiveInterval* new_interval = interval->SplitAt(position);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100774 return new_interval;
775 }
776}
777
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100778void RegisterAllocator::AllocateSpillSlotFor(LiveInterval* interval) {
779 LiveInterval* parent = interval->GetParent();
780
781 // An instruction gets a spill slot for its entire lifetime. If the parent
782 // of this interval already has a spill slot, there is nothing to do.
783 if (parent->HasSpillSlot()) {
784 return;
785 }
786
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100787 HInstruction* defined_by = parent->GetDefinedBy();
788 if (defined_by->IsParameterValue()) {
789 // Parameters have their own stack slot.
790 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
791 return;
792 }
793
Nicolas Geoffray96f89a22014-07-11 10:57:49 +0100794 if (defined_by->IsConstant()) {
795 // Constants don't need a spill slot.
796 return;
797 }
798
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100799 LiveInterval* last_sibling = interval;
800 while (last_sibling->GetNextSibling() != nullptr) {
801 last_sibling = last_sibling->GetNextSibling();
802 }
803 size_t end = last_sibling->GetEnd();
804
Nicolas Geoffray412f10c2014-06-19 10:00:34 +0100805 // Find an available spill slot.
806 size_t slot = 0;
807 for (size_t e = spill_slots_.Size(); slot < e; ++slot) {
808 // We check if it is less rather than less or equal because the parallel move
809 // resolver does not work when a single spill slot needs to be exchanged with
810 // a double spill slot. The strict comparison avoids needing to exchange these
811 // locations at the same lifetime position.
812 if (spill_slots_.Get(slot) < parent->GetStart()
813 && (slot == (e - 1) || spill_slots_.Get(slot + 1) < parent->GetStart())) {
814 break;
815 }
816 }
817
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100818 if (parent->NeedsTwoSpillSlots()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100819 if (slot == spill_slots_.Size()) {
820 // We need a new spill slot.
821 spill_slots_.Add(end);
822 spill_slots_.Add(end);
823 } else if (slot == spill_slots_.Size() - 1) {
824 spill_slots_.Put(slot, end);
825 spill_slots_.Add(end);
826 } else {
827 spill_slots_.Put(slot, end);
828 spill_slots_.Put(slot + 1, end);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100829 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100830 } else {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100831 if (slot == spill_slots_.Size()) {
832 // We need a new spill slot.
833 spill_slots_.Add(end);
834 } else {
835 spill_slots_.Put(slot, end);
836 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100837 }
838
Nicolas Geoffray39468442014-09-02 15:17:15 +0100839 parent->SetSpillSlot((slot + reserved_out_slots_) * kVRegSize);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100840}
841
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100842static bool IsValidDestination(Location destination) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100843 return destination.IsRegister()
844 || destination.IsFpuRegister()
845 || destination.IsStackSlot()
846 || destination.IsDoubleStackSlot();
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100847}
848
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100849void RegisterAllocator::AddInputMoveFor(HInstruction* user,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100850 Location source,
851 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100852 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100853 if (source.Equals(destination)) return;
854
Roland Levillain476df552014-10-09 17:51:36 +0100855 DCHECK(!user->IsPhi());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100856
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100857 HInstruction* previous = user->GetPrevious();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100858 HParallelMove* move = nullptr;
859 if (previous == nullptr
Roland Levillain476df552014-10-09 17:51:36 +0100860 || !previous->IsParallelMove()
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +0100861 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100862 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +0100863 move->SetLifetimePosition(user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100864 user->GetBlock()->InsertInstructionBefore(move, user);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100865 } else {
866 move = previous->AsParallelMove();
867 }
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +0100868 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100869 move->AddMove(new (allocator_) MoveOperands(source, destination, nullptr));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100870}
871
872void RegisterAllocator::InsertParallelMoveAt(size_t position,
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100873 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100874 Location source,
875 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100876 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100877 if (source.Equals(destination)) return;
878
879 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
880 if (at == nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700881 // Block boundary, don't do anything the connection of split siblings will handle it.
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100882 return;
883 }
884 HParallelMove* move;
885 if ((position & 1) == 1) {
886 // Move must happen after the instruction.
887 DCHECK(!at->IsControlFlow());
888 move = at->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100889 // This is a parallel move for connecting siblings in a same block. We need to
890 // differentiate it with moves for connecting blocks, and input moves.
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +0100891 if (move == nullptr || move->GetLifetimePosition() > position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100892 move = new (allocator_) HParallelMove(allocator_);
893 move->SetLifetimePosition(position);
894 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
895 }
896 } else {
897 // Move must happen before the instruction.
898 HInstruction* previous = at->GetPrevious();
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100899 if (previous == nullptr
900 || !previous->IsParallelMove()
901 || previous->GetLifetimePosition() != position) {
902 // If the previous is a parallel move, then its position must be lower
903 // than the given `position`: it was added just after the non-parallel
904 // move instruction that precedes `instruction`.
905 DCHECK(previous == nullptr
906 || !previous->IsParallelMove()
907 || previous->GetLifetimePosition() < position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100908 move = new (allocator_) HParallelMove(allocator_);
909 move->SetLifetimePosition(position);
910 at->GetBlock()->InsertInstructionBefore(move, at);
911 } else {
912 move = previous->AsParallelMove();
913 }
914 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100915 DCHECK_EQ(move->GetLifetimePosition(), position);
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100916 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100917}
918
919void RegisterAllocator::InsertParallelMoveAtExitOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100920 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100921 Location source,
922 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100923 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100924 if (source.Equals(destination)) return;
925
926 DCHECK_EQ(block->GetSuccessors().Size(), 1u);
927 HInstruction* last = block->GetLastInstruction();
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100928 // We insert moves at exit for phi predecessors and connecting blocks.
929 // A block ending with an if cannot branch to a block with phis because
930 // we do not allow critical edges. It can also not connect
931 // a split interval between two blocks: the move has to happen in the successor.
932 DCHECK(!last->IsIf());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100933 HInstruction* previous = last->GetPrevious();
934 HParallelMove* move;
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100935 // This is a parallel move for connecting blocks. We need to differentiate
936 // it with moves for connecting siblings in a same block, and output moves.
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100937 if (previous == nullptr || !previous->IsParallelMove()
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100938 || previous->AsParallelMove()->GetLifetimePosition() != block->GetLifetimeEnd()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100939 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100940 move->SetLifetimePosition(block->GetLifetimeEnd());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100941 block->InsertInstructionBefore(move, last);
942 } else {
943 move = previous->AsParallelMove();
944 }
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100945 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100946}
947
948void RegisterAllocator::InsertParallelMoveAtEntryOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100949 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100950 Location source,
951 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100952 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100953 if (source.Equals(destination)) return;
954
955 HInstruction* first = block->GetFirstInstruction();
956 HParallelMove* move = first->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100957 // This is a parallel move for connecting blocks. We need to differentiate
958 // it with moves for connecting siblings in a same block, and input moves.
959 if (move == nullptr || move->GetLifetimePosition() != block->GetLifetimeStart()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100960 move = new (allocator_) HParallelMove(allocator_);
961 move->SetLifetimePosition(block->GetLifetimeStart());
962 block->InsertInstructionBefore(move, first);
963 }
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100964 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100965}
966
967void RegisterAllocator::InsertMoveAfter(HInstruction* instruction,
968 Location source,
969 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +0100970 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100971 if (source.Equals(destination)) return;
972
Roland Levillain476df552014-10-09 17:51:36 +0100973 if (instruction->IsPhi()) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100974 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100975 return;
976 }
977
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100978 size_t position = instruction->GetLifetimePosition() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100979 HParallelMove* move = instruction->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100980 // This is a parallel move for moving the output of an instruction. We need
981 // to differentiate with input moves, moves for connecting siblings in a
982 // and moves for connecting blocks.
983 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100984 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +0100985 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100986 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
987 }
Nicolas Geoffray740475d2014-09-29 10:33:25 +0100988 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100989}
990
991void RegisterAllocator::ConnectSiblings(LiveInterval* interval) {
992 LiveInterval* current = interval;
993 if (current->HasSpillSlot() && current->HasRegister()) {
994 // We spill eagerly, so move must be at definition.
995 InsertMoveAfter(interval->GetDefinedBy(),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100996 interval->IsFloatingPoint()
997 ? Location::FpuRegisterLocation(interval->GetRegister())
998 : Location::RegisterLocation(interval->GetRegister()),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100999 interval->NeedsTwoSpillSlots()
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001000 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
1001 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001002 }
1003 UsePosition* use = current->GetFirstUse();
1004
1005 // Walk over all siblings, updating locations of use positions, and
1006 // connecting them when they are adjacent.
1007 do {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001008 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001009
1010 // Walk over all uses covered by this interval, and update the location
1011 // information.
1012 while (use != nullptr && use->GetPosition() <= current->GetEnd()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001013 LocationSummary* locations = use->GetUser()->GetLocations();
1014 if (use->GetIsEnvironment()) {
1015 locations->SetEnvironmentAt(use->GetInputIndex(), source);
1016 } else {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001017 Location expected_location = locations->InAt(use->GetInputIndex());
1018 if (expected_location.IsUnallocated()) {
1019 locations->SetInAt(use->GetInputIndex(), source);
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001020 } else if (!expected_location.IsConstant()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001021 AddInputMoveFor(use->GetUser(), source, expected_location);
1022 }
1023 }
1024 use = use->GetNext();
1025 }
1026
1027 // If the next interval starts just after this one, and has a register,
1028 // insert a move.
1029 LiveInterval* next_sibling = current->GetNextSibling();
1030 if (next_sibling != nullptr
1031 && next_sibling->HasRegister()
1032 && current->GetEnd() == next_sibling->GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001033 Location destination = next_sibling->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001034 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001035 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001036
1037 // At each safepoint, we record stack and register information.
1038 for (size_t i = 0, e = safepoints_.Size(); i < e; ++i) {
1039 HInstruction* safepoint = safepoints_.Get(i);
1040 size_t position = safepoint->GetLifetimePosition();
1041 LocationSummary* locations = safepoint->GetLocations();
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +00001042 if (!current->Covers(position)) {
1043 continue;
1044 }
1045 if (interval->GetStart() == position) {
1046 // The safepoint is for this instruction, so the location of the instruction
1047 // does not need to be saved.
1048 continue;
1049 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001050
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001051 if ((current->GetType() == Primitive::kPrimNot) && current->GetParent()->HasSpillSlot()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001052 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
1053 }
1054
1055 switch (source.GetKind()) {
1056 case Location::kRegister: {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001057 locations->AddLiveRegister(source);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001058 if (current->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001059 locations->SetRegisterBit(source.reg());
Nicolas Geoffray39468442014-09-02 15:17:15 +01001060 }
1061 break;
1062 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001063 case Location::kFpuRegister: {
1064 locations->AddLiveRegister(source);
1065 break;
1066 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001067 case Location::kStackSlot: // Fall-through
1068 case Location::kDoubleStackSlot: // Fall-through
1069 case Location::kConstant: {
1070 // Nothing to do.
1071 break;
1072 }
1073 default: {
1074 LOG(FATAL) << "Unexpected location for object";
1075 }
1076 }
1077 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001078 current = next_sibling;
1079 } while (current != nullptr);
1080 DCHECK(use == nullptr);
1081}
1082
1083void RegisterAllocator::ConnectSplitSiblings(LiveInterval* interval,
1084 HBasicBlock* from,
1085 HBasicBlock* to) const {
1086 if (interval->GetNextSibling() == nullptr) {
1087 // Nothing to connect. The whole range was allocated to the same location.
1088 return;
1089 }
1090
1091 size_t from_position = from->GetLifetimeEnd() - 1;
Mingyao Yang296bd602014-10-06 16:47:28 -07001092 // When an instruction dies at entry of another, and the latter is the beginning
Nicolas Geoffray76905622014-09-25 14:39:26 +01001093 // of a block, the register allocator ensures the former has a register
1094 // at block->GetLifetimeStart() + 1. Since this is at a block boundary, it must
1095 // must be handled in this method.
1096 size_t to_position = to->GetLifetimeStart() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001097
1098 LiveInterval* destination = nullptr;
1099 LiveInterval* source = nullptr;
1100
1101 LiveInterval* current = interval;
1102
1103 // Check the intervals that cover `from` and `to`.
1104 while ((current != nullptr) && (source == nullptr || destination == nullptr)) {
1105 if (current->Covers(from_position)) {
1106 DCHECK(source == nullptr);
1107 source = current;
1108 }
1109 if (current->Covers(to_position)) {
1110 DCHECK(destination == nullptr);
1111 destination = current;
1112 }
1113
1114 current = current->GetNextSibling();
1115 }
1116
1117 if (destination == source) {
1118 // Interval was not split.
1119 return;
1120 }
1121
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +01001122 DCHECK(destination != nullptr && source != nullptr);
1123
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001124 if (!destination->HasRegister()) {
1125 // Values are eagerly spilled. Spill slot already contains appropriate value.
1126 return;
1127 }
1128
1129 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
1130 // we need to put the moves at the entry of `to`.
1131 if (from->GetSuccessors().Size() == 1) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001132 InsertParallelMoveAtExitOf(from,
1133 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001134 source->ToLocation(),
1135 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001136 } else {
1137 DCHECK_EQ(to->GetPredecessors().Size(), 1u);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001138 InsertParallelMoveAtEntryOf(to,
1139 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001140 source->ToLocation(),
1141 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001142 }
1143}
1144
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001145void RegisterAllocator::Resolve() {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001146 codegen_->ComputeFrameSize(
1147 spill_slots_.Size(), maximum_number_of_live_registers_, reserved_out_slots_);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001148
1149 // Adjust the Out Location of instructions.
1150 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
1151 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1152 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1153 LiveInterval* current = instruction->GetLiveInterval();
1154 LocationSummary* locations = instruction->GetLocations();
1155 Location location = locations->Out();
Roland Levillain476df552014-10-09 17:51:36 +01001156 if (instruction->IsParameterValue()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001157 // Now that we know the frame size, adjust the parameter's location.
1158 if (location.IsStackSlot()) {
1159 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1160 current->SetSpillSlot(location.GetStackIndex());
1161 locations->SetOut(location);
1162 } else if (location.IsDoubleStackSlot()) {
1163 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1164 current->SetSpillSlot(location.GetStackIndex());
1165 locations->SetOut(location);
1166 } else if (current->HasSpillSlot()) {
1167 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
1168 }
1169 }
1170
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001171 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001172
1173 if (location.IsUnallocated()) {
1174 if (location.GetPolicy() == Location::kSameAsFirstInput) {
1175 locations->SetInAt(0, source);
1176 }
1177 locations->SetOut(source);
1178 } else {
1179 DCHECK(source.Equals(location));
1180 }
1181 }
1182
1183 // Connect siblings.
1184 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1185 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1186 ConnectSiblings(instruction->GetLiveInterval());
1187 }
1188
1189 // Resolve non-linear control flow across branches. Order does not matter.
1190 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
1191 HBasicBlock* block = it.Current();
1192 BitVector* live = liveness_.GetLiveInSet(*block);
1193 for (uint32_t idx : live->Indexes()) {
1194 HInstruction* current = liveness_.GetInstructionFromSsaIndex(idx);
1195 LiveInterval* interval = current->GetLiveInterval();
1196 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
1197 ConnectSplitSiblings(interval, block->GetPredecessors().Get(i), block);
1198 }
1199 }
1200 }
1201
1202 // Resolve phi inputs. Order does not matter.
1203 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
1204 HBasicBlock* current = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001205 for (HInstructionIterator inst_it(current->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
1206 HInstruction* phi = inst_it.Current();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001207 for (size_t i = 0, e = current->GetPredecessors().Size(); i < e; ++i) {
1208 HBasicBlock* predecessor = current->GetPredecessors().Get(i);
1209 DCHECK_EQ(predecessor->GetSuccessors().Size(), 1u);
1210 HInstruction* input = phi->InputAt(i);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001211 Location source = input->GetLiveInterval()->GetLocationAt(
1212 predecessor->GetLifetimeEnd() - 1);
1213 Location destination = phi->GetLiveInterval()->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001214 InsertParallelMoveAtExitOf(predecessor, nullptr, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001215 }
1216 }
1217 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001218
1219 // Assign temp locations.
1220 HInstruction* current = nullptr;
1221 size_t temp_index = 0;
1222 for (size_t i = 0; i < temp_intervals_.Size(); ++i) {
1223 LiveInterval* temp = temp_intervals_.Get(i);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001224 HInstruction* at = liveness_.GetTempUser(temp);
1225 if (at != current) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001226 temp_index = 0;
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001227 current = at;
Nicolas Geoffray39468442014-09-02 15:17:15 +01001228 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001229 LocationSummary* locations = at->GetLocations();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001230 DCHECK(temp->GetType() == Primitive::kPrimInt);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001231 locations->SetTempAt(
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001232 temp_index++, Location::RegisterLocation(temp->GetRegister()));
Nicolas Geoffray39468442014-09-02 15:17:15 +01001233 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001234}
1235
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001236} // namespace art