blob: b481f644899291c3ca46340c9b375dd4ecea4895 [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
Matthew Gharritye9288852016-07-14 14:08:16 -070017#include "register_allocator_linear_scan.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010018
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000019#include <iostream>
Ian Rogersc7dd2952014-10-21 23:31:19 -070020#include <sstream>
21
Ian Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070023#include "base/enums.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010024#include "code_generator.h"
Aart Bik96202302016-10-04 17:33:56 -070025#include "linear_order.h"
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070026#include "register_allocation_resolver.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010027#include "ssa_liveness_analysis.h"
28
Vladimir Marko0a516052019-10-14 13:00:44 +000029namespace art {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010030
31static constexpr size_t kMaxLifetimePosition = -1;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010032static constexpr size_t kDefaultNumberOfSpillSlots = 4;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010033
Nicolas Geoffray840e5462015-01-07 16:01:24 +000034// For simplicity, we implement register pairs as (reg, reg + 1).
35// Note that this is a requirement for double registers on ARM, since we
36// allocate SRegister.
37static int GetHighForLowRegister(int reg) { return reg + 1; }
38static bool IsLowRegister(int reg) { return (reg & 1) == 0; }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000039static bool IsLowOfUnalignedPairInterval(LiveInterval* low) {
40 return GetHighForLowRegister(low->GetRegister()) != low->GetHighInterval()->GetRegister();
41}
Nicolas Geoffray840e5462015-01-07 16:01:24 +000042
Vladimir Markoe764d2e2017-10-05 14:35:55 +010043RegisterAllocatorLinearScan::RegisterAllocatorLinearScan(ScopedArenaAllocator* allocator,
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -070044 CodeGenerator* codegen,
45 const SsaLivenessAnalysis& liveness)
46 : RegisterAllocator(allocator, codegen, liveness),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010047 unhandled_core_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
48 unhandled_fp_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
Nicolas Geoffray39468442014-09-02 15:17:15 +010049 unhandled_(nullptr),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010050 handled_(allocator->Adapter(kArenaAllocRegisterAllocator)),
51 active_(allocator->Adapter(kArenaAllocRegisterAllocator)),
52 inactive_(allocator->Adapter(kArenaAllocRegisterAllocator)),
53 physical_core_register_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
54 physical_fp_register_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
55 temp_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
56 int_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
57 long_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
58 float_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
59 double_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
David Brazdil77a48ae2015-09-15 12:34:04 +000060 catch_phi_spill_slots_(0),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010061 safepoints_(allocator->Adapter(kArenaAllocRegisterAllocator)),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010062 processing_core_registers_(false),
63 number_of_registers_(-1),
64 registers_array_(nullptr),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010065 blocked_core_registers_(codegen->GetBlockedCoreRegisters()),
66 blocked_fp_registers_(codegen->GetBlockedFloatingPointRegisters()),
Vladimir Marko70e97462016-08-09 11:04:26 +010067 reserved_out_slots_(0) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010068 temp_intervals_.reserve(4);
69 int_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
70 long_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
71 float_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
72 double_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
73
David Brazdil58282f42016-01-14 12:45:10 +000074 codegen->SetupBlockedRegisters();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010075 physical_core_register_intervals_.resize(codegen->GetNumberOfCoreRegisters(), nullptr);
76 physical_fp_register_intervals_.resize(codegen->GetNumberOfFloatingPointRegisters(), nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +010077 // Always reserve for the current method and the graph's max out registers.
78 // TODO: compute it instead.
Mathieu Chartiere401d142015-04-22 13:56:20 -070079 // ArtMethod* takes 2 vregs for 64 bits.
Andreas Gampe542451c2016-07-26 09:02:02 -070080 size_t ptr_size = static_cast<size_t>(InstructionSetPointerSize(codegen->GetInstructionSet()));
81 reserved_out_slots_ = ptr_size / kVRegSize + codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010082}
83
Vladimir Markoe764d2e2017-10-05 14:35:55 +010084RegisterAllocatorLinearScan::~RegisterAllocatorLinearScan() {}
85
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010086static bool ShouldProcess(bool processing_core_registers, LiveInterval* interval) {
Nicolas Geoffray39468442014-09-02 15:17:15 +010087 if (interval == nullptr) return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010088 bool is_core_register = (interval->GetType() != DataType::Type::kFloat64)
89 && (interval->GetType() != DataType::Type::kFloat32);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010090 return processing_core_registers == is_core_register;
91}
92
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -070093void RegisterAllocatorLinearScan::AllocateRegisters() {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010094 AllocateRegistersInternal();
Vladimir Markoe764d2e2017-10-05 14:35:55 +010095 RegisterAllocationResolver(codegen_, liveness_)
Vladimir Marko70e97462016-08-09 11:04:26 +010096 .Resolve(ArrayRef<HInstruction* const>(safepoints_),
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070097 reserved_out_slots_,
98 int_spill_slots_.size(),
99 long_spill_slots_.size(),
100 float_spill_slots_.size(),
101 double_spill_slots_.size(),
102 catch_phi_spill_slots_,
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100103 ArrayRef<LiveInterval* const>(temp_intervals_));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100104
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;
Aart Bik96202302016-10-04 17:33:56 -0700114 for (HBasicBlock* block : codegen_->GetGraph()->GetLinearOrder()) {
Nicolas Geoffray59768572014-12-01 09:50:04 +0000115 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
116 HInstruction* instruction = inst_it.Current();
117 DCHECK_LE(current_liveness, instruction->GetLifetimePosition());
118 current_liveness = instruction->GetLifetimePosition();
119 }
120 for (HInstructionIterator inst_it(block->GetInstructions());
121 !inst_it.Done();
122 inst_it.Advance()) {
123 HInstruction* instruction = inst_it.Current();
124 DCHECK_LE(current_liveness, instruction->GetLifetimePosition()) << instruction->DebugName();
125 current_liveness = instruction->GetLifetimePosition();
126 }
127 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100128 }
129}
130
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700131void RegisterAllocatorLinearScan::BlockRegister(Location location, size_t start, size_t end) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100132 int reg = location.reg();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100133 DCHECK(location.IsRegister() || location.IsFpuRegister());
134 LiveInterval* interval = location.IsRegister()
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100135 ? physical_core_register_intervals_[reg]
136 : physical_fp_register_intervals_[reg];
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100137 DataType::Type type = location.IsRegister()
138 ? DataType::Type::kInt32
139 : DataType::Type::kFloat32;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100140 if (interval == nullptr) {
141 interval = LiveInterval::MakeFixedInterval(allocator_, reg, type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100142 if (location.IsRegister()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100143 physical_core_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100144 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100145 physical_fp_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100146 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100147 }
148 DCHECK(interval->GetRegister() == reg);
149 interval->AddRange(start, end);
150}
151
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700152void RegisterAllocatorLinearScan::BlockRegisters(size_t start, size_t end, bool caller_save_only) {
David Brazdil77a48ae2015-09-15 12:34:04 +0000153 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
154 if (!caller_save_only || !codegen_->IsCoreCalleeSaveRegister(i)) {
155 BlockRegister(Location::RegisterLocation(i), start, end);
156 }
157 }
158 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
159 if (!caller_save_only || !codegen_->IsFloatingPointCalleeSaveRegister(i)) {
160 BlockRegister(Location::FpuRegisterLocation(i), start, end);
161 }
162 }
163}
164
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700165void RegisterAllocatorLinearScan::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100166 // Iterate post-order, to ensure the list is sorted, and the last added interval
167 // is the one with the lowest start position.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100168 for (HBasicBlock* block : codegen_->GetGraph()->GetLinearPostOrder()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800169 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
170 back_it.Advance()) {
171 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100172 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800173 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
174 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100175 }
David Brazdil77a48ae2015-09-15 12:34:04 +0000176
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000177 if (block->IsCatchBlock() ||
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +0000178 (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000179 // By blocking all registers at the top of each catch block or irreducible loop, we force
180 // intervals belonging to the live-in set of the catch/header block to be spilled.
181 // TODO(ngeoffray): Phis in this block could be allocated in register.
David Brazdil77a48ae2015-09-15 12:34:04 +0000182 size_t position = block->GetLifetimeStart();
183 BlockRegisters(position, position + 1);
184 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100185 }
186
Nicolas Geoffray39468442014-09-02 15:17:15 +0100187 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100188 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
189 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100190 processing_core_registers_ = true;
191 unhandled_ = &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100192 for (LiveInterval* fixed : physical_core_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100193 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700194 // Fixed interval is added to inactive_ instead of unhandled_.
195 // It's also the only type of inactive interval whose start position
196 // can be after the current interval during linear scan.
197 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100198 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100199 }
200 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100201 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100202
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100203 inactive_.clear();
204 active_.clear();
205 handled_.clear();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100206
207 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100208 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
209 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100210 processing_core_registers_ = false;
211 unhandled_ = &unhandled_fp_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100212 for (LiveInterval* fixed : physical_fp_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100213 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700214 // Fixed interval is added to inactive_ instead of unhandled_.
215 // It's also the only type of inactive interval whose start position
216 // can be after the current interval during linear scan.
217 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100218 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100219 }
220 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100221 LinearScan();
222}
223
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700224void RegisterAllocatorLinearScan::ProcessInstruction(HInstruction* instruction) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100225 LocationSummary* locations = instruction->GetLocations();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100226
Santiago Aboy Solanese8a822d2021-09-13 14:40:53 +0100227 // Check for early returns.
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100228 if (locations == nullptr) {
229 return;
Santiago Aboy Solanese8a822d2021-09-13 14:40:53 +0100230 }
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100231 if (TryRemoveSuspendCheckEntry(instruction)) {
232 return;
233 }
234
235 CheckForTempLiveIntervals(instruction);
236 CheckForSafepoint(instruction);
237 if (locations->WillCall()) {
238 // If a call will happen, create fixed intervals for caller-save registers.
239 const size_t position = instruction->GetLifetimePosition();
240 BlockRegisters(position, position + 1, /* caller_save_only= */ true);
241 }
242 CheckForFixedInputs(instruction);
243
244 LiveInterval* current = instruction->GetLiveInterval();
245 if (current == nullptr)
246 return;
247
248 const bool core_register = !DataType::IsFloatingPointType(instruction->GetType());
249 ScopedArenaVector<LiveInterval*>& unhandled =
250 core_register ? unhandled_core_intervals_ : unhandled_fp_intervals_;
251
252 DCHECK(unhandled.empty() || current->StartsBeforeOrAt(unhandled.back()));
253
254 if (codegen_->NeedsTwoRegisters(current->GetType())) {
255 current->AddHighInterval();
256 }
257
258 AddSafepointsFor(instruction);
259 current->ResetSearchCache();
260 CheckForFixedOutput(instruction);
261
262 if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
263 AllocateSpillSlotForCatchPhi(instruction->AsPhi());
264 }
265
266 // If needed, add interval to the list of unhandled intervals.
267 if (current->HasSpillSlot() || instruction->IsConstant()) {
268 // Split just before first register use.
269 size_t first_register_use = current->FirstRegisterUse();
270 if (first_register_use != kNoLifetime) {
271 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
272 // Don't add directly to `unhandled`, it needs to be sorted and the start
273 // of this new interval might be after intervals already in the list.
274 AddSorted(&unhandled, split);
275 } else {
276 // Nothing to do, we won't allocate a register for this value.
277 }
278 } else {
279 // Don't add directly to `unhandled`, temp or safepoint intervals
280 // for this instruction may have been added, and those can be
281 // processed first.
282 AddSorted(&unhandled, current);
283 }
284}
285
286bool RegisterAllocatorLinearScan::TryRemoveSuspendCheckEntry(HInstruction* instruction) {
287 LocationSummary* locations = instruction->GetLocations();
288 if (instruction->IsSuspendCheckEntry() && !codegen_->NeedsSuspendCheckEntry()) {
289 // TODO: We do this here because we do not want the suspend check to artificially
290 // create live registers. We should find another place, but this is currently the
291 // simplest.
292 DCHECK_EQ(locations->GetTempCount(), 0u);
293 instruction->GetBlock()->RemoveInstruction(instruction);
294 return true;
295 }
296 return false;
297}
298
299void RegisterAllocatorLinearScan::CheckForTempLiveIntervals(HInstruction* instruction) {
300 LocationSummary* locations = instruction->GetLocations();
301 size_t position = instruction->GetLifetimePosition();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100302
303 // Create synthesized intervals for temporaries.
304 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
305 Location temp = locations->GetTemp(i);
Nicolas Geoffray52839d12014-11-07 17:47:25 +0000306 if (temp.IsRegister() || temp.IsFpuRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100307 BlockRegister(temp, position, position + 1);
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000308 // Ensure that an explicit temporary register is marked as being allocated.
309 codegen_->AddAllocatedRegister(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100310 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100311 DCHECK(temp.IsUnallocated());
Roland Levillain5368c212014-11-27 15:03:41 +0000312 switch (temp.GetPolicy()) {
313 case Location::kRequiresRegister: {
314 LiveInterval* interval =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100315 LiveInterval::MakeTempInterval(allocator_, DataType::Type::kInt32);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100316 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000317 interval->AddTempUse(instruction, i);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100318 unhandled_core_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000319 break;
320 }
321
322 case Location::kRequiresFpuRegister: {
323 LiveInterval* interval =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100324 LiveInterval::MakeTempInterval(allocator_, DataType::Type::kFloat64);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100325 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000326 interval->AddTempUse(instruction, i);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100327 if (codegen_->NeedsTwoRegisters(DataType::Type::kFloat64)) {
Andreas Gampe3db70682018-12-26 15:12:03 -0800328 interval->AddHighInterval(/* is_temp= */ true);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000329 LiveInterval* high = interval->GetHighInterval();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100330 temp_intervals_.push_back(high);
331 unhandled_fp_intervals_.push_back(high);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000332 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100333 unhandled_fp_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000334 break;
335 }
336
337 default:
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100338 LOG(FATAL) << "Unexpected policy for temporary location " << temp.GetPolicy();
Roland Levillain5368c212014-11-27 15:03:41 +0000339 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100340 }
341 }
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100342}
Nicolas Geoffray39468442014-09-02 15:17:15 +0100343
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100344void RegisterAllocatorLinearScan::CheckForSafepoint(HInstruction* instruction) {
345 LocationSummary* locations = instruction->GetLocations();
346 if (locations->NeedsSafepoint()) {
347 safepoints_.push_back(instruction);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100348 }
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100349}
Nicolas Geoffray39468442014-09-02 15:17:15 +0100350
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100351void RegisterAllocatorLinearScan::CheckForFixedInputs(HInstruction* instruction) {
352 LocationSummary* locations = instruction->GetLocations();
353 size_t position = instruction->GetLifetimePosition();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100354 for (size_t i = 0; i < locations->GetInputCount(); ++i) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100355 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100356 if (input.IsRegister() || input.IsFpuRegister()) {
357 BlockRegister(input, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000358 } else if (input.IsPair()) {
359 BlockRegister(input.ToLow(), position, position + 1);
360 BlockRegister(input.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100361 }
362 }
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100363}
Nicolas Geoffray39468442014-09-02 15:17:15 +0100364
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100365void RegisterAllocatorLinearScan::AddSafepointsFor(HInstruction* instruction) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100366 LiveInterval* current = instruction->GetLiveInterval();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100367 for (size_t safepoint_index = safepoints_.size(); safepoint_index > 0; --safepoint_index) {
368 HInstruction* safepoint = safepoints_[safepoint_index - 1u];
Nicolas Geoffray2aee3af2018-08-27 20:56:45 +0100369 size_t safepoint_position = SafepointPosition::ComputePosition(safepoint);
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100370
371 // Test that safepoints are ordered in the optimal way.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100372 DCHECK(safepoint_index == safepoints_.size() ||
373 safepoints_[safepoint_index]->GetLifetimePosition() < safepoint_position);
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100374
375 if (safepoint_position == current->GetStart()) {
376 // The safepoint is for this instruction, so the location of the instruction
377 // does not need to be saved.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100378 DCHECK_EQ(safepoint_index, safepoints_.size());
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100379 DCHECK_EQ(safepoint, instruction);
380 continue;
381 } else if (current->IsDeadAt(safepoint_position)) {
382 break;
383 } else if (!current->Covers(safepoint_position)) {
384 // Hole in the interval.
385 continue;
386 }
387 current->AddSafepoint(safepoint);
388 }
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100389}
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100390
Santiago Aboy Solanes88b5c1d2021-09-14 15:58:22 +0100391void RegisterAllocatorLinearScan::CheckForFixedOutput(HInstruction* instruction) {
392 LocationSummary* locations = instruction->GetLocations();
393 size_t position = instruction->GetLifetimePosition();
394 LiveInterval* current = instruction->GetLiveInterval();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100395 // Some instructions define their output in fixed register/stack slot. We need
396 // to ensure we know these locations before doing register allocation. For a
397 // given register, we create an interval that covers these locations. The register
398 // will be unavailable at these locations when trying to allocate one for an
399 // interval.
400 //
401 // The backwards walking ensures the ranges are ordered on increasing start positions.
402 Location output = locations->Out();
Calin Juravled0d48522014-11-04 16:40:20 +0000403 if (output.IsUnallocated() && output.GetPolicy() == Location::kSameAsFirstInput) {
404 Location first = locations->InAt(0);
405 if (first.IsRegister() || first.IsFpuRegister()) {
406 current->SetFrom(position + 1);
407 current->SetRegister(first.reg());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000408 } else if (first.IsPair()) {
409 current->SetFrom(position + 1);
410 current->SetRegister(first.low());
411 LiveInterval* high = current->GetHighInterval();
412 high->SetRegister(first.high());
413 high->SetFrom(position + 1);
Calin Juravled0d48522014-11-04 16:40:20 +0000414 }
415 } else if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100416 // Shift the interval's start by one to account for the blocked register.
417 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100418 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100419 BlockRegister(output, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000420 } else if (output.IsPair()) {
421 current->SetFrom(position + 1);
422 current->SetRegister(output.low());
423 LiveInterval* high = current->GetHighInterval();
424 high->SetRegister(output.high());
425 high->SetFrom(position + 1);
426 BlockRegister(output.ToLow(), position, position + 1);
427 BlockRegister(output.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100428 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
429 current->SetSpillSlot(output.GetStackIndex());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000430 } else {
431 DCHECK(output.IsUnallocated() || output.IsConstant());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100432 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100433}
434
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100435class AllRangesIterator : public ValueObject {
436 public:
437 explicit AllRangesIterator(LiveInterval* interval)
438 : current_interval_(interval),
439 current_range_(interval->GetFirstRange()) {}
440
441 bool Done() const { return current_interval_ == nullptr; }
442 LiveRange* CurrentRange() const { return current_range_; }
443 LiveInterval* CurrentInterval() const { return current_interval_; }
444
445 void Advance() {
446 current_range_ = current_range_->GetNext();
447 if (current_range_ == nullptr) {
448 current_interval_ = current_interval_->GetNextSibling();
449 if (current_interval_ != nullptr) {
450 current_range_ = current_interval_->GetFirstRange();
451 }
452 }
453 }
454
455 private:
456 LiveInterval* current_interval_;
457 LiveRange* current_range_;
458
459 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
460};
461
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700462bool RegisterAllocatorLinearScan::ValidateInternal(bool log_fatal_on_failure) const {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100463 // To simplify unit testing, we eagerly create the array of intervals, and
464 // call the helper method.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100465 ScopedArenaAllocator allocator(allocator_->GetArenaStack());
466 ScopedArenaVector<LiveInterval*> intervals(
467 allocator.Adapter(kArenaAllocRegisterAllocatorValidate));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100468 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
469 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
470 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100471 intervals.push_back(instruction->GetLiveInterval());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100472 }
473 }
474
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100475 const ScopedArenaVector<LiveInterval*>* physical_register_intervals = processing_core_registers_
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100476 ? &physical_core_register_intervals_
477 : &physical_fp_register_intervals_;
478 for (LiveInterval* fixed : *physical_register_intervals) {
479 if (fixed != nullptr) {
480 intervals.push_back(fixed);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100481 }
482 }
483
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100484 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100485 if (ShouldProcess(processing_core_registers_, temp)) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100486 intervals.push_back(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100487 }
488 }
489
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100490 return ValidateIntervals(ArrayRef<LiveInterval* const>(intervals),
491 GetNumberOfSpillSlots(),
492 reserved_out_slots_,
493 *codegen_,
494 processing_core_registers_,
495 log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100496}
497
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700498void RegisterAllocatorLinearScan::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100499 interval->Dump(stream);
500 stream << ": ";
501 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100502 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100503 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100504 } else {
505 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100506 }
507 } else {
508 stream << "spilled";
509 }
510 stream << std::endl;
511}
512
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700513void RegisterAllocatorLinearScan::DumpAllIntervals(std::ostream& stream) const {
Mingyao Yang296bd602014-10-06 16:47:28 -0700514 stream << "inactive: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100515 for (LiveInterval* inactive_interval : inactive_) {
516 DumpInterval(stream, inactive_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700517 }
518 stream << "active: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100519 for (LiveInterval* active_interval : active_) {
520 DumpInterval(stream, active_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700521 }
522 stream << "unhandled: " << std::endl;
523 auto unhandled = (unhandled_ != nullptr) ?
524 unhandled_ : &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100525 for (LiveInterval* unhandled_interval : *unhandled) {
526 DumpInterval(stream, unhandled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700527 }
528 stream << "handled: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100529 for (LiveInterval* handled_interval : handled_) {
530 DumpInterval(stream, handled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700531 }
532}
533
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100534// By the book implementation of a linear scan register allocator.
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700535void RegisterAllocatorLinearScan::LinearScan() {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100536 while (!unhandled_->empty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100537 // (1) Remove interval with the lowest start position from unhandled.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100538 LiveInterval* current = unhandled_->back();
539 unhandled_->pop_back();
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100540
541 // Make sure the interval is an expected state.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100542 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100543 // Make sure we are going in the right order.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100544 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() >= current->GetStart());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100545 // Make sure a low interval is always with a high.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100546 DCHECK(!current->IsLowInterval() || unhandled_->back()->IsHighInterval());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100547 // Make sure a high interval is always with a low.
548 DCHECK(current->IsLowInterval() ||
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100549 unhandled_->empty() ||
550 !unhandled_->back()->IsHighInterval());
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000551
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100552 size_t position = current->GetStart();
553
Mingyao Yang296bd602014-10-06 16:47:28 -0700554 // Remember the inactive_ size here since the ones moved to inactive_ from
555 // active_ below shouldn't need to be re-checked.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100556 size_t inactive_intervals_to_handle = inactive_.size();
Mingyao Yang296bd602014-10-06 16:47:28 -0700557
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100558 // (2) Remove currently active intervals that are dead at this position.
559 // Move active intervals that have a lifetime hole at this position
560 // to inactive.
Vladimir Markob95fb772015-09-30 13:32:31 +0100561 auto active_kept_end = std::remove_if(
562 active_.begin(),
563 active_.end(),
564 [this, position](LiveInterval* interval) {
565 if (interval->IsDeadAt(position)) {
566 handled_.push_back(interval);
567 return true;
568 } else if (!interval->Covers(position)) {
569 inactive_.push_back(interval);
570 return true;
571 } else {
572 return false; // Keep this interval.
573 }
574 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100575 active_.erase(active_kept_end, active_.end());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100576
577 // (3) Remove currently inactive intervals that are dead at this position.
578 // Move inactive intervals that cover this position to active.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100579 auto inactive_to_handle_end = inactive_.begin() + inactive_intervals_to_handle;
Vladimir Markob95fb772015-09-30 13:32:31 +0100580 auto inactive_kept_end = std::remove_if(
581 inactive_.begin(),
582 inactive_to_handle_end,
583 [this, position](LiveInterval* interval) {
584 DCHECK(interval->GetStart() < position || interval->IsFixed());
585 if (interval->IsDeadAt(position)) {
586 handled_.push_back(interval);
587 return true;
588 } else if (interval->Covers(position)) {
589 active_.push_back(interval);
590 return true;
591 } else {
592 return false; // Keep this interval.
593 }
594 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100595 inactive_.erase(inactive_kept_end, inactive_to_handle_end);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100596
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000597 if (current->IsHighInterval() && !current->GetLowInterval()->HasRegister()) {
598 DCHECK(!current->HasRegister());
599 // Allocating the low part was unsucessful. The splitted interval for the high part
600 // will be handled next (it is in the `unhandled_` list).
601 continue;
602 }
603
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100604 // (4) Try to find an available register.
605 bool success = TryAllocateFreeReg(current);
606
607 // (5) If no register could be found, we need to spill.
608 if (!success) {
609 success = AllocateBlockedReg(current);
610 }
611
612 // (6) If the interval had a register allocated, add it to the list of active
613 // intervals.
614 if (success) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000615 codegen_->AddAllocatedRegister(processing_core_registers_
616 ? Location::RegisterLocation(current->GetRegister())
617 : Location::FpuRegisterLocation(current->GetRegister()));
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100618 active_.push_back(current);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000619 if (current->HasHighInterval() && !current->GetHighInterval()->HasRegister()) {
620 current->GetHighInterval()->SetRegister(GetHighForLowRegister(current->GetRegister()));
621 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100622 }
623 }
624}
625
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000626static void FreeIfNotCoverAt(LiveInterval* interval, size_t position, size_t* free_until) {
627 DCHECK(!interval->IsHighInterval());
628 // Note that the same instruction may occur multiple times in the input list,
629 // so `free_until` may have changed already.
David Brazdil3fc992f2015-04-16 18:31:55 +0100630 // Since `position` is not the current scan position, we need to use CoversSlow.
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000631 if (interval->IsDeadAt(position)) {
632 // Set the register to be free. Note that inactive intervals might later
633 // update this.
634 free_until[interval->GetRegister()] = kMaxLifetimePosition;
635 if (interval->HasHighInterval()) {
636 DCHECK(interval->GetHighInterval()->IsDeadAt(position));
637 free_until[interval->GetHighInterval()->GetRegister()] = kMaxLifetimePosition;
638 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100639 } else if (!interval->CoversSlow(position)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000640 // The interval becomes inactive at `defined_by`. We make its register
641 // available only until the next use strictly after `defined_by`.
642 free_until[interval->GetRegister()] = interval->FirstUseAfter(position);
643 if (interval->HasHighInterval()) {
David Brazdil3fc992f2015-04-16 18:31:55 +0100644 DCHECK(!interval->GetHighInterval()->CoversSlow(position));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000645 free_until[interval->GetHighInterval()->GetRegister()] = free_until[interval->GetRegister()];
646 }
647 }
648}
649
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100650// Find a free register. If multiple are found, pick the register that
651// is free the longest.
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700652bool RegisterAllocatorLinearScan::TryAllocateFreeReg(LiveInterval* current) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100653 size_t* free_until = registers_array_;
654
655 // First set all registers to be free.
656 for (size_t i = 0; i < number_of_registers_; ++i) {
657 free_until[i] = kMaxLifetimePosition;
658 }
659
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100660 // For each active interval, set its register to not free.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100661 for (LiveInterval* interval : active_) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100662 DCHECK(interval->HasRegister());
663 free_until[interval->GetRegister()] = 0;
664 }
665
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000666 // An interval that starts an instruction (that is, it is not split), may
667 // re-use the registers used by the inputs of that instruciton, based on the
668 // location summary.
669 HInstruction* defined_by = current->GetDefinedBy();
670 if (defined_by != nullptr && !current->IsSplit()) {
671 LocationSummary* locations = defined_by->GetLocations();
672 if (!locations->OutputCanOverlapWithInputs() && locations->Out().IsUnallocated()) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100673 HInputsRef inputs = defined_by->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100674 for (size_t i = 0; i < inputs.size(); ++i) {
Donghui Bai426b49c2016-11-08 14:55:38 +0800675 if (locations->InAt(i).IsValid()) {
676 // Take the last interval of the input. It is the location of that interval
677 // that will be used at `defined_by`.
678 LiveInterval* interval = inputs[i]->GetLiveInterval()->GetLastSibling();
679 // Note that interval may have not been processed yet.
680 // TODO: Handle non-split intervals last in the work list.
681 if (interval->HasRegister() && interval->SameRegisterKind(*current)) {
682 // The input must be live until the end of `defined_by`, to comply to
683 // the linear scan algorithm. So we use `defined_by`'s end lifetime
684 // position to check whether the input is dead or is inactive after
685 // `defined_by`.
686 DCHECK(interval->CoversSlow(defined_by->GetLifetimePosition()));
687 size_t position = defined_by->GetLifetimePosition() + 1;
688 FreeIfNotCoverAt(interval, position, free_until);
689 }
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000690 }
691 }
692 }
693 }
694
Mingyao Yang296bd602014-10-06 16:47:28 -0700695 // For each inactive interval, set its register to be free until
696 // the next intersection with `current`.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100697 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700698 // Temp/Slow-path-safepoint interval has no holes.
Vladimir Marko70e97462016-08-09 11:04:26 +0100699 DCHECK(!inactive->IsTemp());
Mingyao Yang296bd602014-10-06 16:47:28 -0700700 if (!current->IsSplit() && !inactive->IsFixed()) {
701 // Neither current nor inactive are fixed.
702 // Thanks to SSA, a non-split interval starting in a hole of an
703 // inactive interval should never intersect with that inactive interval.
704 // Only if it's not fixed though, because fixed intervals don't come from SSA.
705 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
706 continue;
707 }
708
709 DCHECK(inactive->HasRegister());
710 if (free_until[inactive->GetRegister()] == 0) {
711 // Already used by some active interval. No need to intersect.
712 continue;
713 }
714 size_t next_intersection = inactive->FirstIntersectionWith(current);
715 if (next_intersection != kNoLifetime) {
716 free_until[inactive->GetRegister()] =
717 std::min(free_until[inactive->GetRegister()], next_intersection);
718 }
719 }
720
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000721 int reg = kNoRegister;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100722 if (current->HasRegister()) {
723 // Some instructions have a fixed register output.
724 reg = current->GetRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000725 if (free_until[reg] == 0) {
726 DCHECK(current->IsHighInterval());
727 // AllocateBlockedReg will spill the holder of the register.
728 return false;
729 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100730 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000731 DCHECK(!current->IsHighInterval());
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100732 int hint = current->FindFirstRegisterHint(free_until, liveness_);
Nicolas Geoffrayf2975812015-08-07 18:13:03 -0700733 if ((hint != kNoRegister)
734 // For simplicity, if the hint we are getting for a pair cannot be used,
735 // we are just going to allocate a new pair.
736 && !(current->IsLowInterval() && IsBlocked(GetHighForLowRegister(hint)))) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100737 DCHECK(!IsBlocked(hint));
738 reg = hint;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000739 } else if (current->IsLowInterval()) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000740 reg = FindAvailableRegisterPair(free_until, current->GetStart());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100741 } else {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100742 reg = FindAvailableRegister(free_until, current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100743 }
744 }
745
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000746 DCHECK_NE(reg, kNoRegister);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100747 // If we could not find a register, we need to spill.
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000748 if (free_until[reg] == 0) {
749 return false;
750 }
751
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000752 if (current->IsLowInterval()) {
753 // If the high register of this interval is not available, we need to spill.
754 int high_reg = current->GetHighInterval()->GetRegister();
755 if (high_reg == kNoRegister) {
756 high_reg = GetHighForLowRegister(reg);
757 }
758 if (free_until[high_reg] == 0) {
759 return false;
760 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100761 }
762
763 current->SetRegister(reg);
764 if (!current->IsDeadAt(free_until[reg])) {
765 // If the register is only available for a subset of live ranges
Nicolas Geoffray82726882015-06-01 13:51:57 +0100766 // covered by `current`, split `current` before the position where
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100767 // the register is not available anymore.
Nicolas Geoffray82726882015-06-01 13:51:57 +0100768 LiveInterval* split = SplitBetween(current, current->GetStart(), free_until[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100769 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100770 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100771 }
772 return true;
773}
774
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700775bool RegisterAllocatorLinearScan::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100776 return processing_core_registers_
777 ? blocked_core_registers_[reg]
778 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100779}
780
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700781int RegisterAllocatorLinearScan::FindAvailableRegisterPair(size_t* next_use, size_t starting_at) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000782 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000783 // Pick the register pair that is used the last.
784 for (size_t i = 0; i < number_of_registers_; ++i) {
785 if (IsBlocked(i)) continue;
786 if (!IsLowRegister(i)) continue;
787 int high_register = GetHighForLowRegister(i);
788 if (IsBlocked(high_register)) continue;
789 int existing_high_register = GetHighForLowRegister(reg);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000790 if ((reg == kNoRegister) || (next_use[i] >= next_use[reg]
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000791 && next_use[high_register] >= next_use[existing_high_register])) {
792 reg = i;
793 if (next_use[i] == kMaxLifetimePosition
794 && next_use[high_register] == kMaxLifetimePosition) {
795 break;
796 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000797 } else if (next_use[reg] <= starting_at || next_use[existing_high_register] <= starting_at) {
798 // If one of the current register is known to be unavailable, just unconditionally
799 // try a new one.
800 reg = i;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000801 }
802 }
803 return reg;
804}
805
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700806bool RegisterAllocatorLinearScan::IsCallerSaveRegister(int reg) const {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100807 return processing_core_registers_
808 ? !codegen_->IsCoreCalleeSaveRegister(reg)
809 : !codegen_->IsFloatingPointCalleeSaveRegister(reg);
810}
811
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700812int RegisterAllocatorLinearScan::FindAvailableRegister(size_t* next_use, LiveInterval* current) const {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100813 // We special case intervals that do not span a safepoint to try to find a caller-save
814 // register if one is available. We iterate from 0 to the number of registers,
815 // so if there are caller-save registers available at the end, we continue the iteration.
816 bool prefers_caller_save = !current->HasWillCallSafepoint();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000817 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000818 for (size_t i = 0; i < number_of_registers_; ++i) {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100819 if (IsBlocked(i)) {
820 // Register cannot be used. Continue.
821 continue;
822 }
823
824 // Best case: we found a register fully available.
825 if (next_use[i] == kMaxLifetimePosition) {
826 if (prefers_caller_save && !IsCallerSaveRegister(i)) {
827 // We can get shorter encodings on some platforms by using
828 // small register numbers. So only update the candidate if the previous
829 // one was not available for the whole method.
830 if (reg == kNoRegister || next_use[reg] != kMaxLifetimePosition) {
831 reg = i;
832 }
833 // Continue the iteration in the hope of finding a caller save register.
834 continue;
835 } else {
836 reg = i;
837 // We know the register is good enough. Return it.
838 break;
839 }
840 }
841
842 // If we had no register before, take this one as a reference.
843 if (reg == kNoRegister) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000844 reg = i;
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100845 continue;
846 }
847
848 // Pick the register that is used the last.
849 if (next_use[i] > next_use[reg]) {
850 reg = i;
851 continue;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000852 }
853 }
854 return reg;
855}
856
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100857// Remove interval and its other half if any. Return iterator to the following element.
858static ArenaVector<LiveInterval*>::iterator RemoveIntervalAndPotentialOtherHalf(
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100859 ScopedArenaVector<LiveInterval*>* intervals, ScopedArenaVector<LiveInterval*>::iterator pos) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100860 DCHECK(intervals->begin() <= pos && pos < intervals->end());
861 LiveInterval* interval = *pos;
862 if (interval->IsLowInterval()) {
863 DCHECK(pos + 1 < intervals->end());
864 DCHECK_EQ(*(pos + 1), interval->GetHighInterval());
865 return intervals->erase(pos, pos + 2);
866 } else if (interval->IsHighInterval()) {
867 DCHECK(intervals->begin() < pos);
868 DCHECK_EQ(*(pos - 1), interval->GetLowInterval());
869 return intervals->erase(pos - 1, pos + 1);
870 } else {
871 return intervals->erase(pos);
872 }
873}
874
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700875bool RegisterAllocatorLinearScan::TrySplitNonPairOrUnalignedPairIntervalAt(size_t position,
876 size_t first_register_use,
877 size_t* next_use) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100878 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
879 LiveInterval* active = *it;
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000880 DCHECK(active->HasRegister());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000881 if (active->IsFixed()) continue;
882 if (active->IsHighInterval()) continue;
883 if (first_register_use > next_use[active->GetRegister()]) continue;
884
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100885 // Split the first interval found that is either:
886 // 1) A non-pair interval.
887 // 2) A pair interval whose high is not low + 1.
888 // 3) A pair interval whose low is not even.
889 if (!active->IsLowInterval() ||
890 IsLowOfUnalignedPairInterval(active) ||
891 !IsLowRegister(active->GetRegister())) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000892 LiveInterval* split = Split(active, position);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000893 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100894 handled_.push_back(active);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000895 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100896 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000897 AddSorted(unhandled_, split);
898 return true;
899 }
900 }
901 return false;
902}
903
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100904// Find the register that is used the last, and spill the interval
905// that holds it. If the first use of `current` is after that register
906// we spill `current` instead.
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -0700907bool RegisterAllocatorLinearScan::AllocateBlockedReg(LiveInterval* current) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100908 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -0700909 if (current->HasRegister()) {
910 DCHECK(current->IsHighInterval());
911 // The low interval has allocated the register for the high interval. In
912 // case the low interval had to split both intervals, we may end up in a
913 // situation where the high interval does not have a register use anymore.
914 // We must still proceed in order to split currently active and inactive
915 // uses of the high interval's register, and put the high interval in the
916 // active set.
917 DCHECK(first_register_use != kNoLifetime || (current->GetNextSibling() != nullptr));
918 } else if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100919 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100920 return false;
921 }
922
923 // First set all registers as not being used.
924 size_t* next_use = registers_array_;
925 for (size_t i = 0; i < number_of_registers_; ++i) {
926 next_use[i] = kMaxLifetimePosition;
927 }
928
929 // For each active interval, find the next use of its register after the
930 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100931 for (LiveInterval* active : active_) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100932 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100933 if (active->IsFixed()) {
934 next_use[active->GetRegister()] = current->GetStart();
935 } else {
Nicolas Geoffray119a8852016-02-06 17:01:15 +0000936 size_t use = active->FirstRegisterUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100937 if (use != kNoLifetime) {
938 next_use[active->GetRegister()] = use;
939 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100940 }
941 }
942
943 // For each inactive interval, find the next use of its register after the
944 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100945 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700946 // Temp/Slow-path-safepoint interval has no holes.
Vladimir Marko70e97462016-08-09 11:04:26 +0100947 DCHECK(!inactive->IsTemp());
Mingyao Yang296bd602014-10-06 16:47:28 -0700948 if (!current->IsSplit() && !inactive->IsFixed()) {
949 // Neither current nor inactive are fixed.
950 // Thanks to SSA, a non-split interval starting in a hole of an
951 // inactive interval should never intersect with that inactive interval.
952 // Only if it's not fixed though, because fixed intervals don't come from SSA.
953 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
954 continue;
955 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100956 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100957 size_t next_intersection = inactive->FirstIntersectionWith(current);
958 if (next_intersection != kNoLifetime) {
959 if (inactive->IsFixed()) {
960 next_use[inactive->GetRegister()] =
961 std::min(next_intersection, next_use[inactive->GetRegister()]);
962 } else {
Nicolas Geoffray1ba19812015-04-21 09:12:40 +0100963 size_t use = inactive->FirstUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100964 if (use != kNoLifetime) {
965 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
966 }
967 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100968 }
969 }
970
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000971 int reg = kNoRegister;
972 bool should_spill = false;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000973 if (current->HasRegister()) {
974 DCHECK(current->IsHighInterval());
975 reg = current->GetRegister();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000976 // When allocating the low part, we made sure the high register was available.
Nicolas Geoffray119a8852016-02-06 17:01:15 +0000977 DCHECK_LT(first_register_use, next_use[reg]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000978 } else if (current->IsLowInterval()) {
Nicolas Geoffray119a8852016-02-06 17:01:15 +0000979 reg = FindAvailableRegisterPair(next_use, first_register_use);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000980 // We should spill if both registers are not available.
Nicolas Geoffray119a8852016-02-06 17:01:15 +0000981 should_spill = (first_register_use >= next_use[reg])
982 || (first_register_use >= next_use[GetHighForLowRegister(reg)]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000983 } else {
984 DCHECK(!current->IsHighInterval());
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100985 reg = FindAvailableRegister(next_use, current);
Nicolas Geoffray119a8852016-02-06 17:01:15 +0000986 should_spill = (first_register_use >= next_use[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100987 }
988
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000989 DCHECK_NE(reg, kNoRegister);
990 if (should_spill) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000991 DCHECK(!current->IsHighInterval());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000992 bool is_allocation_at_use_site = (current->GetStart() >= (first_register_use - 1));
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -0700993 if (is_allocation_at_use_site) {
994 if (!current->IsLowInterval()) {
995 DumpInterval(std::cerr, current);
996 DumpAllIntervals(std::cerr);
997 // This situation has the potential to infinite loop, so we make it a non-debug CHECK.
998 HInstruction* at = liveness_.GetInstructionFromPosition(first_register_use / 2);
999 CHECK(false) << "There is not enough registers available for "
1000 << current->GetParent()->GetDefinedBy()->DebugName() << " "
1001 << current->GetParent()->GetDefinedBy()->GetId()
1002 << " at " << first_register_use - 1 << " "
1003 << (at == nullptr ? "" : at->DebugName());
1004 }
1005
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001006 // If we're allocating a register for `current` because the instruction at
1007 // that position requires it, but we think we should spill, then there are
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001008 // non-pair intervals or unaligned pair intervals blocking the allocation.
1009 // We split the first interval found, and put ourselves first in the
1010 // `unhandled_` list.
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001011 bool success = TrySplitNonPairOrUnalignedPairIntervalAt(current->GetStart(),
1012 first_register_use,
1013 next_use);
1014 DCHECK(success);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001015 LiveInterval* existing = unhandled_->back();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001016 DCHECK(existing->IsHighInterval());
1017 DCHECK_EQ(existing->GetLowInterval(), current);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001018 unhandled_->push_back(current);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001019 } else {
1020 // If the first use of that instruction is after the last use of the found
1021 // register, we split this interval just before its first register use.
1022 AllocateSpillSlotFor(current);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001023 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001024 DCHECK(current != split);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001025 AddSorted(unhandled_, split);
1026 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001027 return false;
1028 } else {
1029 // Use this register and spill the active and inactives interval that
1030 // have that register.
1031 current->SetRegister(reg);
1032
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001033 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
1034 LiveInterval* active = *it;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001035 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001036 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001037 LiveInterval* split = Split(active, current->GetStart());
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001038 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001039 handled_.push_back(active);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001040 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001041 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001042 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001043 break;
1044 }
1045 }
1046
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001047 // NOTE: Retrieve end() on each iteration because we're removing elements in the loop body.
1048 for (auto it = inactive_.begin(); it != inactive_.end(); ) {
1049 LiveInterval* inactive = *it;
1050 bool erased = false;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001051 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001052 if (!current->IsSplit() && !inactive->IsFixed()) {
1053 // Neither current nor inactive are fixed.
1054 // Thanks to SSA, a non-split interval starting in a hole of an
1055 // inactive interval should never intersect with that inactive interval.
1056 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1057 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001058 } else {
1059 size_t next_intersection = inactive->FirstIntersectionWith(current);
1060 if (next_intersection != kNoLifetime) {
1061 if (inactive->IsFixed()) {
1062 LiveInterval* split = Split(current, next_intersection);
1063 DCHECK_NE(split, current);
1064 AddSorted(unhandled_, split);
1065 } else {
1066 // Split at the start of `current`, which will lead to splitting
1067 // at the end of the lifetime hole of `inactive`.
1068 LiveInterval* split = Split(inactive, current->GetStart());
1069 // If it's inactive, it must start before the current interval.
1070 DCHECK_NE(split, inactive);
1071 it = RemoveIntervalAndPotentialOtherHalf(&inactive_, it);
1072 erased = true;
1073 handled_.push_back(inactive);
1074 AddSorted(unhandled_, split);
Nicolas Geoffray5b168de2015-03-27 10:27:22 +00001075 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001076 }
1077 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001078 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001079 // If we have erased the element, `it` already points to the next element.
1080 // Otherwise we need to move to the next element.
1081 if (!erased) {
1082 ++it;
1083 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001084 }
1085
1086 return true;
1087 }
1088}
1089
Vladimir Markoe764d2e2017-10-05 14:35:55 +01001090void RegisterAllocatorLinearScan::AddSorted(ScopedArenaVector<LiveInterval*>* array,
1091 LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +01001092 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001093 size_t insert_at = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001094 for (size_t i = array->size(); i > 0; --i) {
1095 LiveInterval* current = (*array)[i - 1u];
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001096 // High intervals must be processed right after their low equivalent.
1097 if (current->StartsAfter(interval) && !current->IsHighInterval()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001098 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001099 break;
1100 }
1101 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001102
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001103 // Insert the high interval before the low, to ensure the low is processed before.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001104 auto insert_pos = array->begin() + insert_at;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001105 if (interval->HasHighInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001106 array->insert(insert_pos, { interval->GetHighInterval(), interval });
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001107 } else if (interval->HasLowInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001108 array->insert(insert_pos, { interval, interval->GetLowInterval() });
1109 } else {
1110 array->insert(insert_pos, interval);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001111 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001112}
1113
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -07001114void RegisterAllocatorLinearScan::AllocateSpillSlotFor(LiveInterval* interval) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001115 if (interval->IsHighInterval()) {
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001116 // The low interval already took care of allocating the spill slot.
1117 DCHECK(!interval->GetLowInterval()->HasRegister());
1118 DCHECK(interval->GetLowInterval()->GetParent()->HasSpillSlot());
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001119 return;
1120 }
1121
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001122 LiveInterval* parent = interval->GetParent();
1123
1124 // An instruction gets a spill slot for its entire lifetime. If the parent
1125 // of this interval already has a spill slot, there is nothing to do.
1126 if (parent->HasSpillSlot()) {
1127 return;
1128 }
1129
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001130 HInstruction* defined_by = parent->GetDefinedBy();
David Brazdil77a48ae2015-09-15 12:34:04 +00001131 DCHECK(!defined_by->IsPhi() || !defined_by->AsPhi()->IsCatchPhi());
1132
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001133 if (defined_by->IsParameterValue()) {
1134 // Parameters have their own stack slot.
1135 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
1136 return;
1137 }
1138
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001139 if (defined_by->IsCurrentMethod()) {
1140 parent->SetSpillSlot(0);
1141 return;
1142 }
1143
Nicolas Geoffray96f89a22014-07-11 10:57:49 +01001144 if (defined_by->IsConstant()) {
1145 // Constants don't need a spill slot.
1146 return;
1147 }
1148
Vladimir Markoe764d2e2017-10-05 14:35:55 +01001149 ScopedArenaVector<size_t>* spill_slots = nullptr;
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001150 switch (interval->GetType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001151 case DataType::Type::kFloat64:
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001152 spill_slots = &double_spill_slots_;
1153 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001154 case DataType::Type::kInt64:
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001155 spill_slots = &long_spill_slots_;
1156 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001157 case DataType::Type::kFloat32:
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001158 spill_slots = &float_spill_slots_;
1159 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001160 case DataType::Type::kReference:
1161 case DataType::Type::kInt32:
1162 case DataType::Type::kUint16:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001163 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001164 case DataType::Type::kInt8:
1165 case DataType::Type::kBool:
1166 case DataType::Type::kInt16:
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001167 spill_slots = &int_spill_slots_;
1168 break;
Aart Bik66c158e2018-01-31 12:55:04 -08001169 case DataType::Type::kUint32:
1170 case DataType::Type::kUint64:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001171 case DataType::Type::kVoid:
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001172 LOG(FATAL) << "Unexpected type for interval " << interval->GetType();
1173 }
1174
Aart Bikcc895252017-03-21 10:55:15 -07001175 // Find first available spill slots.
1176 size_t number_of_spill_slots_needed = parent->NumberOfSpillSlotsNeeded();
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001177 size_t slot = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001178 for (size_t e = spill_slots->size(); slot < e; ++slot) {
Aart Bikcc895252017-03-21 10:55:15 -07001179 bool found = true;
1180 for (size_t s = slot, u = std::min(slot + number_of_spill_slots_needed, e); s < u; s++) {
1181 if ((*spill_slots)[s] > parent->GetStart()) {
1182 found = false; // failure
Matthew Gharrityf64a6ab2016-07-11 14:45:01 -07001183 break;
1184 }
Aart Bikcc895252017-03-21 10:55:15 -07001185 }
1186 if (found) {
1187 break; // success
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001188 }
1189 }
1190
Aart Bikcc895252017-03-21 10:55:15 -07001191 // Need new spill slots?
1192 size_t upper = slot + number_of_spill_slots_needed;
1193 if (upper > spill_slots->size()) {
1194 spill_slots->resize(upper);
1195 }
1196 // Set slots to end.
David Brazdil77a48ae2015-09-15 12:34:04 +00001197 size_t end = interval->GetLastSibling()->GetEnd();
Aart Bikcc895252017-03-21 10:55:15 -07001198 for (size_t s = slot; s < upper; s++) {
1199 (*spill_slots)[s] = end;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001200 }
1201
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001202 // Note that the exact spill slot location will be computed when we resolve,
1203 // that is when we know the number of spill slots for each type.
1204 parent->SetSpillSlot(slot);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001205}
1206
Matthew Gharrity8f49d4b2016-07-14 13:24:00 -07001207void RegisterAllocatorLinearScan::AllocateSpillSlotForCatchPhi(HPhi* phi) {
David Brazdil77a48ae2015-09-15 12:34:04 +00001208 LiveInterval* interval = phi->GetLiveInterval();
1209
1210 HInstruction* previous_phi = phi->GetPrevious();
1211 DCHECK(previous_phi == nullptr ||
1212 previous_phi->AsPhi()->GetRegNumber() <= phi->GetRegNumber())
1213 << "Phis expected to be sorted by vreg number, so that equivalent phis are adjacent.";
1214
1215 if (phi->IsVRegEquivalentOf(previous_phi)) {
1216 // This is an equivalent of the previous phi. We need to assign the same
1217 // catch phi slot.
1218 DCHECK(previous_phi->GetLiveInterval()->HasSpillSlot());
1219 interval->SetSpillSlot(previous_phi->GetLiveInterval()->GetSpillSlot());
1220 } else {
1221 // Allocate a new spill slot for this catch phi.
1222 // TODO: Reuse spill slots when intervals of phis from different catch
1223 // blocks do not overlap.
1224 interval->SetSpillSlot(catch_phi_spill_slots_);
Aart Bikcc895252017-03-21 10:55:15 -07001225 catch_phi_spill_slots_ += interval->NumberOfSpillSlotsNeeded();
David Brazdil77a48ae2015-09-15 12:34:04 +00001226 }
1227}
1228
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001229} // namespace art