blob: 6f8f688a2bfca3fe56f8a1f20233f9b6ffbf21b9 [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 Geoffray840e5462015-01-07 16:01:24 +000030// For simplicity, we implement register pairs as (reg, reg + 1).
31// Note that this is a requirement for double registers on ARM, since we
32// allocate SRegister.
33static int GetHighForLowRegister(int reg) { return reg + 1; }
34static bool IsLowRegister(int reg) { return (reg & 1) == 0; }
35
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010036RegisterAllocator::RegisterAllocator(ArenaAllocator* allocator,
37 CodeGenerator* codegen,
38 const SsaLivenessAnalysis& liveness)
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010039 : allocator_(allocator),
40 codegen_(codegen),
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010041 liveness_(liveness),
Nicolas Geoffray39468442014-09-02 15:17:15 +010042 unhandled_core_intervals_(allocator, 0),
43 unhandled_fp_intervals_(allocator, 0),
44 unhandled_(nullptr),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010045 handled_(allocator, 0),
46 active_(allocator, 0),
47 inactive_(allocator, 0),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010048 physical_core_register_intervals_(allocator, codegen->GetNumberOfCoreRegisters()),
49 physical_fp_register_intervals_(allocator, codegen->GetNumberOfFloatingPointRegisters()),
Nicolas Geoffray39468442014-09-02 15:17:15 +010050 temp_intervals_(allocator, 4),
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010051 spill_slots_(allocator, kDefaultNumberOfSpillSlots),
Nicolas Geoffray39468442014-09-02 15:17:15 +010052 safepoints_(allocator, 0),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010053 processing_core_registers_(false),
54 number_of_registers_(-1),
55 registers_array_(nullptr),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010056 blocked_core_registers_(codegen->GetBlockedCoreRegisters()),
57 blocked_fp_registers_(codegen->GetBlockedFloatingPointRegisters()),
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +010058 reserved_out_slots_(0),
Mark Mendellf85a9ca2015-01-13 09:20:58 -050059 maximum_number_of_live_core_registers_(0),
60 maximum_number_of_live_fp_registers_(0) {
Nicolas Geoffray98893962015-01-21 12:32:32 +000061 static constexpr bool kIsBaseline = false;
62 codegen->SetupBlockedRegisters(kIsBaseline);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010063 physical_core_register_intervals_.SetSize(codegen->GetNumberOfCoreRegisters());
64 physical_fp_register_intervals_.SetSize(codegen->GetNumberOfFloatingPointRegisters());
Nicolas Geoffray39468442014-09-02 15:17:15 +010065 // Always reserve for the current method and the graph's max out registers.
66 // TODO: compute it instead.
67 reserved_out_slots_ = 1 + codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010068}
69
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010070bool RegisterAllocator::CanAllocateRegistersFor(const HGraph& graph,
71 InstructionSet instruction_set) {
72 if (!Supports(instruction_set)) {
73 return false;
74 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +000075 if (instruction_set == kArm64
76 || instruction_set == kX86_64
77 || instruction_set == kArm
78 || instruction_set == kThumb2) {
Alexandre Rames3e69f162014-12-10 10:36:50 +000079 return true;
80 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010081 for (size_t i = 0, e = graph.GetBlocks().Size(); i < e; ++i) {
82 for (HInstructionIterator it(graph.GetBlocks().Get(i)->GetInstructions());
83 !it.Done();
84 it.Advance()) {
85 HInstruction* current = it.Current();
Mark Mendell7c8d0092015-01-26 11:21:33 -050086 if (instruction_set == kX86 && current->GetType() == Primitive::kPrimLong) {
87 return false;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010088 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010089 }
90 }
91 return true;
92}
93
94static bool ShouldProcess(bool processing_core_registers, LiveInterval* interval) {
Nicolas Geoffray39468442014-09-02 15:17:15 +010095 if (interval == nullptr) return false;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010096 bool is_core_register = (interval->GetType() != Primitive::kPrimDouble)
97 && (interval->GetType() != Primitive::kPrimFloat);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010098 return processing_core_registers == is_core_register;
99}
100
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100101void RegisterAllocator::AllocateRegisters() {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100102 AllocateRegistersInternal();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100103 Resolve();
104
105 if (kIsDebugBuild) {
106 processing_core_registers_ = true;
107 ValidateInternal(true);
108 processing_core_registers_ = false;
109 ValidateInternal(true);
Nicolas Geoffray59768572014-12-01 09:50:04 +0000110 // Check that the linear order is still correct with regards to lifetime positions.
111 // Since only parallel moves have been inserted during the register allocation,
112 // these checks are mostly for making sure these moves have been added correctly.
113 size_t current_liveness = 0;
114 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
115 HBasicBlock* block = it.Current();
116 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
117 HInstruction* instruction = inst_it.Current();
118 DCHECK_LE(current_liveness, instruction->GetLifetimePosition());
119 current_liveness = instruction->GetLifetimePosition();
120 }
121 for (HInstructionIterator inst_it(block->GetInstructions());
122 !inst_it.Done();
123 inst_it.Advance()) {
124 HInstruction* instruction = inst_it.Current();
125 DCHECK_LE(current_liveness, instruction->GetLifetimePosition()) << instruction->DebugName();
126 current_liveness = instruction->GetLifetimePosition();
127 }
128 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100129 }
130}
131
132void RegisterAllocator::BlockRegister(Location location,
133 size_t start,
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100134 size_t end) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100135 int reg = location.reg();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100136 DCHECK(location.IsRegister() || location.IsFpuRegister());
137 LiveInterval* interval = location.IsRegister()
138 ? physical_core_register_intervals_.Get(reg)
139 : physical_fp_register_intervals_.Get(reg);
140 Primitive::Type type = location.IsRegister()
141 ? Primitive::kPrimInt
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000142 : Primitive::kPrimFloat;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100143 if (interval == nullptr) {
144 interval = LiveInterval::MakeFixedInterval(allocator_, reg, type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100145 if (location.IsRegister()) {
146 physical_core_register_intervals_.Put(reg, interval);
147 } else {
148 physical_fp_register_intervals_.Put(reg, interval);
149 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100150 }
151 DCHECK(interval->GetRegister() == reg);
152 interval->AddRange(start, end);
153}
154
155void RegisterAllocator::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100156 // Iterate post-order, to ensure the list is sorted, and the last added interval
157 // is the one with the lowest start position.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100158 for (HLinearPostOrderIterator it(liveness_); !it.Done(); it.Advance()) {
159 HBasicBlock* block = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800160 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
161 back_it.Advance()) {
162 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100163 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800164 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
165 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100166 }
167 }
168
Nicolas Geoffray39468442014-09-02 15:17:15 +0100169 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
170 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_);
171 processing_core_registers_ = true;
172 unhandled_ = &unhandled_core_intervals_;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100173 for (size_t i = 0, e = physical_core_register_intervals_.Size(); i < e; ++i) {
174 LiveInterval* fixed = physical_core_register_intervals_.Get(i);
175 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700176 // Fixed interval is added to inactive_ instead of unhandled_.
177 // It's also the only type of inactive interval whose start position
178 // can be after the current interval during linear scan.
179 // Fixed interval is never split and never moves to unhandled_.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100180 inactive_.Add(fixed);
181 }
182 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100183 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100184
185 inactive_.Reset();
186 active_.Reset();
187 handled_.Reset();
188
189 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
190 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_);
191 processing_core_registers_ = false;
192 unhandled_ = &unhandled_fp_intervals_;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100193 for (size_t i = 0, e = physical_fp_register_intervals_.Size(); i < e; ++i) {
194 LiveInterval* fixed = physical_fp_register_intervals_.Get(i);
195 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700196 // Fixed interval is added to inactive_ instead of unhandled_.
197 // It's also the only type of inactive interval whose start position
198 // can be after the current interval during linear scan.
199 // Fixed interval is never split and never moves to unhandled_.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100200 inactive_.Add(fixed);
201 }
202 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100203 LinearScan();
204}
205
206void RegisterAllocator::ProcessInstruction(HInstruction* instruction) {
207 LocationSummary* locations = instruction->GetLocations();
208 size_t position = instruction->GetLifetimePosition();
209
210 if (locations == nullptr) return;
211
212 // Create synthesized intervals for temporaries.
213 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
214 Location temp = locations->GetTemp(i);
Nicolas Geoffray52839d12014-11-07 17:47:25 +0000215 if (temp.IsRegister() || temp.IsFpuRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100216 BlockRegister(temp, position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100217 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100218 DCHECK(temp.IsUnallocated());
Roland Levillain5368c212014-11-27 15:03:41 +0000219 switch (temp.GetPolicy()) {
220 case Location::kRequiresRegister: {
221 LiveInterval* interval =
222 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimInt);
223 temp_intervals_.Add(interval);
224 interval->AddRange(position, position + 1);
225 unhandled_core_intervals_.Add(interval);
226 break;
227 }
228
229 case Location::kRequiresFpuRegister: {
230 LiveInterval* interval =
231 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimDouble);
232 temp_intervals_.Add(interval);
233 interval->AddRange(position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000234 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
235 interval->AddHighInterval(true);
236 LiveInterval* high = interval->GetHighInterval();
237 temp_intervals_.Add(high);
238 unhandled_fp_intervals_.Add(high);
239 }
Roland Levillain5368c212014-11-27 15:03:41 +0000240 unhandled_fp_intervals_.Add(interval);
241 break;
242 }
243
244 default:
245 LOG(FATAL) << "Unexpected policy for temporary location "
246 << temp.GetPolicy();
247 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100248 }
249 }
250
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100251 bool core_register = (instruction->GetType() != Primitive::kPrimDouble)
252 && (instruction->GetType() != Primitive::kPrimFloat);
253
Nicolas Geoffray39468442014-09-02 15:17:15 +0100254 if (locations->CanCall()) {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100255 if (!instruction->IsSuspendCheck()) {
256 codegen_->MarkNotLeaf();
257 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100258 safepoints_.Add(instruction);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100259 if (locations->OnlyCallsOnSlowPath()) {
260 // We add a synthesized range at this position to record the live registers
261 // at this position. Ideally, we could just update the safepoints when locations
262 // are updated, but we currently need to know the full stack size before updating
263 // locations (because of parameters and the fact that we don't have a frame pointer).
264 // And knowing the full stack size requires to know the maximum number of live
265 // registers at calls in slow paths.
266 // By adding the following interval in the algorithm, we can compute this
267 // maximum before updating locations.
268 LiveInterval* interval = LiveInterval::MakeSlowPathInterval(allocator_, instruction);
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000269 interval->AddRange(position, position + 1);
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000270 AddSorted(&unhandled_core_intervals_, interval);
271 AddSorted(&unhandled_fp_intervals_, interval);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100272 }
273 }
274
275 if (locations->WillCall()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100276 // Block all registers.
277 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000278 if (!codegen_->IsCoreCalleeSaveRegister(i)) {
279 BlockRegister(Location::RegisterLocation(i),
280 position,
281 position + 1);
282 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100283 }
284 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000285 if (!codegen_->IsFloatingPointCalleeSaveRegister(i)) {
286 BlockRegister(Location::FpuRegisterLocation(i),
287 position,
288 position + 1);
289 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100290 }
291 }
292
293 for (size_t i = 0; i < instruction->InputCount(); ++i) {
294 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100295 if (input.IsRegister() || input.IsFpuRegister()) {
296 BlockRegister(input, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000297 } else if (input.IsPair()) {
298 BlockRegister(input.ToLow(), position, position + 1);
299 BlockRegister(input.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100300 }
301 }
302
Nicolas Geoffray39468442014-09-02 15:17:15 +0100303 LiveInterval* current = instruction->GetLiveInterval();
304 if (current == nullptr) return;
305
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100306 GrowableArray<LiveInterval*>& unhandled = core_register
307 ? unhandled_core_intervals_
308 : unhandled_fp_intervals_;
309
Nicolas Geoffray76905622014-09-25 14:39:26 +0100310 DCHECK(unhandled.IsEmpty() || current->StartsBeforeOrAt(unhandled.Peek()));
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000311
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000312 if (codegen_->NeedsTwoRegisters(current->GetType())) {
313 current->AddHighInterval();
314 }
315
Nicolas Geoffray39468442014-09-02 15:17:15 +0100316 // Some instructions define their output in fixed register/stack slot. We need
317 // to ensure we know these locations before doing register allocation. For a
318 // given register, we create an interval that covers these locations. The register
319 // will be unavailable at these locations when trying to allocate one for an
320 // interval.
321 //
322 // The backwards walking ensures the ranges are ordered on increasing start positions.
323 Location output = locations->Out();
Calin Juravled0d48522014-11-04 16:40:20 +0000324 if (output.IsUnallocated() && output.GetPolicy() == Location::kSameAsFirstInput) {
325 Location first = locations->InAt(0);
326 if (first.IsRegister() || first.IsFpuRegister()) {
327 current->SetFrom(position + 1);
328 current->SetRegister(first.reg());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000329 } else if (first.IsPair()) {
330 current->SetFrom(position + 1);
331 current->SetRegister(first.low());
332 LiveInterval* high = current->GetHighInterval();
333 high->SetRegister(first.high());
334 high->SetFrom(position + 1);
Calin Juravled0d48522014-11-04 16:40:20 +0000335 }
336 } else if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100337 // Shift the interval's start by one to account for the blocked register.
338 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100339 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100340 BlockRegister(output, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000341 } else if (output.IsPair()) {
342 current->SetFrom(position + 1);
343 current->SetRegister(output.low());
344 LiveInterval* high = current->GetHighInterval();
345 high->SetRegister(output.high());
346 high->SetFrom(position + 1);
347 BlockRegister(output.ToLow(), position, position + 1);
348 BlockRegister(output.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100349 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
350 current->SetSpillSlot(output.GetStackIndex());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000351 } else {
352 DCHECK(output.IsUnallocated() || output.IsConstant());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100353 }
354
355 // If needed, add interval to the list of unhandled intervals.
356 if (current->HasSpillSlot() || instruction->IsConstant()) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100357 // Split just before first register use.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100358 size_t first_register_use = current->FirstRegisterUse();
359 if (first_register_use != kNoLifetime) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100360 LiveInterval* split = Split(current, first_register_use - 1);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000361 // Don't add directly to `unhandled`, it needs to be sorted and the start
Nicolas Geoffray39468442014-09-02 15:17:15 +0100362 // of this new interval might be after intervals already in the list.
363 AddSorted(&unhandled, split);
364 } else {
365 // Nothing to do, we won't allocate a register for this value.
366 }
367 } else {
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000368 // Don't add directly to `unhandled`, temp or safepoint intervals
369 // for this instruction may have been added, and those can be
370 // processed first.
371 AddSorted(&unhandled, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100372 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100373}
374
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100375class AllRangesIterator : public ValueObject {
376 public:
377 explicit AllRangesIterator(LiveInterval* interval)
378 : current_interval_(interval),
379 current_range_(interval->GetFirstRange()) {}
380
381 bool Done() const { return current_interval_ == nullptr; }
382 LiveRange* CurrentRange() const { return current_range_; }
383 LiveInterval* CurrentInterval() const { return current_interval_; }
384
385 void Advance() {
386 current_range_ = current_range_->GetNext();
387 if (current_range_ == nullptr) {
388 current_interval_ = current_interval_->GetNextSibling();
389 if (current_interval_ != nullptr) {
390 current_range_ = current_interval_->GetFirstRange();
391 }
392 }
393 }
394
395 private:
396 LiveInterval* current_interval_;
397 LiveRange* current_range_;
398
399 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
400};
401
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100402bool RegisterAllocator::ValidateInternal(bool log_fatal_on_failure) const {
403 // To simplify unit testing, we eagerly create the array of intervals, and
404 // call the helper method.
405 GrowableArray<LiveInterval*> intervals(allocator_, 0);
406 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
407 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
408 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
409 intervals.Add(instruction->GetLiveInterval());
410 }
411 }
412
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100413 if (processing_core_registers_) {
414 for (size_t i = 0, e = physical_core_register_intervals_.Size(); i < e; ++i) {
415 LiveInterval* fixed = physical_core_register_intervals_.Get(i);
416 if (fixed != nullptr) {
417 intervals.Add(fixed);
418 }
419 }
420 } else {
421 for (size_t i = 0, e = physical_fp_register_intervals_.Size(); i < e; ++i) {
422 LiveInterval* fixed = physical_fp_register_intervals_.Get(i);
423 if (fixed != nullptr) {
424 intervals.Add(fixed);
425 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100426 }
427 }
428
Nicolas Geoffray39468442014-09-02 15:17:15 +0100429 for (size_t i = 0, e = temp_intervals_.Size(); i < e; ++i) {
430 LiveInterval* temp = temp_intervals_.Get(i);
431 if (ShouldProcess(processing_core_registers_, temp)) {
432 intervals.Add(temp);
433 }
434 }
435
436 return ValidateIntervals(intervals, spill_slots_.Size(), reserved_out_slots_, *codegen_,
437 allocator_, processing_core_registers_, log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100438}
439
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100440bool RegisterAllocator::ValidateIntervals(const GrowableArray<LiveInterval*>& intervals,
441 size_t number_of_spill_slots,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100442 size_t number_of_out_slots,
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100443 const CodeGenerator& codegen,
444 ArenaAllocator* allocator,
445 bool processing_core_registers,
446 bool log_fatal_on_failure) {
447 size_t number_of_registers = processing_core_registers
448 ? codegen.GetNumberOfCoreRegisters()
449 : codegen.GetNumberOfFloatingPointRegisters();
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100450 GrowableArray<ArenaBitVector*> liveness_of_values(
451 allocator, number_of_registers + number_of_spill_slots);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100452
453 // Allocate a bit vector per register. A live interval that has a register
454 // allocated will populate the associated bit vector based on its live ranges.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100455 for (size_t i = 0; i < number_of_registers + number_of_spill_slots; ++i) {
456 liveness_of_values.Add(new (allocator) ArenaBitVector(allocator, 0, true));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100457 }
458
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100459 for (size_t i = 0, e = intervals.Size(); i < e; ++i) {
460 for (AllRangesIterator it(intervals.Get(i)); !it.Done(); it.Advance()) {
461 LiveInterval* current = it.CurrentInterval();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100462 HInstruction* defined_by = current->GetParent()->GetDefinedBy();
463 if (current->GetParent()->HasSpillSlot()
464 // Parameters have their own stack slot.
465 && !(defined_by != nullptr && defined_by->IsParameterValue())) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100466 BitVector* liveness_of_spill_slot = liveness_of_values.Get(number_of_registers
467 + current->GetParent()->GetSpillSlot() / kVRegSize
468 - number_of_out_slots);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100469 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
470 if (liveness_of_spill_slot->IsBitSet(j)) {
471 if (log_fatal_on_failure) {
472 std::ostringstream message;
473 message << "Spill slot conflict at " << j;
474 LOG(FATAL) << message.str();
475 } else {
476 return false;
477 }
478 } else {
479 liveness_of_spill_slot->SetBit(j);
480 }
481 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100482 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100483
484 if (current->HasRegister()) {
485 BitVector* liveness_of_register = liveness_of_values.Get(current->GetRegister());
486 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
487 if (liveness_of_register->IsBitSet(j)) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100488 if (log_fatal_on_failure) {
489 std::ostringstream message;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100490 message << "Register conflict at " << j << " ";
491 if (defined_by != nullptr) {
492 message << "(" << defined_by->DebugName() << ")";
493 }
494 message << "for ";
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100495 if (processing_core_registers) {
496 codegen.DumpCoreRegister(message, current->GetRegister());
497 } else {
498 codegen.DumpFloatingPointRegister(message, current->GetRegister());
499 }
500 LOG(FATAL) << message.str();
501 } else {
502 return false;
503 }
504 } else {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100505 liveness_of_register->SetBit(j);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100506 }
507 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100508 }
509 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100510 }
511 return true;
512}
513
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100514void RegisterAllocator::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100515 interval->Dump(stream);
516 stream << ": ";
517 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100518 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100519 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100520 } else {
521 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100522 }
523 } else {
524 stream << "spilled";
525 }
526 stream << std::endl;
527}
528
Mingyao Yang296bd602014-10-06 16:47:28 -0700529void RegisterAllocator::DumpAllIntervals(std::ostream& stream) const {
530 stream << "inactive: " << std::endl;
531 for (size_t i = 0; i < inactive_.Size(); i ++) {
532 DumpInterval(stream, inactive_.Get(i));
533 }
534 stream << "active: " << std::endl;
535 for (size_t i = 0; i < active_.Size(); i ++) {
536 DumpInterval(stream, active_.Get(i));
537 }
538 stream << "unhandled: " << std::endl;
539 auto unhandled = (unhandled_ != nullptr) ?
540 unhandled_ : &unhandled_core_intervals_;
541 for (size_t i = 0; i < unhandled->Size(); i ++) {
542 DumpInterval(stream, unhandled->Get(i));
543 }
544 stream << "handled: " << std::endl;
545 for (size_t i = 0; i < handled_.Size(); i ++) {
546 DumpInterval(stream, handled_.Get(i));
547 }
548}
549
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100550// By the book implementation of a linear scan register allocator.
551void RegisterAllocator::LinearScan() {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100552 while (!unhandled_->IsEmpty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100553 // (1) Remove interval with the lowest start position from unhandled.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100554 LiveInterval* current = unhandled_->Pop();
555 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100556 DCHECK(unhandled_->IsEmpty() || unhandled_->Peek()->GetStart() >= current->GetStart());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000557 DCHECK(!current->IsLowInterval() || unhandled_->Peek()->IsHighInterval());
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000558
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100559 size_t position = current->GetStart();
560
Mingyao Yang296bd602014-10-06 16:47:28 -0700561 // Remember the inactive_ size here since the ones moved to inactive_ from
562 // active_ below shouldn't need to be re-checked.
563 size_t inactive_intervals_to_handle = inactive_.Size();
564
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100565 // (2) Remove currently active intervals that are dead at this position.
566 // Move active intervals that have a lifetime hole at this position
567 // to inactive.
568 for (size_t i = 0; i < active_.Size(); ++i) {
569 LiveInterval* interval = active_.Get(i);
570 if (interval->IsDeadAt(position)) {
571 active_.Delete(interval);
572 --i;
573 handled_.Add(interval);
574 } else if (!interval->Covers(position)) {
575 active_.Delete(interval);
576 --i;
577 inactive_.Add(interval);
578 }
579 }
580
581 // (3) Remove currently inactive intervals that are dead at this position.
582 // Move inactive intervals that cover this position to active.
Mingyao Yang296bd602014-10-06 16:47:28 -0700583 for (size_t i = 0; i < inactive_intervals_to_handle; ++i) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100584 LiveInterval* interval = inactive_.Get(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700585 DCHECK(interval->GetStart() < position || interval->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100586 if (interval->IsDeadAt(position)) {
587 inactive_.Delete(interval);
588 --i;
Mingyao Yang296bd602014-10-06 16:47:28 -0700589 --inactive_intervals_to_handle;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100590 handled_.Add(interval);
591 } else if (interval->Covers(position)) {
592 inactive_.Delete(interval);
593 --i;
Mingyao Yang296bd602014-10-06 16:47:28 -0700594 --inactive_intervals_to_handle;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100595 active_.Add(interval);
596 }
597 }
598
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000599 if (current->IsSlowPathSafepoint()) {
600 // Synthesized interval to record the maximum number of live registers
601 // at safepoints. No need to allocate a register for it.
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500602 if (processing_core_registers_) {
603 maximum_number_of_live_core_registers_ =
604 std::max(maximum_number_of_live_core_registers_, active_.Size());
605 } else {
606 maximum_number_of_live_fp_registers_ =
607 std::max(maximum_number_of_live_fp_registers_, active_.Size());
608 }
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000609 DCHECK(unhandled_->IsEmpty() || unhandled_->Peek()->GetStart() > current->GetStart());
610 continue;
611 }
612
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000613 if (current->IsHighInterval() && !current->GetLowInterval()->HasRegister()) {
614 DCHECK(!current->HasRegister());
615 // Allocating the low part was unsucessful. The splitted interval for the high part
616 // will be handled next (it is in the `unhandled_` list).
617 continue;
618 }
619
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100620 // (4) Try to find an available register.
621 bool success = TryAllocateFreeReg(current);
622
623 // (5) If no register could be found, we need to spill.
624 if (!success) {
625 success = AllocateBlockedReg(current);
626 }
627
628 // (6) If the interval had a register allocated, add it to the list of active
629 // intervals.
630 if (success) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000631 codegen_->AddAllocatedRegister(processing_core_registers_
632 ? Location::RegisterLocation(current->GetRegister())
633 : Location::FpuRegisterLocation(current->GetRegister()));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100634 active_.Add(current);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000635 if (current->HasHighInterval() && !current->GetHighInterval()->HasRegister()) {
636 current->GetHighInterval()->SetRegister(GetHighForLowRegister(current->GetRegister()));
637 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100638 }
639 }
640}
641
642// Find a free register. If multiple are found, pick the register that
643// is free the longest.
644bool RegisterAllocator::TryAllocateFreeReg(LiveInterval* current) {
645 size_t* free_until = registers_array_;
646
647 // First set all registers to be free.
648 for (size_t i = 0; i < number_of_registers_; ++i) {
649 free_until[i] = kMaxLifetimePosition;
650 }
651
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100652 // For each active interval, set its register to not free.
653 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
654 LiveInterval* interval = active_.Get(i);
655 DCHECK(interval->HasRegister());
656 free_until[interval->GetRegister()] = 0;
657 }
658
Mingyao Yang296bd602014-10-06 16:47:28 -0700659 // For each inactive interval, set its register to be free until
660 // the next intersection with `current`.
661 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
662 LiveInterval* inactive = inactive_.Get(i);
663 // Temp/Slow-path-safepoint interval has no holes.
664 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
665 if (!current->IsSplit() && !inactive->IsFixed()) {
666 // Neither current nor inactive are fixed.
667 // Thanks to SSA, a non-split interval starting in a hole of an
668 // inactive interval should never intersect with that inactive interval.
669 // Only if it's not fixed though, because fixed intervals don't come from SSA.
670 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
671 continue;
672 }
673
674 DCHECK(inactive->HasRegister());
675 if (free_until[inactive->GetRegister()] == 0) {
676 // Already used by some active interval. No need to intersect.
677 continue;
678 }
679 size_t next_intersection = inactive->FirstIntersectionWith(current);
680 if (next_intersection != kNoLifetime) {
681 free_until[inactive->GetRegister()] =
682 std::min(free_until[inactive->GetRegister()], next_intersection);
683 }
684 }
685
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000686 int reg = kNoRegister;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100687 if (current->HasRegister()) {
688 // Some instructions have a fixed register output.
689 reg = current->GetRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000690 if (free_until[reg] == 0) {
691 DCHECK(current->IsHighInterval());
692 // AllocateBlockedReg will spill the holder of the register.
693 return false;
694 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100695 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000696 DCHECK(!current->IsHighInterval());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100697 int hint = current->FindFirstRegisterHint(free_until);
698 if (hint != kNoRegister) {
699 DCHECK(!IsBlocked(hint));
700 reg = hint;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000701 } else if (current->IsLowInterval()) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000702 reg = FindAvailableRegisterPair(free_until, current->GetStart());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100703 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000704 reg = FindAvailableRegister(free_until);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100705 }
706 }
707
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000708 DCHECK_NE(reg, kNoRegister);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100709 // If we could not find a register, we need to spill.
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000710 if (free_until[reg] == 0) {
711 return false;
712 }
713
714 if (current->IsLowInterval() && free_until[GetHighForLowRegister(reg)] == 0) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100715 return false;
716 }
717
718 current->SetRegister(reg);
719 if (!current->IsDeadAt(free_until[reg])) {
720 // If the register is only available for a subset of live ranges
721 // covered by `current`, split `current` at the position where
722 // the register is not available anymore.
723 LiveInterval* split = Split(current, free_until[reg]);
724 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100725 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100726 }
727 return true;
728}
729
730bool RegisterAllocator::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100731 return processing_core_registers_
732 ? blocked_core_registers_[reg]
733 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100734}
735
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000736int RegisterAllocator::FindAvailableRegisterPair(size_t* next_use, size_t starting_at) const {
737 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000738 // Pick the register pair that is used the last.
739 for (size_t i = 0; i < number_of_registers_; ++i) {
740 if (IsBlocked(i)) continue;
741 if (!IsLowRegister(i)) continue;
742 int high_register = GetHighForLowRegister(i);
743 if (IsBlocked(high_register)) continue;
744 int existing_high_register = GetHighForLowRegister(reg);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000745 if ((reg == kNoRegister) || (next_use[i] >= next_use[reg]
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000746 && next_use[high_register] >= next_use[existing_high_register])) {
747 reg = i;
748 if (next_use[i] == kMaxLifetimePosition
749 && next_use[high_register] == kMaxLifetimePosition) {
750 break;
751 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000752 } else if (next_use[reg] <= starting_at || next_use[existing_high_register] <= starting_at) {
753 // If one of the current register is known to be unavailable, just unconditionally
754 // try a new one.
755 reg = i;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000756 }
757 }
758 return reg;
759}
760
761int RegisterAllocator::FindAvailableRegister(size_t* next_use) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000762 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000763 // Pick the register that is used the last.
764 for (size_t i = 0; i < number_of_registers_; ++i) {
765 if (IsBlocked(i)) continue;
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000766 if (reg == kNoRegister || next_use[i] > next_use[reg]) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000767 reg = i;
768 if (next_use[i] == kMaxLifetimePosition) break;
769 }
770 }
771 return reg;
772}
773
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000774bool RegisterAllocator::TrySplitNonPairIntervalAt(size_t position,
775 size_t first_register_use,
776 size_t* next_use) {
777 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
778 LiveInterval* active = active_.Get(i);
779 DCHECK(active->HasRegister());
780 // Split the first interval found.
781 if (first_register_use <= next_use[active->GetRegister()]
782 && !active->IsLowInterval()
783 && !active->IsHighInterval()) {
784 LiveInterval* split = Split(active, position);
785 active_.DeleteAt(i);
786 if (split != active) {
787 handled_.Add(active);
788 }
789 AddSorted(unhandled_, split);
790 return true;
791 }
792 }
793 return false;
794}
795
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100796// Find the register that is used the last, and spill the interval
797// that holds it. If the first use of `current` is after that register
798// we spill `current` instead.
799bool RegisterAllocator::AllocateBlockedReg(LiveInterval* current) {
800 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffray412f10c2014-06-19 10:00:34 +0100801 if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100802 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100803 return false;
804 }
805
806 // First set all registers as not being used.
807 size_t* next_use = registers_array_;
808 for (size_t i = 0; i < number_of_registers_; ++i) {
809 next_use[i] = kMaxLifetimePosition;
810 }
811
812 // For each active interval, find the next use of its register after the
813 // start of current.
814 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
815 LiveInterval* active = active_.Get(i);
816 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100817 if (active->IsFixed()) {
818 next_use[active->GetRegister()] = current->GetStart();
819 } else {
820 size_t use = active->FirstRegisterUseAfter(current->GetStart());
821 if (use != kNoLifetime) {
822 next_use[active->GetRegister()] = use;
823 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100824 }
825 }
826
827 // For each inactive interval, find the next use of its register after the
828 // start of current.
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100829 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
830 LiveInterval* inactive = inactive_.Get(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700831 // Temp/Slow-path-safepoint interval has no holes.
832 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
833 if (!current->IsSplit() && !inactive->IsFixed()) {
834 // Neither current nor inactive are fixed.
835 // Thanks to SSA, a non-split interval starting in a hole of an
836 // inactive interval should never intersect with that inactive interval.
837 // Only if it's not fixed though, because fixed intervals don't come from SSA.
838 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
839 continue;
840 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100841 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100842 size_t next_intersection = inactive->FirstIntersectionWith(current);
843 if (next_intersection != kNoLifetime) {
844 if (inactive->IsFixed()) {
845 next_use[inactive->GetRegister()] =
846 std::min(next_intersection, next_use[inactive->GetRegister()]);
847 } else {
848 size_t use = inactive->FirstRegisterUseAfter(current->GetStart());
849 if (use != kNoLifetime) {
850 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
851 }
852 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100853 }
854 }
855
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000856 int reg = kNoRegister;
857 bool should_spill = false;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000858 if (current->HasRegister()) {
859 DCHECK(current->IsHighInterval());
860 reg = current->GetRegister();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000861 // When allocating the low part, we made sure the high register was available.
862 DCHECK_LT(first_register_use, next_use[reg]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000863 } else if (current->IsLowInterval()) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000864 reg = FindAvailableRegisterPair(next_use, current->GetStart());
865 // We should spill if both registers are not available.
866 should_spill = (first_register_use >= next_use[reg])
867 || (first_register_use >= next_use[GetHighForLowRegister(reg)]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000868 } else {
869 DCHECK(!current->IsHighInterval());
870 reg = FindAvailableRegister(next_use);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000871 should_spill = (first_register_use >= next_use[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100872 }
873
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000874 DCHECK_NE(reg, kNoRegister);
875 if (should_spill) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000876 DCHECK(!current->IsHighInterval());
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000877 bool is_allocation_at_use_site = (current->GetStart() == (first_register_use - 1));
878 if (current->IsLowInterval()
879 && is_allocation_at_use_site
880 && TrySplitNonPairIntervalAt(current->GetStart(), first_register_use, next_use)) {
881 // If we're allocating a register for `current` because the instruction at
882 // that position requires it, but we think we should spill, then there are
883 // non-pair intervals blocking the allocation. We split the first
884 // interval found, and put ourselves first in the `unhandled_` list.
885 LiveInterval* existing = unhandled_->Peek();
886 DCHECK(existing->IsHighInterval());
887 DCHECK_EQ(existing->GetLowInterval(), current);
888 unhandled_->Add(current);
889 } else {
890 // If the first use of that instruction is after the last use of the found
891 // register, we split this interval just before its first register use.
892 AllocateSpillSlotFor(current);
893 LiveInterval* split = Split(current, first_register_use - 1);
894 DCHECK_NE(current, split) << "There is not enough registers available for "
895 << split->GetParent()->GetDefinedBy()->DebugName() << " "
896 << split->GetParent()->GetDefinedBy()->GetId()
897 << " at " << first_register_use - 1;
898 AddSorted(unhandled_, split);
899 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100900 return false;
901 } else {
902 // Use this register and spill the active and inactives interval that
903 // have that register.
904 current->SetRegister(reg);
905
906 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
907 LiveInterval* active = active_.Get(i);
908 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100909 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100910 LiveInterval* split = Split(active, current->GetStart());
911 active_.DeleteAt(i);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +0000912 if (split != active) {
913 handled_.Add(active);
914 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100915 AddSorted(unhandled_, split);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000916
917 if (active->IsLowInterval() || active->IsHighInterval()) {
918 LiveInterval* other_half = active->IsLowInterval()
919 ? active->GetHighInterval()
920 : active->GetLowInterval();
921 // We also need to remove the other half from the list of actives.
922 bool found = false;
923 for (size_t j = 0; j < active_.Size(); ++j) {
924 if (active_.Get(j) == other_half) {
925 found = true;
926 active_.DeleteAt(j);
927 handled_.Add(other_half);
928 break;
929 }
930 }
931 DCHECK(found);
932 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100933 break;
934 }
935 }
936
Mingyao Yang296bd602014-10-06 16:47:28 -0700937 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100938 LiveInterval* inactive = inactive_.Get(i);
939 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700940 if (!current->IsSplit() && !inactive->IsFixed()) {
941 // Neither current nor inactive are fixed.
942 // Thanks to SSA, a non-split interval starting in a hole of an
943 // inactive interval should never intersect with that inactive interval.
944 // Only if it's not fixed though, because fixed intervals don't come from SSA.
945 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
946 continue;
947 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100948 size_t next_intersection = inactive->FirstIntersectionWith(current);
949 if (next_intersection != kNoLifetime) {
950 if (inactive->IsFixed()) {
951 LiveInterval* split = Split(current, next_intersection);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +0000952 DCHECK_NE(split, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100953 AddSorted(unhandled_, split);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100954 } else {
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +0000955 // Split at the start of `current`, which will lead to splitting
956 // at the end of the lifetime hole of `inactive`.
957 LiveInterval* split = Split(inactive, current->GetStart());
958 // If it's inactive, it must start before the current interval.
959 DCHECK_NE(split, inactive);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100960 inactive_.DeleteAt(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700961 --i;
962 --e;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100963 handled_.Add(inactive);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100964 AddSorted(unhandled_, split);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000965
966 if (inactive->IsLowInterval() || inactive->IsHighInterval()) {
967 LiveInterval* other_half = inactive->IsLowInterval()
968 ? inactive->GetHighInterval()
969 : inactive->GetLowInterval();
970
971 // We also need to remove the other half from the list of inactives.
972 bool found = false;
973 for (size_t j = 0; j < inactive_.Size(); ++j) {
974 if (inactive_.Get(j) == other_half) {
975 found = true;
976 inactive_.DeleteAt(j);
977 --e;
978 handled_.Add(other_half);
979 break;
980 }
981 }
982 DCHECK(found);
983 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100984 }
985 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100986 }
987 }
988
989 return true;
990 }
991}
992
Nicolas Geoffray39468442014-09-02 15:17:15 +0100993void RegisterAllocator::AddSorted(GrowableArray<LiveInterval*>* array, LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100994 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100995 size_t insert_at = 0;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100996 for (size_t i = array->Size(); i > 0; --i) {
997 LiveInterval* current = array->Get(i - 1);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000998 // High intervals must be processed right after their low equivalent.
999 if (current->StartsAfter(interval) && !current->IsHighInterval()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001000 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001001 break;
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001002 } else if ((current->GetStart() == interval->GetStart()) && current->IsSlowPathSafepoint()) {
1003 // Ensure the slow path interval is the last to be processed at its location: we want the
1004 // interval to know all live registers at this location.
1005 DCHECK(i == 1 || array->Get(i - 2)->StartsAfter(current));
1006 insert_at = i;
1007 break;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001008 }
1009 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001010
Nicolas Geoffray39468442014-09-02 15:17:15 +01001011 array->InsertAt(insert_at, interval);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001012 // Insert the high interval before the low, to ensure the low is processed before.
1013 if (interval->HasHighInterval()) {
1014 array->InsertAt(insert_at, interval->GetHighInterval());
1015 } else if (interval->HasLowInterval()) {
1016 array->InsertAt(insert_at + 1, interval->GetLowInterval());
1017 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001018}
1019
1020LiveInterval* RegisterAllocator::Split(LiveInterval* interval, size_t position) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001021 DCHECK_GE(position, interval->GetStart());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001022 DCHECK(!interval->IsDeadAt(position));
1023 if (position == interval->GetStart()) {
1024 // Spill slot will be allocated when handling `interval` again.
1025 interval->ClearRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001026 if (interval->HasHighInterval()) {
1027 interval->GetHighInterval()->ClearRegister();
1028 } else if (interval->HasLowInterval()) {
1029 interval->GetLowInterval()->ClearRegister();
1030 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001031 return interval;
1032 } else {
1033 LiveInterval* new_interval = interval->SplitAt(position);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001034 if (interval->HasHighInterval()) {
1035 LiveInterval* high = interval->GetHighInterval()->SplitAt(position);
1036 new_interval->SetHighInterval(high);
1037 high->SetLowInterval(new_interval);
1038 } else if (interval->HasLowInterval()) {
1039 LiveInterval* low = interval->GetLowInterval()->SplitAt(position);
1040 new_interval->SetLowInterval(low);
1041 low->SetHighInterval(new_interval);
1042 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001043 return new_interval;
1044 }
1045}
1046
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001047void RegisterAllocator::AllocateSpillSlotFor(LiveInterval* interval) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001048 if (interval->IsHighInterval()) {
1049 // The low interval will contain the spill slot.
1050 return;
1051 }
1052
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001053 LiveInterval* parent = interval->GetParent();
1054
1055 // An instruction gets a spill slot for its entire lifetime. If the parent
1056 // of this interval already has a spill slot, there is nothing to do.
1057 if (parent->HasSpillSlot()) {
1058 return;
1059 }
1060
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001061 HInstruction* defined_by = parent->GetDefinedBy();
1062 if (defined_by->IsParameterValue()) {
1063 // Parameters have their own stack slot.
1064 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
1065 return;
1066 }
1067
Nicolas Geoffray96f89a22014-07-11 10:57:49 +01001068 if (defined_by->IsConstant()) {
1069 // Constants don't need a spill slot.
1070 return;
1071 }
1072
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001073 LiveInterval* last_sibling = interval;
1074 while (last_sibling->GetNextSibling() != nullptr) {
1075 last_sibling = last_sibling->GetNextSibling();
1076 }
1077 size_t end = last_sibling->GetEnd();
1078
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001079 // Find an available spill slot.
1080 size_t slot = 0;
1081 for (size_t e = spill_slots_.Size(); slot < e; ++slot) {
1082 // We check if it is less rather than less or equal because the parallel move
1083 // resolver does not work when a single spill slot needs to be exchanged with
1084 // a double spill slot. The strict comparison avoids needing to exchange these
1085 // locations at the same lifetime position.
1086 if (spill_slots_.Get(slot) < parent->GetStart()
1087 && (slot == (e - 1) || spill_slots_.Get(slot + 1) < parent->GetStart())) {
1088 break;
1089 }
1090 }
1091
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001092 if (parent->NeedsTwoSpillSlots()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001093 if (slot == spill_slots_.Size()) {
1094 // We need a new spill slot.
1095 spill_slots_.Add(end);
1096 spill_slots_.Add(end);
1097 } else if (slot == spill_slots_.Size() - 1) {
1098 spill_slots_.Put(slot, end);
1099 spill_slots_.Add(end);
1100 } else {
1101 spill_slots_.Put(slot, end);
1102 spill_slots_.Put(slot + 1, end);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001103 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001104 } else {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001105 if (slot == spill_slots_.Size()) {
1106 // We need a new spill slot.
1107 spill_slots_.Add(end);
1108 } else {
1109 spill_slots_.Put(slot, end);
1110 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001111 }
1112
Nicolas Geoffray39468442014-09-02 15:17:15 +01001113 parent->SetSpillSlot((slot + reserved_out_slots_) * kVRegSize);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001114}
1115
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001116static bool IsValidDestination(Location destination) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001117 return destination.IsRegister()
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001118 || destination.IsRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001119 || destination.IsFpuRegister()
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001120 || destination.IsFpuRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001121 || destination.IsStackSlot()
1122 || destination.IsDoubleStackSlot();
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001123}
1124
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001125void RegisterAllocator::AddInputMoveFor(HInstruction* user,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001126 Location source,
1127 Location destination) const {
1128 if (source.Equals(destination)) return;
1129
Roland Levillain476df552014-10-09 17:51:36 +01001130 DCHECK(!user->IsPhi());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001131
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001132 HInstruction* previous = user->GetPrevious();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001133 HParallelMove* move = nullptr;
1134 if (previous == nullptr
Roland Levillain476df552014-10-09 17:51:36 +01001135 || !previous->IsParallelMove()
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001136 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001137 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001138 move->SetLifetimePosition(user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001139 user->GetBlock()->InsertInstructionBefore(move, user);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001140 } else {
1141 move = previous->AsParallelMove();
1142 }
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001143 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
Nicolas Geoffray42d1f5f2015-01-16 09:14:18 +00001144 move->AddMove(source, destination, nullptr);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001145}
1146
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001147static bool IsInstructionStart(size_t position) {
1148 return (position & 1) == 0;
1149}
1150
1151static bool IsInstructionEnd(size_t position) {
1152 return (position & 1) == 1;
1153}
1154
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001155void RegisterAllocator::InsertParallelMoveAt(size_t position,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001156 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001157 Location source,
1158 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001159 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001160 if (source.Equals(destination)) return;
1161
1162 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001163 HParallelMove* move;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001164 if (at == nullptr) {
1165 if (IsInstructionStart(position)) {
1166 // Block boundary, don't do anything the connection of split siblings will handle it.
1167 return;
1168 } else {
1169 // Move must happen before the first instruction of the block.
1170 at = liveness_.GetInstructionFromPosition((position + 1) / 2);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001171 // Note that parallel moves may have already been inserted, so we explicitly
1172 // ask for the first instruction of the block: `GetInstructionFromPosition` does
1173 // not contain the moves.
1174 at = at->GetBlock()->GetFirstInstruction();
1175 if (at->GetLifetimePosition() != position) {
1176 DCHECK_GT(at->GetLifetimePosition(), position);
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001177 move = new (allocator_) HParallelMove(allocator_);
1178 move->SetLifetimePosition(position);
1179 at->GetBlock()->InsertInstructionBefore(move, at);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001180 } else {
1181 DCHECK(at->IsParallelMove());
1182 move = at->AsParallelMove();
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001183 }
1184 }
1185 } else if (IsInstructionEnd(position)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001186 // Move must happen after the instruction.
1187 DCHECK(!at->IsControlFlow());
1188 move = at->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001189 // This is a parallel move for connecting siblings in a same block. We need to
1190 // differentiate it with moves for connecting blocks, and input moves.
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001191 if (move == nullptr || move->GetLifetimePosition() > position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001192 move = new (allocator_) HParallelMove(allocator_);
1193 move->SetLifetimePosition(position);
1194 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
1195 }
1196 } else {
1197 // Move must happen before the instruction.
1198 HInstruction* previous = at->GetPrevious();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001199 if (previous == nullptr
1200 || !previous->IsParallelMove()
1201 || previous->GetLifetimePosition() != position) {
1202 // If the previous is a parallel move, then its position must be lower
1203 // than the given `position`: it was added just after the non-parallel
1204 // move instruction that precedes `instruction`.
1205 DCHECK(previous == nullptr
1206 || !previous->IsParallelMove()
1207 || previous->GetLifetimePosition() < position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001208 move = new (allocator_) HParallelMove(allocator_);
1209 move->SetLifetimePosition(position);
1210 at->GetBlock()->InsertInstructionBefore(move, at);
1211 } else {
1212 move = previous->AsParallelMove();
1213 }
1214 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001215 DCHECK_EQ(move->GetLifetimePosition(), position);
Nicolas Geoffray42d1f5f2015-01-16 09:14:18 +00001216 move->AddMove(source, destination, instruction);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001217}
1218
1219void RegisterAllocator::InsertParallelMoveAtExitOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001220 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001221 Location source,
1222 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001223 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001224 if (source.Equals(destination)) return;
1225
1226 DCHECK_EQ(block->GetSuccessors().Size(), 1u);
1227 HInstruction* last = block->GetLastInstruction();
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001228 // We insert moves at exit for phi predecessors and connecting blocks.
1229 // A block ending with an if cannot branch to a block with phis because
1230 // we do not allow critical edges. It can also not connect
1231 // a split interval between two blocks: the move has to happen in the successor.
1232 DCHECK(!last->IsIf());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001233 HInstruction* previous = last->GetPrevious();
1234 HParallelMove* move;
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001235 // This is a parallel move for connecting blocks. We need to differentiate
1236 // it with moves for connecting siblings in a same block, and output moves.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001237 size_t position = last->GetLifetimePosition();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001238 if (previous == nullptr || !previous->IsParallelMove()
Nicolas Geoffray59768572014-12-01 09:50:04 +00001239 || previous->AsParallelMove()->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001240 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001241 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001242 block->InsertInstructionBefore(move, last);
1243 } else {
1244 move = previous->AsParallelMove();
1245 }
Nicolas Geoffray42d1f5f2015-01-16 09:14:18 +00001246 move->AddMove(source, destination, instruction);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001247}
1248
1249void RegisterAllocator::InsertParallelMoveAtEntryOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001250 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001251 Location source,
1252 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001253 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001254 if (source.Equals(destination)) return;
1255
1256 HInstruction* first = block->GetFirstInstruction();
1257 HParallelMove* move = first->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001258 // This is a parallel move for connecting blocks. We need to differentiate
1259 // it with moves for connecting siblings in a same block, and input moves.
1260 if (move == nullptr || move->GetLifetimePosition() != block->GetLifetimeStart()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001261 move = new (allocator_) HParallelMove(allocator_);
1262 move->SetLifetimePosition(block->GetLifetimeStart());
1263 block->InsertInstructionBefore(move, first);
1264 }
Nicolas Geoffray42d1f5f2015-01-16 09:14:18 +00001265 move->AddMove(source, destination, instruction);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001266}
1267
1268void RegisterAllocator::InsertMoveAfter(HInstruction* instruction,
1269 Location source,
1270 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001271 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001272 if (source.Equals(destination)) return;
1273
Roland Levillain476df552014-10-09 17:51:36 +01001274 if (instruction->IsPhi()) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001275 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001276 return;
1277 }
1278
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001279 size_t position = instruction->GetLifetimePosition() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001280 HParallelMove* move = instruction->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001281 // This is a parallel move for moving the output of an instruction. We need
1282 // to differentiate with input moves, moves for connecting siblings in a
1283 // and moves for connecting blocks.
1284 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001285 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001286 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001287 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
1288 }
Nicolas Geoffray42d1f5f2015-01-16 09:14:18 +00001289 move->AddMove(source, destination, instruction);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001290}
1291
1292void RegisterAllocator::ConnectSiblings(LiveInterval* interval) {
1293 LiveInterval* current = interval;
1294 if (current->HasSpillSlot() && current->HasRegister()) {
1295 // We spill eagerly, so move must be at definition.
1296 InsertMoveAfter(interval->GetDefinedBy(),
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001297 interval->ToLocation(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001298 interval->NeedsTwoSpillSlots()
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001299 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
1300 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001301 }
1302 UsePosition* use = current->GetFirstUse();
1303
1304 // Walk over all siblings, updating locations of use positions, and
1305 // connecting them when they are adjacent.
1306 do {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001307 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001308
1309 // Walk over all uses covered by this interval, and update the location
1310 // information.
1311 while (use != nullptr && use->GetPosition() <= current->GetEnd()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001312 LocationSummary* locations = use->GetUser()->GetLocations();
1313 if (use->GetIsEnvironment()) {
1314 locations->SetEnvironmentAt(use->GetInputIndex(), source);
1315 } else {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001316 Location expected_location = locations->InAt(use->GetInputIndex());
Andreas Gampe71fb52f2014-12-29 17:43:08 -08001317 // The expected (actual) location may be invalid in case the input is unused. Currently
1318 // this only happens for intrinsics.
1319 if (expected_location.IsValid()) {
1320 if (expected_location.IsUnallocated()) {
1321 locations->SetInAt(use->GetInputIndex(), source);
1322 } else if (!expected_location.IsConstant()) {
1323 AddInputMoveFor(use->GetUser(), source, expected_location);
1324 }
1325 } else {
1326 DCHECK(use->GetUser()->IsInvoke());
1327 DCHECK(use->GetUser()->AsInvoke()->GetIntrinsic() != Intrinsics::kNone);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001328 }
1329 }
1330 use = use->GetNext();
1331 }
1332
1333 // If the next interval starts just after this one, and has a register,
1334 // insert a move.
1335 LiveInterval* next_sibling = current->GetNextSibling();
1336 if (next_sibling != nullptr
1337 && next_sibling->HasRegister()
1338 && current->GetEnd() == next_sibling->GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001339 Location destination = next_sibling->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001340 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001341 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001342
1343 // At each safepoint, we record stack and register information.
1344 for (size_t i = 0, e = safepoints_.Size(); i < e; ++i) {
1345 HInstruction* safepoint = safepoints_.Get(i);
1346 size_t position = safepoint->GetLifetimePosition();
1347 LocationSummary* locations = safepoint->GetLocations();
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +00001348 if (!current->Covers(position)) {
1349 continue;
1350 }
1351 if (interval->GetStart() == position) {
1352 // The safepoint is for this instruction, so the location of the instruction
1353 // does not need to be saved.
1354 continue;
1355 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001356
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001357 if ((current->GetType() == Primitive::kPrimNot) && current->GetParent()->HasSpillSlot()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001358 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
1359 }
1360
1361 switch (source.GetKind()) {
1362 case Location::kRegister: {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001363 locations->AddLiveRegister(source);
Nicolas Geoffray98893962015-01-21 12:32:32 +00001364 if (kIsDebugBuild && locations->OnlyCallsOnSlowPath()) {
1365 DCHECK_LE(locations->GetNumberOfLiveRegisters(),
1366 maximum_number_of_live_core_registers_ +
1367 maximum_number_of_live_fp_registers_);
1368 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001369 if (current->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001370 locations->SetRegisterBit(source.reg());
Nicolas Geoffray39468442014-09-02 15:17:15 +01001371 }
1372 break;
1373 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001374 case Location::kFpuRegister: {
1375 locations->AddLiveRegister(source);
1376 break;
1377 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001378
1379 case Location::kRegisterPair:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001380 case Location::kFpuRegisterPair: {
1381 locations->AddLiveRegister(source.ToLow());
1382 locations->AddLiveRegister(source.ToHigh());
1383 break;
1384 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001385 case Location::kStackSlot: // Fall-through
1386 case Location::kDoubleStackSlot: // Fall-through
1387 case Location::kConstant: {
1388 // Nothing to do.
1389 break;
1390 }
1391 default: {
1392 LOG(FATAL) << "Unexpected location for object";
1393 }
1394 }
1395 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001396 current = next_sibling;
1397 } while (current != nullptr);
1398 DCHECK(use == nullptr);
1399}
1400
1401void RegisterAllocator::ConnectSplitSiblings(LiveInterval* interval,
1402 HBasicBlock* from,
1403 HBasicBlock* to) const {
1404 if (interval->GetNextSibling() == nullptr) {
1405 // Nothing to connect. The whole range was allocated to the same location.
1406 return;
1407 }
1408
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001409 // Intervals end at the lifetime end of a block. The decrement by one
1410 // ensures the `Cover` call will return true.
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001411 size_t from_position = from->GetLifetimeEnd() - 1;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001412 size_t to_position = to->GetLifetimeStart();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001413
1414 LiveInterval* destination = nullptr;
1415 LiveInterval* source = nullptr;
1416
1417 LiveInterval* current = interval;
1418
1419 // Check the intervals that cover `from` and `to`.
1420 while ((current != nullptr) && (source == nullptr || destination == nullptr)) {
1421 if (current->Covers(from_position)) {
1422 DCHECK(source == nullptr);
1423 source = current;
1424 }
1425 if (current->Covers(to_position)) {
1426 DCHECK(destination == nullptr);
1427 destination = current;
1428 }
1429
1430 current = current->GetNextSibling();
1431 }
1432
1433 if (destination == source) {
1434 // Interval was not split.
1435 return;
1436 }
1437
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +01001438 DCHECK(destination != nullptr && source != nullptr);
1439
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001440 if (!destination->HasRegister()) {
1441 // Values are eagerly spilled. Spill slot already contains appropriate value.
1442 return;
1443 }
1444
1445 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
1446 // we need to put the moves at the entry of `to`.
1447 if (from->GetSuccessors().Size() == 1) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001448 InsertParallelMoveAtExitOf(from,
1449 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001450 source->ToLocation(),
1451 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001452 } else {
1453 DCHECK_EQ(to->GetPredecessors().Size(), 1u);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001454 InsertParallelMoveAtEntryOf(to,
1455 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001456 source->ToLocation(),
1457 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001458 }
1459}
1460
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001461void RegisterAllocator::Resolve() {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001462 codegen_->ComputeFrameSize(
Mark Mendellf85a9ca2015-01-13 09:20:58 -05001463 spill_slots_.Size(), maximum_number_of_live_core_registers_,
1464 maximum_number_of_live_fp_registers_, reserved_out_slots_);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001465
1466 // Adjust the Out Location of instructions.
1467 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
1468 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1469 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1470 LiveInterval* current = instruction->GetLiveInterval();
1471 LocationSummary* locations = instruction->GetLocations();
1472 Location location = locations->Out();
Roland Levillain476df552014-10-09 17:51:36 +01001473 if (instruction->IsParameterValue()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001474 // Now that we know the frame size, adjust the parameter's location.
1475 if (location.IsStackSlot()) {
1476 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1477 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001478 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001479 } else if (location.IsDoubleStackSlot()) {
1480 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1481 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001482 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001483 } else if (current->HasSpillSlot()) {
1484 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
1485 }
1486 }
1487
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001488 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001489
1490 if (location.IsUnallocated()) {
1491 if (location.GetPolicy() == Location::kSameAsFirstInput) {
Calin Juravled0d48522014-11-04 16:40:20 +00001492 if (locations->InAt(0).IsUnallocated()) {
1493 locations->SetInAt(0, source);
1494 } else {
1495 DCHECK(locations->InAt(0).Equals(source));
1496 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001497 }
1498 locations->SetOut(source);
1499 } else {
1500 DCHECK(source.Equals(location));
1501 }
1502 }
1503
1504 // Connect siblings.
1505 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1506 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1507 ConnectSiblings(instruction->GetLiveInterval());
1508 }
1509
1510 // Resolve non-linear control flow across branches. Order does not matter.
1511 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
1512 HBasicBlock* block = it.Current();
1513 BitVector* live = liveness_.GetLiveInSet(*block);
1514 for (uint32_t idx : live->Indexes()) {
1515 HInstruction* current = liveness_.GetInstructionFromSsaIndex(idx);
1516 LiveInterval* interval = current->GetLiveInterval();
1517 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
1518 ConnectSplitSiblings(interval, block->GetPredecessors().Get(i), block);
1519 }
1520 }
1521 }
1522
1523 // Resolve phi inputs. Order does not matter.
1524 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
1525 HBasicBlock* current = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001526 for (HInstructionIterator inst_it(current->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
1527 HInstruction* phi = inst_it.Current();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001528 for (size_t i = 0, e = current->GetPredecessors().Size(); i < e; ++i) {
1529 HBasicBlock* predecessor = current->GetPredecessors().Get(i);
1530 DCHECK_EQ(predecessor->GetSuccessors().Size(), 1u);
1531 HInstruction* input = phi->InputAt(i);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001532 Location source = input->GetLiveInterval()->GetLocationAt(
1533 predecessor->GetLifetimeEnd() - 1);
1534 Location destination = phi->GetLiveInterval()->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001535 InsertParallelMoveAtExitOf(predecessor, nullptr, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001536 }
1537 }
1538 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001539
1540 // Assign temp locations.
1541 HInstruction* current = nullptr;
1542 size_t temp_index = 0;
1543 for (size_t i = 0; i < temp_intervals_.Size(); ++i) {
1544 LiveInterval* temp = temp_intervals_.Get(i);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001545 if (temp->IsHighInterval()) {
1546 // High intervals can be skipped, they are already handled by the low interval.
1547 continue;
1548 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001549 HInstruction* at = liveness_.GetTempUser(temp);
1550 if (at != current) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001551 temp_index = 0;
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001552 current = at;
Nicolas Geoffray39468442014-09-02 15:17:15 +01001553 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001554 LocationSummary* locations = at->GetLocations();
Roland Levillain5368c212014-11-27 15:03:41 +00001555 switch (temp->GetType()) {
1556 case Primitive::kPrimInt:
1557 locations->SetTempAt(
1558 temp_index++, Location::RegisterLocation(temp->GetRegister()));
1559 break;
1560
1561 case Primitive::kPrimDouble:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001562 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
1563 Location location = Location::FpuRegisterPairLocation(
1564 temp->GetRegister(), temp->GetHighInterval()->GetRegister());
1565 locations->SetTempAt(temp_index++, location);
1566 } else {
1567 locations->SetTempAt(
1568 temp_index++, Location::FpuRegisterLocation(temp->GetRegister()));
1569 }
Roland Levillain5368c212014-11-27 15:03:41 +00001570 break;
1571
1572 default:
1573 LOG(FATAL) << "Unexpected type for temporary location "
1574 << temp->GetType();
1575 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001576 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001577}
1578
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001579} // namespace art