blob: 5cd30adb45ff61946b58fdd0a3691121cb74037d [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
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"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010023#include "code_generator.h"
24#include "ssa_liveness_analysis.h"
25
26namespace art {
27
28static constexpr size_t kMaxLifetimePosition = -1;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010029static constexpr size_t kDefaultNumberOfSpillSlots = 4;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010030
Nicolas Geoffray840e5462015-01-07 16:01:24 +000031// For simplicity, we implement register pairs as (reg, reg + 1).
32// Note that this is a requirement for double registers on ARM, since we
33// allocate SRegister.
34static int GetHighForLowRegister(int reg) { return reg + 1; }
35static bool IsLowRegister(int reg) { return (reg & 1) == 0; }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000036static bool IsLowOfUnalignedPairInterval(LiveInterval* low) {
37 return GetHighForLowRegister(low->GetRegister()) != low->GetHighInterval()->GetRegister();
38}
Nicolas Geoffray840e5462015-01-07 16:01:24 +000039
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010040RegisterAllocator::RegisterAllocator(ArenaAllocator* allocator,
41 CodeGenerator* codegen,
42 const SsaLivenessAnalysis& liveness)
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010043 : allocator_(allocator),
44 codegen_(codegen),
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010045 liveness_(liveness),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010046 unhandled_core_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
47 unhandled_fp_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
Nicolas Geoffray39468442014-09-02 15:17:15 +010048 unhandled_(nullptr),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010049 handled_(allocator->Adapter(kArenaAllocRegisterAllocator)),
50 active_(allocator->Adapter(kArenaAllocRegisterAllocator)),
51 inactive_(allocator->Adapter(kArenaAllocRegisterAllocator)),
52 physical_core_register_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
53 physical_fp_register_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
54 temp_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
55 int_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
56 long_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
57 float_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
58 double_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
David Brazdil77a48ae2015-09-15 12:34:04 +000059 catch_phi_spill_slots_(0),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010060 safepoints_(allocator->Adapter(kArenaAllocRegisterAllocator)),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010061 processing_core_registers_(false),
62 number_of_registers_(-1),
63 registers_array_(nullptr),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010064 blocked_core_registers_(codegen->GetBlockedCoreRegisters()),
65 blocked_fp_registers_(codegen->GetBlockedFloatingPointRegisters()),
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +010066 reserved_out_slots_(0),
Mark Mendellf85a9ca2015-01-13 09:20:58 -050067 maximum_number_of_live_core_registers_(0),
68 maximum_number_of_live_fp_registers_(0) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010069 temp_intervals_.reserve(4);
70 int_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
71 long_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
72 float_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
73 double_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
74
David Brazdil58282f42016-01-14 12:45:10 +000075 codegen->SetupBlockedRegisters();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010076 physical_core_register_intervals_.resize(codegen->GetNumberOfCoreRegisters(), nullptr);
77 physical_fp_register_intervals_.resize(codegen->GetNumberOfFloatingPointRegisters(), nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +010078 // Always reserve for the current method and the graph's max out registers.
79 // TODO: compute it instead.
Mathieu Chartiere401d142015-04-22 13:56:20 -070080 // ArtMethod* takes 2 vregs for 64 bits.
81 reserved_out_slots_ = InstructionSetPointerSize(codegen->GetInstructionSet()) / kVRegSize +
82 codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010083}
84
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000085bool RegisterAllocator::CanAllocateRegistersFor(const HGraph& graph ATTRIBUTE_UNUSED,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010086 InstructionSet instruction_set) {
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020087 return instruction_set == kArm
88 || instruction_set == kArm64
89 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -070090 || instruction_set == kMips64
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020091 || instruction_set == kThumb2
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000092 || instruction_set == kX86
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020093 || instruction_set == kX86_64;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010094}
95
96static bool ShouldProcess(bool processing_core_registers, LiveInterval* interval) {
Nicolas Geoffray39468442014-09-02 15:17:15 +010097 if (interval == nullptr) return false;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010098 bool is_core_register = (interval->GetType() != Primitive::kPrimDouble)
99 && (interval->GetType() != Primitive::kPrimFloat);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100100 return processing_core_registers == is_core_register;
101}
102
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100103void RegisterAllocator::AllocateRegisters() {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100104 AllocateRegistersInternal();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100105 Resolve();
106
107 if (kIsDebugBuild) {
108 processing_core_registers_ = true;
109 ValidateInternal(true);
110 processing_core_registers_ = false;
111 ValidateInternal(true);
Nicolas Geoffray59768572014-12-01 09:50:04 +0000112 // Check that the linear order is still correct with regards to lifetime positions.
113 // Since only parallel moves have been inserted during the register allocation,
114 // these checks are mostly for making sure these moves have been added correctly.
115 size_t current_liveness = 0;
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100116 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray59768572014-12-01 09:50:04 +0000117 HBasicBlock* block = it.Current();
118 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
119 HInstruction* instruction = inst_it.Current();
120 DCHECK_LE(current_liveness, instruction->GetLifetimePosition());
121 current_liveness = instruction->GetLifetimePosition();
122 }
123 for (HInstructionIterator inst_it(block->GetInstructions());
124 !inst_it.Done();
125 inst_it.Advance()) {
126 HInstruction* instruction = inst_it.Current();
127 DCHECK_LE(current_liveness, instruction->GetLifetimePosition()) << instruction->DebugName();
128 current_liveness = instruction->GetLifetimePosition();
129 }
130 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100131 }
132}
133
David Brazdil77a48ae2015-09-15 12:34:04 +0000134void RegisterAllocator::BlockRegister(Location location, size_t start, 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()
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100138 ? physical_core_register_intervals_[reg]
139 : physical_fp_register_intervals_[reg];
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100140 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()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100146 physical_core_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100147 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100148 physical_fp_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100149 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100150 }
151 DCHECK(interval->GetRegister() == reg);
152 interval->AddRange(start, end);
153}
154
David Brazdil77a48ae2015-09-15 12:34:04 +0000155void RegisterAllocator::BlockRegisters(size_t start, size_t end, bool caller_save_only) {
156 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
157 if (!caller_save_only || !codegen_->IsCoreCalleeSaveRegister(i)) {
158 BlockRegister(Location::RegisterLocation(i), start, end);
159 }
160 }
161 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
162 if (!caller_save_only || !codegen_->IsFloatingPointCalleeSaveRegister(i)) {
163 BlockRegister(Location::FpuRegisterLocation(i), start, end);
164 }
165 }
166}
167
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100168void RegisterAllocator::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100169 // Iterate post-order, to ensure the list is sorted, and the last added interval
170 // is the one with the lowest start position.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100171 for (HLinearPostOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100172 HBasicBlock* block = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800173 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
174 back_it.Advance()) {
175 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100176 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800177 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
178 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100179 }
David Brazdil77a48ae2015-09-15 12:34:04 +0000180
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000181 if (block->IsCatchBlock() ||
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +0000182 (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000183 // By blocking all registers at the top of each catch block or irreducible loop, we force
184 // intervals belonging to the live-in set of the catch/header block to be spilled.
185 // TODO(ngeoffray): Phis in this block could be allocated in register.
David Brazdil77a48ae2015-09-15 12:34:04 +0000186 size_t position = block->GetLifetimeStart();
187 BlockRegisters(position, position + 1);
188 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100189 }
190
Nicolas Geoffray39468442014-09-02 15:17:15 +0100191 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100192 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
193 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100194 processing_core_registers_ = true;
195 unhandled_ = &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100196 for (LiveInterval* fixed : physical_core_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100197 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700198 // Fixed interval is added to inactive_ instead of unhandled_.
199 // It's also the only type of inactive interval whose start position
200 // can be after the current interval during linear scan.
201 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100202 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100203 }
204 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100205 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100206
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100207 inactive_.clear();
208 active_.clear();
209 handled_.clear();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100210
211 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100212 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
213 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100214 processing_core_registers_ = false;
215 unhandled_ = &unhandled_fp_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100216 for (LiveInterval* fixed : physical_fp_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100217 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700218 // Fixed interval is added to inactive_ instead of unhandled_.
219 // It's also the only type of inactive interval whose start position
220 // can be after the current interval during linear scan.
221 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100222 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100223 }
224 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100225 LinearScan();
226}
227
228void RegisterAllocator::ProcessInstruction(HInstruction* instruction) {
229 LocationSummary* locations = instruction->GetLocations();
230 size_t position = instruction->GetLifetimePosition();
231
232 if (locations == nullptr) return;
233
234 // Create synthesized intervals for temporaries.
235 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
236 Location temp = locations->GetTemp(i);
Nicolas Geoffray52839d12014-11-07 17:47:25 +0000237 if (temp.IsRegister() || temp.IsFpuRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100238 BlockRegister(temp, position, position + 1);
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000239 // Ensure that an explicit temporary register is marked as being allocated.
240 codegen_->AddAllocatedRegister(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100241 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100242 DCHECK(temp.IsUnallocated());
Roland Levillain5368c212014-11-27 15:03:41 +0000243 switch (temp.GetPolicy()) {
244 case Location::kRequiresRegister: {
245 LiveInterval* interval =
246 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimInt);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100247 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000248 interval->AddTempUse(instruction, i);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100249 unhandled_core_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000250 break;
251 }
252
253 case Location::kRequiresFpuRegister: {
254 LiveInterval* interval =
255 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimDouble);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100256 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000257 interval->AddTempUse(instruction, i);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000258 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100259 interval->AddHighInterval(/* is_temp */ true);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000260 LiveInterval* high = interval->GetHighInterval();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100261 temp_intervals_.push_back(high);
262 unhandled_fp_intervals_.push_back(high);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000263 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100264 unhandled_fp_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000265 break;
266 }
267
268 default:
269 LOG(FATAL) << "Unexpected policy for temporary location "
270 << temp.GetPolicy();
271 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100272 }
273 }
274
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100275 bool core_register = (instruction->GetType() != Primitive::kPrimDouble)
276 && (instruction->GetType() != Primitive::kPrimFloat);
277
Alexandre Rames8158f282015-08-07 10:26:17 +0100278 if (locations->NeedsSafepoint()) {
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000279 if (codegen_->IsLeafMethod()) {
280 // TODO: We do this here because we do not want the suspend check to artificially
281 // create live registers. We should find another place, but this is currently the
282 // simplest.
283 DCHECK(instruction->IsSuspendCheckEntry());
284 instruction->GetBlock()->RemoveInstruction(instruction);
285 return;
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100286 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100287 safepoints_.push_back(instruction);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100288 if (locations->OnlyCallsOnSlowPath()) {
289 // We add a synthesized range at this position to record the live registers
290 // at this position. Ideally, we could just update the safepoints when locations
291 // are updated, but we currently need to know the full stack size before updating
292 // locations (because of parameters and the fact that we don't have a frame pointer).
293 // And knowing the full stack size requires to know the maximum number of live
294 // registers at calls in slow paths.
295 // By adding the following interval in the algorithm, we can compute this
296 // maximum before updating locations.
297 LiveInterval* interval = LiveInterval::MakeSlowPathInterval(allocator_, instruction);
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000298 interval->AddRange(position, position + 1);
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000299 AddSorted(&unhandled_core_intervals_, interval);
300 AddSorted(&unhandled_fp_intervals_, interval);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100301 }
302 }
303
304 if (locations->WillCall()) {
David Brazdil77a48ae2015-09-15 12:34:04 +0000305 BlockRegisters(position, position + 1, /* caller_save_only */ true);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100306 }
307
308 for (size_t i = 0; i < instruction->InputCount(); ++i) {
309 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100310 if (input.IsRegister() || input.IsFpuRegister()) {
311 BlockRegister(input, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000312 } else if (input.IsPair()) {
313 BlockRegister(input.ToLow(), position, position + 1);
314 BlockRegister(input.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100315 }
316 }
317
Nicolas Geoffray39468442014-09-02 15:17:15 +0100318 LiveInterval* current = instruction->GetLiveInterval();
319 if (current == nullptr) return;
320
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100321 ArenaVector<LiveInterval*>& unhandled = core_register
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100322 ? unhandled_core_intervals_
323 : unhandled_fp_intervals_;
324
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100325 DCHECK(unhandled.empty() || current->StartsBeforeOrAt(unhandled.back()));
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000326
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000327 if (codegen_->NeedsTwoRegisters(current->GetType())) {
328 current->AddHighInterval();
329 }
330
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100331 for (size_t safepoint_index = safepoints_.size(); safepoint_index > 0; --safepoint_index) {
332 HInstruction* safepoint = safepoints_[safepoint_index - 1u];
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100333 size_t safepoint_position = safepoint->GetLifetimePosition();
334
335 // Test that safepoints are ordered in the optimal way.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100336 DCHECK(safepoint_index == safepoints_.size() ||
337 safepoints_[safepoint_index]->GetLifetimePosition() < safepoint_position);
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100338
339 if (safepoint_position == current->GetStart()) {
340 // The safepoint is for this instruction, so the location of the instruction
341 // does not need to be saved.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100342 DCHECK_EQ(safepoint_index, safepoints_.size());
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100343 DCHECK_EQ(safepoint, instruction);
344 continue;
345 } else if (current->IsDeadAt(safepoint_position)) {
346 break;
347 } else if (!current->Covers(safepoint_position)) {
348 // Hole in the interval.
349 continue;
350 }
351 current->AddSafepoint(safepoint);
352 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100353 current->ResetSearchCache();
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100354
Nicolas Geoffray39468442014-09-02 15:17:15 +0100355 // Some instructions define their output in fixed register/stack slot. We need
356 // to ensure we know these locations before doing register allocation. For a
357 // given register, we create an interval that covers these locations. The register
358 // will be unavailable at these locations when trying to allocate one for an
359 // interval.
360 //
361 // The backwards walking ensures the ranges are ordered on increasing start positions.
362 Location output = locations->Out();
Calin Juravled0d48522014-11-04 16:40:20 +0000363 if (output.IsUnallocated() && output.GetPolicy() == Location::kSameAsFirstInput) {
364 Location first = locations->InAt(0);
365 if (first.IsRegister() || first.IsFpuRegister()) {
366 current->SetFrom(position + 1);
367 current->SetRegister(first.reg());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000368 } else if (first.IsPair()) {
369 current->SetFrom(position + 1);
370 current->SetRegister(first.low());
371 LiveInterval* high = current->GetHighInterval();
372 high->SetRegister(first.high());
373 high->SetFrom(position + 1);
Calin Juravled0d48522014-11-04 16:40:20 +0000374 }
375 } else if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100376 // Shift the interval's start by one to account for the blocked register.
377 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100378 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100379 BlockRegister(output, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000380 } else if (output.IsPair()) {
381 current->SetFrom(position + 1);
382 current->SetRegister(output.low());
383 LiveInterval* high = current->GetHighInterval();
384 high->SetRegister(output.high());
385 high->SetFrom(position + 1);
386 BlockRegister(output.ToLow(), position, position + 1);
387 BlockRegister(output.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100388 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
389 current->SetSpillSlot(output.GetStackIndex());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000390 } else {
391 DCHECK(output.IsUnallocated() || output.IsConstant());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100392 }
393
David Brazdil77a48ae2015-09-15 12:34:04 +0000394 if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
395 AllocateSpillSlotForCatchPhi(instruction->AsPhi());
396 }
397
Nicolas Geoffray39468442014-09-02 15:17:15 +0100398 // If needed, add interval to the list of unhandled intervals.
399 if (current->HasSpillSlot() || instruction->IsConstant()) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100400 // Split just before first register use.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100401 size_t first_register_use = current->FirstRegisterUse();
402 if (first_register_use != kNoLifetime) {
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +0100403 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000404 // Don't add directly to `unhandled`, it needs to be sorted and the start
Nicolas Geoffray39468442014-09-02 15:17:15 +0100405 // of this new interval might be after intervals already in the list.
406 AddSorted(&unhandled, split);
407 } else {
408 // Nothing to do, we won't allocate a register for this value.
409 }
410 } else {
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000411 // Don't add directly to `unhandled`, temp or safepoint intervals
412 // for this instruction may have been added, and those can be
413 // processed first.
414 AddSorted(&unhandled, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100415 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100416}
417
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100418class AllRangesIterator : public ValueObject {
419 public:
420 explicit AllRangesIterator(LiveInterval* interval)
421 : current_interval_(interval),
422 current_range_(interval->GetFirstRange()) {}
423
424 bool Done() const { return current_interval_ == nullptr; }
425 LiveRange* CurrentRange() const { return current_range_; }
426 LiveInterval* CurrentInterval() const { return current_interval_; }
427
428 void Advance() {
429 current_range_ = current_range_->GetNext();
430 if (current_range_ == nullptr) {
431 current_interval_ = current_interval_->GetNextSibling();
432 if (current_interval_ != nullptr) {
433 current_range_ = current_interval_->GetFirstRange();
434 }
435 }
436 }
437
438 private:
439 LiveInterval* current_interval_;
440 LiveRange* current_range_;
441
442 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
443};
444
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100445bool RegisterAllocator::ValidateInternal(bool log_fatal_on_failure) const {
446 // To simplify unit testing, we eagerly create the array of intervals, and
447 // call the helper method.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100448 ArenaVector<LiveInterval*> intervals(allocator_->Adapter(kArenaAllocRegisterAllocator));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100449 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
450 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
451 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100452 intervals.push_back(instruction->GetLiveInterval());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100453 }
454 }
455
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100456 const ArenaVector<LiveInterval*>* physical_register_intervals = processing_core_registers_
457 ? &physical_core_register_intervals_
458 : &physical_fp_register_intervals_;
459 for (LiveInterval* fixed : *physical_register_intervals) {
460 if (fixed != nullptr) {
461 intervals.push_back(fixed);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100462 }
463 }
464
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100465 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100466 if (ShouldProcess(processing_core_registers_, temp)) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100467 intervals.push_back(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100468 }
469 }
470
Nicolas Geoffray776b3182015-02-23 14:14:57 +0000471 return ValidateIntervals(intervals, GetNumberOfSpillSlots(), reserved_out_slots_, *codegen_,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100472 allocator_, processing_core_registers_, log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100473}
474
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100475bool RegisterAllocator::ValidateIntervals(const ArenaVector<LiveInterval*>& intervals,
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100476 size_t number_of_spill_slots,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100477 size_t number_of_out_slots,
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100478 const CodeGenerator& codegen,
479 ArenaAllocator* allocator,
480 bool processing_core_registers,
481 bool log_fatal_on_failure) {
482 size_t number_of_registers = processing_core_registers
483 ? codegen.GetNumberOfCoreRegisters()
484 : codegen.GetNumberOfFloatingPointRegisters();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100485 ArenaVector<ArenaBitVector*> liveness_of_values(
486 allocator->Adapter(kArenaAllocRegisterAllocator));
487 liveness_of_values.reserve(number_of_registers + number_of_spill_slots);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100488
489 // Allocate a bit vector per register. A live interval that has a register
490 // allocated will populate the associated bit vector based on its live ranges.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100491 for (size_t i = 0; i < number_of_registers + number_of_spill_slots; ++i) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100492 liveness_of_values.push_back(new (allocator) ArenaBitVector(allocator, 0, true));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100493 }
494
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100495 for (LiveInterval* start_interval : intervals) {
496 for (AllRangesIterator it(start_interval); !it.Done(); it.Advance()) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100497 LiveInterval* current = it.CurrentInterval();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100498 HInstruction* defined_by = current->GetParent()->GetDefinedBy();
499 if (current->GetParent()->HasSpillSlot()
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100500 // Parameters and current method have their own stack slot.
501 && !(defined_by != nullptr && (defined_by->IsParameterValue()
502 || defined_by->IsCurrentMethod()))) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100503 BitVector* liveness_of_spill_slot = liveness_of_values[number_of_registers
Nicolas Geoffray39468442014-09-02 15:17:15 +0100504 + current->GetParent()->GetSpillSlot() / kVRegSize
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100505 - number_of_out_slots];
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100506 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
507 if (liveness_of_spill_slot->IsBitSet(j)) {
508 if (log_fatal_on_failure) {
509 std::ostringstream message;
510 message << "Spill slot conflict at " << j;
511 LOG(FATAL) << message.str();
512 } else {
513 return false;
514 }
515 } else {
516 liveness_of_spill_slot->SetBit(j);
517 }
518 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100519 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100520
521 if (current->HasRegister()) {
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000522 if (kIsDebugBuild && log_fatal_on_failure && !current->IsFixed()) {
523 // Only check when an error is fatal. Only tests code ask for non-fatal failures
524 // and test code may not properly fill the right information to the code generator.
525 CHECK(codegen.HasAllocatedRegister(processing_core_registers, current->GetRegister()));
526 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100527 BitVector* liveness_of_register = liveness_of_values[current->GetRegister()];
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100528 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
529 if (liveness_of_register->IsBitSet(j)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000530 if (current->IsUsingInputRegister() && current->CanUseInputRegister()) {
531 continue;
532 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100533 if (log_fatal_on_failure) {
534 std::ostringstream message;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100535 message << "Register conflict at " << j << " ";
536 if (defined_by != nullptr) {
537 message << "(" << defined_by->DebugName() << ")";
538 }
539 message << "for ";
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100540 if (processing_core_registers) {
541 codegen.DumpCoreRegister(message, current->GetRegister());
542 } else {
543 codegen.DumpFloatingPointRegister(message, current->GetRegister());
544 }
545 LOG(FATAL) << message.str();
546 } else {
547 return false;
548 }
549 } else {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100550 liveness_of_register->SetBit(j);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100551 }
552 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100553 }
554 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100555 }
556 return true;
557}
558
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100559void RegisterAllocator::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100560 interval->Dump(stream);
561 stream << ": ";
562 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100563 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100564 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100565 } else {
566 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100567 }
568 } else {
569 stream << "spilled";
570 }
571 stream << std::endl;
572}
573
Mingyao Yang296bd602014-10-06 16:47:28 -0700574void RegisterAllocator::DumpAllIntervals(std::ostream& stream) const {
575 stream << "inactive: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100576 for (LiveInterval* inactive_interval : inactive_) {
577 DumpInterval(stream, inactive_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700578 }
579 stream << "active: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100580 for (LiveInterval* active_interval : active_) {
581 DumpInterval(stream, active_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700582 }
583 stream << "unhandled: " << std::endl;
584 auto unhandled = (unhandled_ != nullptr) ?
585 unhandled_ : &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100586 for (LiveInterval* unhandled_interval : *unhandled) {
587 DumpInterval(stream, unhandled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700588 }
589 stream << "handled: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100590 for (LiveInterval* handled_interval : handled_) {
591 DumpInterval(stream, handled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700592 }
593}
594
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100595// By the book implementation of a linear scan register allocator.
596void RegisterAllocator::LinearScan() {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100597 while (!unhandled_->empty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100598 // (1) Remove interval with the lowest start position from unhandled.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100599 LiveInterval* current = unhandled_->back();
600 unhandled_->pop_back();
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100601
602 // Make sure the interval is an expected state.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100603 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100604 // Make sure we are going in the right order.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100605 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() >= current->GetStart());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100606 // Make sure a low interval is always with a high.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100607 DCHECK(!current->IsLowInterval() || unhandled_->back()->IsHighInterval());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100608 // Make sure a high interval is always with a low.
609 DCHECK(current->IsLowInterval() ||
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100610 unhandled_->empty() ||
611 !unhandled_->back()->IsHighInterval());
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000612
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100613 size_t position = current->GetStart();
614
Mingyao Yang296bd602014-10-06 16:47:28 -0700615 // Remember the inactive_ size here since the ones moved to inactive_ from
616 // active_ below shouldn't need to be re-checked.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100617 size_t inactive_intervals_to_handle = inactive_.size();
Mingyao Yang296bd602014-10-06 16:47:28 -0700618
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100619 // (2) Remove currently active intervals that are dead at this position.
620 // Move active intervals that have a lifetime hole at this position
621 // to inactive.
Vladimir Markob95fb772015-09-30 13:32:31 +0100622 auto active_kept_end = std::remove_if(
623 active_.begin(),
624 active_.end(),
625 [this, position](LiveInterval* interval) {
626 if (interval->IsDeadAt(position)) {
627 handled_.push_back(interval);
628 return true;
629 } else if (!interval->Covers(position)) {
630 inactive_.push_back(interval);
631 return true;
632 } else {
633 return false; // Keep this interval.
634 }
635 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100636 active_.erase(active_kept_end, active_.end());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100637
638 // (3) Remove currently inactive intervals that are dead at this position.
639 // Move inactive intervals that cover this position to active.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100640 auto inactive_to_handle_end = inactive_.begin() + inactive_intervals_to_handle;
Vladimir Markob95fb772015-09-30 13:32:31 +0100641 auto inactive_kept_end = std::remove_if(
642 inactive_.begin(),
643 inactive_to_handle_end,
644 [this, position](LiveInterval* interval) {
645 DCHECK(interval->GetStart() < position || interval->IsFixed());
646 if (interval->IsDeadAt(position)) {
647 handled_.push_back(interval);
648 return true;
649 } else if (interval->Covers(position)) {
650 active_.push_back(interval);
651 return true;
652 } else {
653 return false; // Keep this interval.
654 }
655 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100656 inactive_.erase(inactive_kept_end, inactive_to_handle_end);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100657
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000658 if (current->IsSlowPathSafepoint()) {
659 // Synthesized interval to record the maximum number of live registers
660 // at safepoints. No need to allocate a register for it.
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500661 if (processing_core_registers_) {
662 maximum_number_of_live_core_registers_ =
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100663 std::max(maximum_number_of_live_core_registers_, active_.size());
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500664 } else {
665 maximum_number_of_live_fp_registers_ =
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100666 std::max(maximum_number_of_live_fp_registers_, active_.size());
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500667 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100668 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() > current->GetStart());
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000669 continue;
670 }
671
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000672 if (current->IsHighInterval() && !current->GetLowInterval()->HasRegister()) {
673 DCHECK(!current->HasRegister());
674 // Allocating the low part was unsucessful. The splitted interval for the high part
675 // will be handled next (it is in the `unhandled_` list).
676 continue;
677 }
678
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100679 // (4) Try to find an available register.
680 bool success = TryAllocateFreeReg(current);
681
682 // (5) If no register could be found, we need to spill.
683 if (!success) {
684 success = AllocateBlockedReg(current);
685 }
686
687 // (6) If the interval had a register allocated, add it to the list of active
688 // intervals.
689 if (success) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000690 codegen_->AddAllocatedRegister(processing_core_registers_
691 ? Location::RegisterLocation(current->GetRegister())
692 : Location::FpuRegisterLocation(current->GetRegister()));
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100693 active_.push_back(current);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000694 if (current->HasHighInterval() && !current->GetHighInterval()->HasRegister()) {
695 current->GetHighInterval()->SetRegister(GetHighForLowRegister(current->GetRegister()));
696 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100697 }
698 }
699}
700
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000701static void FreeIfNotCoverAt(LiveInterval* interval, size_t position, size_t* free_until) {
702 DCHECK(!interval->IsHighInterval());
703 // Note that the same instruction may occur multiple times in the input list,
704 // so `free_until` may have changed already.
David Brazdil3fc992f2015-04-16 18:31:55 +0100705 // Since `position` is not the current scan position, we need to use CoversSlow.
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000706 if (interval->IsDeadAt(position)) {
707 // Set the register to be free. Note that inactive intervals might later
708 // update this.
709 free_until[interval->GetRegister()] = kMaxLifetimePosition;
710 if (interval->HasHighInterval()) {
711 DCHECK(interval->GetHighInterval()->IsDeadAt(position));
712 free_until[interval->GetHighInterval()->GetRegister()] = kMaxLifetimePosition;
713 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100714 } else if (!interval->CoversSlow(position)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000715 // The interval becomes inactive at `defined_by`. We make its register
716 // available only until the next use strictly after `defined_by`.
717 free_until[interval->GetRegister()] = interval->FirstUseAfter(position);
718 if (interval->HasHighInterval()) {
David Brazdil3fc992f2015-04-16 18:31:55 +0100719 DCHECK(!interval->GetHighInterval()->CoversSlow(position));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000720 free_until[interval->GetHighInterval()->GetRegister()] = free_until[interval->GetRegister()];
721 }
722 }
723}
724
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100725// Find a free register. If multiple are found, pick the register that
726// is free the longest.
727bool RegisterAllocator::TryAllocateFreeReg(LiveInterval* current) {
728 size_t* free_until = registers_array_;
729
730 // First set all registers to be free.
731 for (size_t i = 0; i < number_of_registers_; ++i) {
732 free_until[i] = kMaxLifetimePosition;
733 }
734
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100735 // For each active interval, set its register to not free.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100736 for (LiveInterval* interval : active_) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100737 DCHECK(interval->HasRegister());
738 free_until[interval->GetRegister()] = 0;
739 }
740
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000741 // An interval that starts an instruction (that is, it is not split), may
742 // re-use the registers used by the inputs of that instruciton, based on the
743 // location summary.
744 HInstruction* defined_by = current->GetDefinedBy();
745 if (defined_by != nullptr && !current->IsSplit()) {
746 LocationSummary* locations = defined_by->GetLocations();
747 if (!locations->OutputCanOverlapWithInputs() && locations->Out().IsUnallocated()) {
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100748 for (size_t i = 0, e = defined_by->InputCount(); i < e; ++i) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000749 // Take the last interval of the input. It is the location of that interval
750 // that will be used at `defined_by`.
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100751 LiveInterval* interval = defined_by->InputAt(i)->GetLiveInterval()->GetLastSibling();
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000752 // Note that interval may have not been processed yet.
753 // TODO: Handle non-split intervals last in the work list.
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100754 if (locations->InAt(i).IsValid()
755 && interval->HasRegister()
756 && interval->SameRegisterKind(*current)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000757 // The input must be live until the end of `defined_by`, to comply to
758 // the linear scan algorithm. So we use `defined_by`'s end lifetime
759 // position to check whether the input is dead or is inactive after
760 // `defined_by`.
David Brazdil3fc992f2015-04-16 18:31:55 +0100761 DCHECK(interval->CoversSlow(defined_by->GetLifetimePosition()));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000762 size_t position = defined_by->GetLifetimePosition() + 1;
763 FreeIfNotCoverAt(interval, position, free_until);
764 }
765 }
766 }
767 }
768
Mingyao Yang296bd602014-10-06 16:47:28 -0700769 // For each inactive interval, set its register to be free until
770 // the next intersection with `current`.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100771 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700772 // Temp/Slow-path-safepoint interval has no holes.
773 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
774 if (!current->IsSplit() && !inactive->IsFixed()) {
775 // Neither current nor inactive are fixed.
776 // Thanks to SSA, a non-split interval starting in a hole of an
777 // inactive interval should never intersect with that inactive interval.
778 // Only if it's not fixed though, because fixed intervals don't come from SSA.
779 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
780 continue;
781 }
782
783 DCHECK(inactive->HasRegister());
784 if (free_until[inactive->GetRegister()] == 0) {
785 // Already used by some active interval. No need to intersect.
786 continue;
787 }
788 size_t next_intersection = inactive->FirstIntersectionWith(current);
789 if (next_intersection != kNoLifetime) {
790 free_until[inactive->GetRegister()] =
791 std::min(free_until[inactive->GetRegister()], next_intersection);
792 }
793 }
794
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000795 int reg = kNoRegister;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100796 if (current->HasRegister()) {
797 // Some instructions have a fixed register output.
798 reg = current->GetRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000799 if (free_until[reg] == 0) {
800 DCHECK(current->IsHighInterval());
801 // AllocateBlockedReg will spill the holder of the register.
802 return false;
803 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100804 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000805 DCHECK(!current->IsHighInterval());
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100806 int hint = current->FindFirstRegisterHint(free_until, liveness_);
Nicolas Geoffrayf2975812015-08-07 18:13:03 -0700807 if ((hint != kNoRegister)
808 // For simplicity, if the hint we are getting for a pair cannot be used,
809 // we are just going to allocate a new pair.
810 && !(current->IsLowInterval() && IsBlocked(GetHighForLowRegister(hint)))) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100811 DCHECK(!IsBlocked(hint));
812 reg = hint;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000813 } else if (current->IsLowInterval()) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000814 reg = FindAvailableRegisterPair(free_until, current->GetStart());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100815 } else {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100816 reg = FindAvailableRegister(free_until, current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100817 }
818 }
819
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000820 DCHECK_NE(reg, kNoRegister);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100821 // If we could not find a register, we need to spill.
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000822 if (free_until[reg] == 0) {
823 return false;
824 }
825
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000826 if (current->IsLowInterval()) {
827 // If the high register of this interval is not available, we need to spill.
828 int high_reg = current->GetHighInterval()->GetRegister();
829 if (high_reg == kNoRegister) {
830 high_reg = GetHighForLowRegister(reg);
831 }
832 if (free_until[high_reg] == 0) {
833 return false;
834 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100835 }
836
837 current->SetRegister(reg);
838 if (!current->IsDeadAt(free_until[reg])) {
839 // If the register is only available for a subset of live ranges
Nicolas Geoffray82726882015-06-01 13:51:57 +0100840 // covered by `current`, split `current` before the position where
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100841 // the register is not available anymore.
Nicolas Geoffray82726882015-06-01 13:51:57 +0100842 LiveInterval* split = SplitBetween(current, current->GetStart(), free_until[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100843 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100844 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100845 }
846 return true;
847}
848
849bool RegisterAllocator::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100850 return processing_core_registers_
851 ? blocked_core_registers_[reg]
852 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100853}
854
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000855int RegisterAllocator::FindAvailableRegisterPair(size_t* next_use, size_t starting_at) const {
856 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000857 // Pick the register pair that is used the last.
858 for (size_t i = 0; i < number_of_registers_; ++i) {
859 if (IsBlocked(i)) continue;
860 if (!IsLowRegister(i)) continue;
861 int high_register = GetHighForLowRegister(i);
862 if (IsBlocked(high_register)) continue;
863 int existing_high_register = GetHighForLowRegister(reg);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000864 if ((reg == kNoRegister) || (next_use[i] >= next_use[reg]
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000865 && next_use[high_register] >= next_use[existing_high_register])) {
866 reg = i;
867 if (next_use[i] == kMaxLifetimePosition
868 && next_use[high_register] == kMaxLifetimePosition) {
869 break;
870 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000871 } else if (next_use[reg] <= starting_at || next_use[existing_high_register] <= starting_at) {
872 // If one of the current register is known to be unavailable, just unconditionally
873 // try a new one.
874 reg = i;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000875 }
876 }
877 return reg;
878}
879
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100880bool RegisterAllocator::IsCallerSaveRegister(int reg) const {
881 return processing_core_registers_
882 ? !codegen_->IsCoreCalleeSaveRegister(reg)
883 : !codegen_->IsFloatingPointCalleeSaveRegister(reg);
884}
885
886int RegisterAllocator::FindAvailableRegister(size_t* next_use, LiveInterval* current) const {
887 // We special case intervals that do not span a safepoint to try to find a caller-save
888 // register if one is available. We iterate from 0 to the number of registers,
889 // so if there are caller-save registers available at the end, we continue the iteration.
890 bool prefers_caller_save = !current->HasWillCallSafepoint();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000891 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000892 for (size_t i = 0; i < number_of_registers_; ++i) {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100893 if (IsBlocked(i)) {
894 // Register cannot be used. Continue.
895 continue;
896 }
897
898 // Best case: we found a register fully available.
899 if (next_use[i] == kMaxLifetimePosition) {
900 if (prefers_caller_save && !IsCallerSaveRegister(i)) {
901 // We can get shorter encodings on some platforms by using
902 // small register numbers. So only update the candidate if the previous
903 // one was not available for the whole method.
904 if (reg == kNoRegister || next_use[reg] != kMaxLifetimePosition) {
905 reg = i;
906 }
907 // Continue the iteration in the hope of finding a caller save register.
908 continue;
909 } else {
910 reg = i;
911 // We know the register is good enough. Return it.
912 break;
913 }
914 }
915
916 // If we had no register before, take this one as a reference.
917 if (reg == kNoRegister) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000918 reg = i;
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100919 continue;
920 }
921
922 // Pick the register that is used the last.
923 if (next_use[i] > next_use[reg]) {
924 reg = i;
925 continue;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000926 }
927 }
928 return reg;
929}
930
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100931// Remove interval and its other half if any. Return iterator to the following element.
932static ArenaVector<LiveInterval*>::iterator RemoveIntervalAndPotentialOtherHalf(
933 ArenaVector<LiveInterval*>* intervals, ArenaVector<LiveInterval*>::iterator pos) {
934 DCHECK(intervals->begin() <= pos && pos < intervals->end());
935 LiveInterval* interval = *pos;
936 if (interval->IsLowInterval()) {
937 DCHECK(pos + 1 < intervals->end());
938 DCHECK_EQ(*(pos + 1), interval->GetHighInterval());
939 return intervals->erase(pos, pos + 2);
940 } else if (interval->IsHighInterval()) {
941 DCHECK(intervals->begin() < pos);
942 DCHECK_EQ(*(pos - 1), interval->GetLowInterval());
943 return intervals->erase(pos - 1, pos + 1);
944 } else {
945 return intervals->erase(pos);
946 }
947}
948
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000949bool RegisterAllocator::TrySplitNonPairOrUnalignedPairIntervalAt(size_t position,
950 size_t first_register_use,
951 size_t* next_use) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100952 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
953 LiveInterval* active = *it;
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000954 DCHECK(active->HasRegister());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000955 if (active->IsFixed()) continue;
956 if (active->IsHighInterval()) continue;
957 if (first_register_use > next_use[active->GetRegister()]) continue;
958
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100959 // Split the first interval found that is either:
960 // 1) A non-pair interval.
961 // 2) A pair interval whose high is not low + 1.
962 // 3) A pair interval whose low is not even.
963 if (!active->IsLowInterval() ||
964 IsLowOfUnalignedPairInterval(active) ||
965 !IsLowRegister(active->GetRegister())) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000966 LiveInterval* split = Split(active, position);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000967 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100968 handled_.push_back(active);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000969 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100970 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000971 AddSorted(unhandled_, split);
972 return true;
973 }
974 }
975 return false;
976}
977
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100978// Find the register that is used the last, and spill the interval
979// that holds it. If the first use of `current` is after that register
980// we spill `current` instead.
981bool RegisterAllocator::AllocateBlockedReg(LiveInterval* current) {
982 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -0700983 if (current->HasRegister()) {
984 DCHECK(current->IsHighInterval());
985 // The low interval has allocated the register for the high interval. In
986 // case the low interval had to split both intervals, we may end up in a
987 // situation where the high interval does not have a register use anymore.
988 // We must still proceed in order to split currently active and inactive
989 // uses of the high interval's register, and put the high interval in the
990 // active set.
991 DCHECK(first_register_use != kNoLifetime || (current->GetNextSibling() != nullptr));
992 } else if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100993 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100994 return false;
995 }
996
Nicolas Geoffray1ba19812015-04-21 09:12:40 +0100997 // We use the first use to compare with other intervals. If this interval
998 // is used after any active intervals, we will spill this interval.
999 size_t first_use = current->FirstUseAfter(current->GetStart());
1000
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001001 // First set all registers as not being used.
1002 size_t* next_use = registers_array_;
1003 for (size_t i = 0; i < number_of_registers_; ++i) {
1004 next_use[i] = kMaxLifetimePosition;
1005 }
1006
1007 // For each active interval, find the next use of its register after the
1008 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001009 for (LiveInterval* active : active_) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001010 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001011 if (active->IsFixed()) {
1012 next_use[active->GetRegister()] = current->GetStart();
1013 } else {
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001014 size_t use = active->FirstUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001015 if (use != kNoLifetime) {
1016 next_use[active->GetRegister()] = use;
1017 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001018 }
1019 }
1020
1021 // For each inactive interval, find the next use of its register after the
1022 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001023 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001024 // Temp/Slow-path-safepoint interval has no holes.
1025 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
1026 if (!current->IsSplit() && !inactive->IsFixed()) {
1027 // Neither current nor inactive are fixed.
1028 // Thanks to SSA, a non-split interval starting in a hole of an
1029 // inactive interval should never intersect with that inactive interval.
1030 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1031 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
1032 continue;
1033 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001034 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001035 size_t next_intersection = inactive->FirstIntersectionWith(current);
1036 if (next_intersection != kNoLifetime) {
1037 if (inactive->IsFixed()) {
1038 next_use[inactive->GetRegister()] =
1039 std::min(next_intersection, next_use[inactive->GetRegister()]);
1040 } else {
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001041 size_t use = inactive->FirstUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001042 if (use != kNoLifetime) {
1043 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
1044 }
1045 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001046 }
1047 }
1048
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001049 int reg = kNoRegister;
1050 bool should_spill = false;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001051 if (current->HasRegister()) {
1052 DCHECK(current->IsHighInterval());
1053 reg = current->GetRegister();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001054 // When allocating the low part, we made sure the high register was available.
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001055 DCHECK_LT(first_use, next_use[reg]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001056 } else if (current->IsLowInterval()) {
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001057 reg = FindAvailableRegisterPair(next_use, first_use);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001058 // We should spill if both registers are not available.
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001059 should_spill = (first_use >= next_use[reg])
1060 || (first_use >= next_use[GetHighForLowRegister(reg)]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001061 } else {
1062 DCHECK(!current->IsHighInterval());
Nicolas Geoffray8826f672015-04-17 09:15:11 +01001063 reg = FindAvailableRegister(next_use, current);
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001064 should_spill = (first_use >= next_use[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001065 }
1066
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001067 DCHECK_NE(reg, kNoRegister);
1068 if (should_spill) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001069 DCHECK(!current->IsHighInterval());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001070 bool is_allocation_at_use_site = (current->GetStart() >= (first_register_use - 1));
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001071 if (is_allocation_at_use_site) {
1072 if (!current->IsLowInterval()) {
1073 DumpInterval(std::cerr, current);
1074 DumpAllIntervals(std::cerr);
1075 // This situation has the potential to infinite loop, so we make it a non-debug CHECK.
1076 HInstruction* at = liveness_.GetInstructionFromPosition(first_register_use / 2);
1077 CHECK(false) << "There is not enough registers available for "
1078 << current->GetParent()->GetDefinedBy()->DebugName() << " "
1079 << current->GetParent()->GetDefinedBy()->GetId()
1080 << " at " << first_register_use - 1 << " "
1081 << (at == nullptr ? "" : at->DebugName());
1082 }
1083
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001084 // If we're allocating a register for `current` because the instruction at
1085 // that position requires it, but we think we should spill, then there are
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001086 // non-pair intervals or unaligned pair intervals blocking the allocation.
1087 // We split the first interval found, and put ourselves first in the
1088 // `unhandled_` list.
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001089 bool success = TrySplitNonPairOrUnalignedPairIntervalAt(current->GetStart(),
1090 first_register_use,
1091 next_use);
1092 DCHECK(success);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001093 LiveInterval* existing = unhandled_->back();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001094 DCHECK(existing->IsHighInterval());
1095 DCHECK_EQ(existing->GetLowInterval(), current);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001096 unhandled_->push_back(current);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001097 } else {
1098 // If the first use of that instruction is after the last use of the found
1099 // register, we split this interval just before its first register use.
1100 AllocateSpillSlotFor(current);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001101 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001102 DCHECK(current != split);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001103 AddSorted(unhandled_, split);
1104 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001105 return false;
1106 } else {
1107 // Use this register and spill the active and inactives interval that
1108 // have that register.
1109 current->SetRegister(reg);
1110
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001111 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
1112 LiveInterval* active = *it;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001113 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001114 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001115 LiveInterval* split = Split(active, current->GetStart());
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001116 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001117 handled_.push_back(active);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001118 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001119 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001120 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001121 break;
1122 }
1123 }
1124
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001125 // NOTE: Retrieve end() on each iteration because we're removing elements in the loop body.
1126 for (auto it = inactive_.begin(); it != inactive_.end(); ) {
1127 LiveInterval* inactive = *it;
1128 bool erased = false;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001129 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001130 if (!current->IsSplit() && !inactive->IsFixed()) {
1131 // Neither current nor inactive are fixed.
1132 // Thanks to SSA, a non-split interval starting in a hole of an
1133 // inactive interval should never intersect with that inactive interval.
1134 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1135 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001136 } else {
1137 size_t next_intersection = inactive->FirstIntersectionWith(current);
1138 if (next_intersection != kNoLifetime) {
1139 if (inactive->IsFixed()) {
1140 LiveInterval* split = Split(current, next_intersection);
1141 DCHECK_NE(split, current);
1142 AddSorted(unhandled_, split);
1143 } else {
1144 // Split at the start of `current`, which will lead to splitting
1145 // at the end of the lifetime hole of `inactive`.
1146 LiveInterval* split = Split(inactive, current->GetStart());
1147 // If it's inactive, it must start before the current interval.
1148 DCHECK_NE(split, inactive);
1149 it = RemoveIntervalAndPotentialOtherHalf(&inactive_, it);
1150 erased = true;
1151 handled_.push_back(inactive);
1152 AddSorted(unhandled_, split);
Nicolas Geoffray5b168de2015-03-27 10:27:22 +00001153 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001154 }
1155 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001156 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001157 // If we have erased the element, `it` already points to the next element.
1158 // Otherwise we need to move to the next element.
1159 if (!erased) {
1160 ++it;
1161 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001162 }
1163
1164 return true;
1165 }
1166}
1167
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001168void RegisterAllocator::AddSorted(ArenaVector<LiveInterval*>* array, LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +01001169 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001170 size_t insert_at = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001171 for (size_t i = array->size(); i > 0; --i) {
1172 LiveInterval* current = (*array)[i - 1u];
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001173 // High intervals must be processed right after their low equivalent.
1174 if (current->StartsAfter(interval) && !current->IsHighInterval()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001175 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001176 break;
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001177 } else if ((current->GetStart() == interval->GetStart()) && current->IsSlowPathSafepoint()) {
1178 // Ensure the slow path interval is the last to be processed at its location: we want the
1179 // interval to know all live registers at this location.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001180 DCHECK(i == 1 || (*array)[i - 2u]->StartsAfter(current));
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001181 insert_at = i;
1182 break;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001183 }
1184 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001185
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001186 // Insert the high interval before the low, to ensure the low is processed before.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001187 auto insert_pos = array->begin() + insert_at;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001188 if (interval->HasHighInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001189 array->insert(insert_pos, { interval->GetHighInterval(), interval });
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001190 } else if (interval->HasLowInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001191 array->insert(insert_pos, { interval, interval->GetLowInterval() });
1192 } else {
1193 array->insert(insert_pos, interval);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001194 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001195}
1196
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001197LiveInterval* RegisterAllocator::SplitBetween(LiveInterval* interval, size_t from, size_t to) {
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001198 HBasicBlock* block_from = liveness_.GetBlockFromPosition(from / 2);
1199 HBasicBlock* block_to = liveness_.GetBlockFromPosition(to / 2);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001200 DCHECK(block_from != nullptr);
1201 DCHECK(block_to != nullptr);
1202
1203 // Both locations are in the same block. We split at the given location.
1204 if (block_from == block_to) {
1205 return Split(interval, to);
1206 }
1207
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001208 /*
1209 * Non-linear control flow will force moves at every branch instruction to the new location.
1210 * To avoid having all branches doing the moves, we find the next non-linear position and
1211 * split the interval at this position. Take the following example (block number is the linear
1212 * order position):
1213 *
1214 * B1
1215 * / \
1216 * B2 B3
1217 * \ /
1218 * B4
1219 *
1220 * B2 needs to split an interval, whose next use is in B4. If we were to split at the
1221 * beginning of B4, B3 would need to do a move between B3 and B4 to ensure the interval
1222 * is now in the correct location. It makes performance worst if the interval is spilled
1223 * and both B2 and B3 need to reload it before entering B4.
1224 *
1225 * By splitting at B3, we give a chance to the register allocator to allocate the
1226 * interval to the same register as in B1, and therefore avoid doing any
1227 * moves in B3.
1228 */
1229 if (block_from->GetDominator() != nullptr) {
Vladimir Marko60584552015-09-03 13:35:12 +00001230 for (HBasicBlock* dominated : block_from->GetDominator()->GetDominatedBlocks()) {
1231 size_t position = dominated->GetLifetimeStart();
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001232 if ((position > from) && (block_to->GetLifetimeStart() > position)) {
1233 // Even if we found a better block, we continue iterating in case
1234 // a dominated block is closer.
1235 // Note that dominated blocks are not sorted in liveness order.
Vladimir Marko60584552015-09-03 13:35:12 +00001236 block_to = dominated;
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001237 DCHECK_NE(block_to, block_from);
1238 }
1239 }
1240 }
1241
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001242 // If `to` is in a loop, find the outermost loop header which does not contain `from`.
1243 for (HLoopInformationOutwardIterator it(*block_to); !it.Done(); it.Advance()) {
1244 HBasicBlock* header = it.Current()->GetHeader();
1245 if (block_from->GetLifetimeStart() >= header->GetLifetimeStart()) {
1246 break;
1247 }
1248 block_to = header;
1249 }
1250
1251 // Split at the start of the found block, to piggy back on existing moves
1252 // due to resolution if non-linear control flow (see `ConnectSplitSiblings`).
1253 return Split(interval, block_to->GetLifetimeStart());
1254}
1255
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001256LiveInterval* RegisterAllocator::Split(LiveInterval* interval, size_t position) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001257 DCHECK_GE(position, interval->GetStart());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001258 DCHECK(!interval->IsDeadAt(position));
1259 if (position == interval->GetStart()) {
1260 // Spill slot will be allocated when handling `interval` again.
1261 interval->ClearRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001262 if (interval->HasHighInterval()) {
1263 interval->GetHighInterval()->ClearRegister();
1264 } else if (interval->HasLowInterval()) {
1265 interval->GetLowInterval()->ClearRegister();
1266 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001267 return interval;
1268 } else {
1269 LiveInterval* new_interval = interval->SplitAt(position);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001270 if (interval->HasHighInterval()) {
1271 LiveInterval* high = interval->GetHighInterval()->SplitAt(position);
1272 new_interval->SetHighInterval(high);
1273 high->SetLowInterval(new_interval);
1274 } else if (interval->HasLowInterval()) {
1275 LiveInterval* low = interval->GetLowInterval()->SplitAt(position);
1276 new_interval->SetLowInterval(low);
1277 low->SetHighInterval(new_interval);
1278 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001279 return new_interval;
1280 }
1281}
1282
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001283void RegisterAllocator::AllocateSpillSlotFor(LiveInterval* interval) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001284 if (interval->IsHighInterval()) {
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001285 // The low interval already took care of allocating the spill slot.
1286 DCHECK(!interval->GetLowInterval()->HasRegister());
1287 DCHECK(interval->GetLowInterval()->GetParent()->HasSpillSlot());
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001288 return;
1289 }
1290
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001291 LiveInterval* parent = interval->GetParent();
1292
1293 // An instruction gets a spill slot for its entire lifetime. If the parent
1294 // of this interval already has a spill slot, there is nothing to do.
1295 if (parent->HasSpillSlot()) {
1296 return;
1297 }
1298
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001299 HInstruction* defined_by = parent->GetDefinedBy();
David Brazdil77a48ae2015-09-15 12:34:04 +00001300 DCHECK(!defined_by->IsPhi() || !defined_by->AsPhi()->IsCatchPhi());
1301
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001302 if (defined_by->IsParameterValue()) {
1303 // Parameters have their own stack slot.
1304 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
1305 return;
1306 }
1307
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001308 if (defined_by->IsCurrentMethod()) {
1309 parent->SetSpillSlot(0);
1310 return;
1311 }
1312
Nicolas Geoffray96f89a22014-07-11 10:57:49 +01001313 if (defined_by->IsConstant()) {
1314 // Constants don't need a spill slot.
1315 return;
1316 }
1317
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001318 ArenaVector<size_t>* spill_slots = nullptr;
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001319 switch (interval->GetType()) {
1320 case Primitive::kPrimDouble:
1321 spill_slots = &double_spill_slots_;
1322 break;
1323 case Primitive::kPrimLong:
1324 spill_slots = &long_spill_slots_;
1325 break;
1326 case Primitive::kPrimFloat:
1327 spill_slots = &float_spill_slots_;
1328 break;
1329 case Primitive::kPrimNot:
1330 case Primitive::kPrimInt:
1331 case Primitive::kPrimChar:
1332 case Primitive::kPrimByte:
1333 case Primitive::kPrimBoolean:
1334 case Primitive::kPrimShort:
1335 spill_slots = &int_spill_slots_;
1336 break;
1337 case Primitive::kPrimVoid:
1338 LOG(FATAL) << "Unexpected type for interval " << interval->GetType();
1339 }
1340
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001341 // Find an available spill slot.
1342 size_t slot = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001343 for (size_t e = spill_slots->size(); slot < e; ++slot) {
1344 if ((*spill_slots)[slot] <= parent->GetStart()
1345 && (slot == (e - 1) || (*spill_slots)[slot + 1] <= parent->GetStart())) {
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001346 break;
1347 }
1348 }
1349
David Brazdil77a48ae2015-09-15 12:34:04 +00001350 size_t end = interval->GetLastSibling()->GetEnd();
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001351 if (parent->NeedsTwoSpillSlots()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001352 if (slot + 2u > spill_slots->size()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001353 // We need a new spill slot.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001354 spill_slots->resize(slot + 2u, end);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001355 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001356 (*spill_slots)[slot] = end;
1357 (*spill_slots)[slot + 1] = end;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001358 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001359 if (slot == spill_slots->size()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001360 // We need a new spill slot.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001361 spill_slots->push_back(end);
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001362 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001363 (*spill_slots)[slot] = end;
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001364 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001365 }
1366
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001367 // Note that the exact spill slot location will be computed when we resolve,
1368 // that is when we know the number of spill slots for each type.
1369 parent->SetSpillSlot(slot);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001370}
1371
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001372static bool IsValidDestination(Location destination) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001373 return destination.IsRegister()
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001374 || destination.IsRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001375 || destination.IsFpuRegister()
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001376 || destination.IsFpuRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001377 || destination.IsStackSlot()
1378 || destination.IsDoubleStackSlot();
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001379}
1380
David Brazdil77a48ae2015-09-15 12:34:04 +00001381void RegisterAllocator::AllocateSpillSlotForCatchPhi(HPhi* phi) {
1382 LiveInterval* interval = phi->GetLiveInterval();
1383
1384 HInstruction* previous_phi = phi->GetPrevious();
1385 DCHECK(previous_phi == nullptr ||
1386 previous_phi->AsPhi()->GetRegNumber() <= phi->GetRegNumber())
1387 << "Phis expected to be sorted by vreg number, so that equivalent phis are adjacent.";
1388
1389 if (phi->IsVRegEquivalentOf(previous_phi)) {
1390 // This is an equivalent of the previous phi. We need to assign the same
1391 // catch phi slot.
1392 DCHECK(previous_phi->GetLiveInterval()->HasSpillSlot());
1393 interval->SetSpillSlot(previous_phi->GetLiveInterval()->GetSpillSlot());
1394 } else {
1395 // Allocate a new spill slot for this catch phi.
1396 // TODO: Reuse spill slots when intervals of phis from different catch
1397 // blocks do not overlap.
1398 interval->SetSpillSlot(catch_phi_spill_slots_);
1399 catch_phi_spill_slots_ += interval->NeedsTwoSpillSlots() ? 2 : 1;
1400 }
1401}
1402
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001403void RegisterAllocator::AddMove(HParallelMove* move,
1404 Location source,
1405 Location destination,
1406 HInstruction* instruction,
1407 Primitive::Type type) const {
1408 if (type == Primitive::kPrimLong
1409 && codegen_->ShouldSplitLongMoves()
1410 // The parallel move resolver knows how to deal with long constants.
1411 && !source.IsConstant()) {
Nicolas Geoffray90218252015-04-15 11:56:51 +01001412 move->AddMove(source.ToLow(), destination.ToLow(), Primitive::kPrimInt, instruction);
1413 move->AddMove(source.ToHigh(), destination.ToHigh(), Primitive::kPrimInt, nullptr);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001414 } else {
Nicolas Geoffray90218252015-04-15 11:56:51 +01001415 move->AddMove(source, destination, type, instruction);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001416 }
1417}
1418
1419void RegisterAllocator::AddInputMoveFor(HInstruction* input,
1420 HInstruction* user,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001421 Location source,
1422 Location destination) const {
1423 if (source.Equals(destination)) return;
1424
Roland Levillain476df552014-10-09 17:51:36 +01001425 DCHECK(!user->IsPhi());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001426
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001427 HInstruction* previous = user->GetPrevious();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001428 HParallelMove* move = nullptr;
1429 if (previous == nullptr
Roland Levillain476df552014-10-09 17:51:36 +01001430 || !previous->IsParallelMove()
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001431 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001432 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001433 move->SetLifetimePosition(user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001434 user->GetBlock()->InsertInstructionBefore(move, user);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001435 } else {
1436 move = previous->AsParallelMove();
1437 }
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001438 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001439 AddMove(move, source, destination, nullptr, input->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001440}
1441
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001442static bool IsInstructionStart(size_t position) {
1443 return (position & 1) == 0;
1444}
1445
1446static bool IsInstructionEnd(size_t position) {
1447 return (position & 1) == 1;
1448}
1449
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001450void RegisterAllocator::InsertParallelMoveAt(size_t position,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001451 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001452 Location source,
1453 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001454 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001455 if (source.Equals(destination)) return;
1456
1457 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001458 HParallelMove* move;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001459 if (at == nullptr) {
1460 if (IsInstructionStart(position)) {
1461 // Block boundary, don't do anything the connection of split siblings will handle it.
1462 return;
1463 } else {
1464 // Move must happen before the first instruction of the block.
1465 at = liveness_.GetInstructionFromPosition((position + 1) / 2);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001466 // Note that parallel moves may have already been inserted, so we explicitly
1467 // ask for the first instruction of the block: `GetInstructionFromPosition` does
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001468 // not contain the `HParallelMove` instructions.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001469 at = at->GetBlock()->GetFirstInstruction();
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001470
1471 if (at->GetLifetimePosition() < position) {
1472 // We may insert moves for split siblings and phi spills at the beginning of the block.
1473 // Since this is a different lifetime position, we need to go to the next instruction.
1474 DCHECK(at->IsParallelMove());
1475 at = at->GetNext();
1476 }
1477
Nicolas Geoffray59768572014-12-01 09:50:04 +00001478 if (at->GetLifetimePosition() != position) {
1479 DCHECK_GT(at->GetLifetimePosition(), position);
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001480 move = new (allocator_) HParallelMove(allocator_);
1481 move->SetLifetimePosition(position);
1482 at->GetBlock()->InsertInstructionBefore(move, at);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001483 } else {
1484 DCHECK(at->IsParallelMove());
1485 move = at->AsParallelMove();
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001486 }
1487 }
1488 } else if (IsInstructionEnd(position)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001489 // Move must happen after the instruction.
1490 DCHECK(!at->IsControlFlow());
1491 move = at->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001492 // This is a parallel move for connecting siblings in a same block. We need to
1493 // differentiate it with moves for connecting blocks, and input moves.
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001494 if (move == nullptr || move->GetLifetimePosition() > position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001495 move = new (allocator_) HParallelMove(allocator_);
1496 move->SetLifetimePosition(position);
1497 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
1498 }
1499 } else {
1500 // Move must happen before the instruction.
1501 HInstruction* previous = at->GetPrevious();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001502 if (previous == nullptr
1503 || !previous->IsParallelMove()
1504 || previous->GetLifetimePosition() != position) {
1505 // If the previous is a parallel move, then its position must be lower
1506 // than the given `position`: it was added just after the non-parallel
1507 // move instruction that precedes `instruction`.
1508 DCHECK(previous == nullptr
1509 || !previous->IsParallelMove()
1510 || previous->GetLifetimePosition() < position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001511 move = new (allocator_) HParallelMove(allocator_);
1512 move->SetLifetimePosition(position);
1513 at->GetBlock()->InsertInstructionBefore(move, at);
1514 } else {
1515 move = previous->AsParallelMove();
1516 }
1517 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001518 DCHECK_EQ(move->GetLifetimePosition(), position);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001519 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001520}
1521
1522void RegisterAllocator::InsertParallelMoveAtExitOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001523 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001524 Location source,
1525 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001526 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001527 if (source.Equals(destination)) return;
1528
David Brazdild26a4112015-11-10 11:07:31 +00001529 DCHECK_EQ(block->GetNormalSuccessors().size(), 1u);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001530 HInstruction* last = block->GetLastInstruction();
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001531 // We insert moves at exit for phi predecessors and connecting blocks.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001532 // A block ending with an if or a packed switch cannot branch to a block
1533 // with phis because we do not allow critical edges. It can also not connect
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001534 // a split interval between two blocks: the move has to happen in the successor.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001535 DCHECK(!last->IsIf() && !last->IsPackedSwitch());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001536 HInstruction* previous = last->GetPrevious();
1537 HParallelMove* move;
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001538 // This is a parallel move for connecting blocks. We need to differentiate
1539 // it with moves for connecting siblings in a same block, and output moves.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001540 size_t position = last->GetLifetimePosition();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001541 if (previous == nullptr || !previous->IsParallelMove()
Nicolas Geoffray59768572014-12-01 09:50:04 +00001542 || previous->AsParallelMove()->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001543 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001544 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001545 block->InsertInstructionBefore(move, last);
1546 } else {
1547 move = previous->AsParallelMove();
1548 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001549 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001550}
1551
1552void RegisterAllocator::InsertParallelMoveAtEntryOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001553 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001554 Location source,
1555 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001556 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001557 if (source.Equals(destination)) return;
1558
1559 HInstruction* first = block->GetFirstInstruction();
1560 HParallelMove* move = first->AsParallelMove();
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001561 size_t position = block->GetLifetimeStart();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001562 // This is a parallel move for connecting blocks. We need to differentiate
1563 // it with moves for connecting siblings in a same block, and input moves.
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001564 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001565 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001566 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001567 block->InsertInstructionBefore(move, first);
1568 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001569 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001570}
1571
1572void RegisterAllocator::InsertMoveAfter(HInstruction* instruction,
1573 Location source,
1574 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001575 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001576 if (source.Equals(destination)) return;
1577
Roland Levillain476df552014-10-09 17:51:36 +01001578 if (instruction->IsPhi()) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001579 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001580 return;
1581 }
1582
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001583 size_t position = instruction->GetLifetimePosition() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001584 HParallelMove* move = instruction->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001585 // This is a parallel move for moving the output of an instruction. We need
1586 // to differentiate with input moves, moves for connecting siblings in a
1587 // and moves for connecting blocks.
1588 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001589 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001590 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001591 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
1592 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001593 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001594}
1595
1596void RegisterAllocator::ConnectSiblings(LiveInterval* interval) {
1597 LiveInterval* current = interval;
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001598 if (current->HasSpillSlot()
1599 && current->HasRegister()
1600 // Currently, we spill unconditionnally the current method in the code generators.
1601 && !interval->GetDefinedBy()->IsCurrentMethod()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001602 // We spill eagerly, so move must be at definition.
1603 InsertMoveAfter(interval->GetDefinedBy(),
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001604 interval->ToLocation(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001605 interval->NeedsTwoSpillSlots()
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001606 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
1607 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001608 }
1609 UsePosition* use = current->GetFirstUse();
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001610 UsePosition* env_use = current->GetFirstEnvironmentUse();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001611
1612 // Walk over all siblings, updating locations of use positions, and
1613 // connecting them when they are adjacent.
1614 do {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001615 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001616
1617 // Walk over all uses covered by this interval, and update the location
1618 // information.
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001619
1620 LiveRange* range = current->GetFirstRange();
1621 while (range != nullptr) {
Nicolas Geoffray57902602015-04-21 14:28:41 +01001622 while (use != nullptr && use->GetPosition() < range->GetStart()) {
1623 DCHECK(use->IsSynthesized());
1624 use = use->GetNext();
1625 }
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001626 while (use != nullptr && use->GetPosition() <= range->GetEnd()) {
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001627 DCHECK(!use->GetIsEnvironment());
David Brazdil3fc992f2015-04-16 18:31:55 +01001628 DCHECK(current->CoversSlow(use->GetPosition()) || (use->GetPosition() == range->GetEnd()));
Nicolas Geoffray57902602015-04-21 14:28:41 +01001629 if (!use->IsSynthesized()) {
1630 LocationSummary* locations = use->GetUser()->GetLocations();
1631 Location expected_location = locations->InAt(use->GetInputIndex());
1632 // The expected (actual) location may be invalid in case the input is unused. Currently
1633 // this only happens for intrinsics.
1634 if (expected_location.IsValid()) {
1635 if (expected_location.IsUnallocated()) {
1636 locations->SetInAt(use->GetInputIndex(), source);
1637 } else if (!expected_location.IsConstant()) {
1638 AddInputMoveFor(interval->GetDefinedBy(), use->GetUser(), source, expected_location);
1639 }
1640 } else {
1641 DCHECK(use->GetUser()->IsInvoke());
1642 DCHECK(use->GetUser()->AsInvoke()->GetIntrinsic() != Intrinsics::kNone);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001643 }
1644 }
1645 use = use->GetNext();
1646 }
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001647
1648 // Walk over the environment uses, and update their locations.
1649 while (env_use != nullptr && env_use->GetPosition() < range->GetStart()) {
1650 env_use = env_use->GetNext();
1651 }
1652
1653 while (env_use != nullptr && env_use->GetPosition() <= range->GetEnd()) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001654 DCHECK(current->CoversSlow(env_use->GetPosition())
1655 || (env_use->GetPosition() == range->GetEnd()));
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001656 HEnvironment* environment = env_use->GetEnvironment();
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001657 environment->SetLocationAt(env_use->GetInputIndex(), source);
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001658 env_use = env_use->GetNext();
1659 }
1660
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001661 range = range->GetNext();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001662 }
1663
1664 // If the next interval starts just after this one, and has a register,
1665 // insert a move.
1666 LiveInterval* next_sibling = current->GetNextSibling();
1667 if (next_sibling != nullptr
1668 && next_sibling->HasRegister()
1669 && current->GetEnd() == next_sibling->GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001670 Location destination = next_sibling->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001671 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001672 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001673
Nicolas Geoffray43af7282015-04-16 13:01:01 +01001674 for (SafepointPosition* safepoint_position = current->GetFirstSafepoint();
1675 safepoint_position != nullptr;
1676 safepoint_position = safepoint_position->GetNext()) {
David Brazdil3fc992f2015-04-16 18:31:55 +01001677 DCHECK(current->CoversSlow(safepoint_position->GetPosition()));
Nicolas Geoffray39468442014-09-02 15:17:15 +01001678
Nicolas Geoffray5588e582015-04-14 14:10:59 +01001679 LocationSummary* locations = safepoint_position->GetLocations();
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001680 if ((current->GetType() == Primitive::kPrimNot) && current->GetParent()->HasSpillSlot()) {
Nicolas Geoffray1af564e2016-01-13 12:09:39 +00001681 DCHECK(interval->GetDefinedBy()->IsActualObject())
1682 << interval->GetDefinedBy()->DebugName()
1683 << "@" << safepoint_position->GetInstruction()->DebugName();
Nicolas Geoffray39468442014-09-02 15:17:15 +01001684 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
1685 }
1686
1687 switch (source.GetKind()) {
1688 case Location::kRegister: {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001689 locations->AddLiveRegister(source);
Nicolas Geoffray98893962015-01-21 12:32:32 +00001690 if (kIsDebugBuild && locations->OnlyCallsOnSlowPath()) {
1691 DCHECK_LE(locations->GetNumberOfLiveRegisters(),
1692 maximum_number_of_live_core_registers_ +
1693 maximum_number_of_live_fp_registers_);
1694 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001695 if (current->GetType() == Primitive::kPrimNot) {
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00001696 DCHECK(interval->GetDefinedBy()->IsActualObject())
Nicolas Geoffray1af564e2016-01-13 12:09:39 +00001697 << interval->GetDefinedBy()->DebugName()
1698 << "@" << safepoint_position->GetInstruction()->DebugName();
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001699 locations->SetRegisterBit(source.reg());
Nicolas Geoffray39468442014-09-02 15:17:15 +01001700 }
1701 break;
1702 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001703 case Location::kFpuRegister: {
1704 locations->AddLiveRegister(source);
1705 break;
1706 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001707
1708 case Location::kRegisterPair:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001709 case Location::kFpuRegisterPair: {
1710 locations->AddLiveRegister(source.ToLow());
1711 locations->AddLiveRegister(source.ToHigh());
1712 break;
1713 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001714 case Location::kStackSlot: // Fall-through
1715 case Location::kDoubleStackSlot: // Fall-through
1716 case Location::kConstant: {
1717 // Nothing to do.
1718 break;
1719 }
1720 default: {
1721 LOG(FATAL) << "Unexpected location for object";
1722 }
1723 }
1724 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001725 current = next_sibling;
1726 } while (current != nullptr);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001727
Nicolas Geoffray57902602015-04-21 14:28:41 +01001728 if (kIsDebugBuild) {
1729 // Following uses can only be synthesized uses.
1730 while (use != nullptr) {
1731 DCHECK(use->IsSynthesized());
1732 use = use->GetNext();
1733 }
1734 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001735}
1736
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001737static bool IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(
1738 HInstruction* instruction) {
1739 return instruction->GetBlock()->GetGraph()->HasIrreducibleLoops() &&
1740 (instruction->IsConstant() || instruction->IsCurrentMethod());
1741}
1742
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001743void RegisterAllocator::ConnectSplitSiblings(LiveInterval* interval,
1744 HBasicBlock* from,
1745 HBasicBlock* to) const {
1746 if (interval->GetNextSibling() == nullptr) {
1747 // Nothing to connect. The whole range was allocated to the same location.
1748 return;
1749 }
1750
David Brazdil241a4862015-04-16 17:59:03 +01001751 // Find the intervals that cover `from` and `to`.
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001752 size_t destination_position = to->GetLifetimeStart();
1753 size_t source_position = from->GetLifetimeEnd() - 1;
1754 LiveInterval* destination = interval->GetSiblingAt(destination_position);
1755 LiveInterval* source = interval->GetSiblingAt(source_position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001756
1757 if (destination == source) {
1758 // Interval was not split.
1759 return;
1760 }
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001761
1762 LiveInterval* parent = interval->GetParent();
1763 HInstruction* defined_by = parent->GetDefinedBy();
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001764 if (codegen_->GetGraph()->HasIrreducibleLoops() &&
1765 (destination == nullptr || !destination->CoversSlow(destination_position))) {
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001766 // Our live_in fixed point calculation has found that the instruction is live
1767 // in the `to` block because it will eventually enter an irreducible loop. Our
1768 // live interval computation however does not compute a fixed point, and
1769 // therefore will not have a location for that instruction for `to`.
1770 // Because the instruction is a constant or the ArtMethod, we don't need to
1771 // do anything: it will be materialized in the irreducible loop.
1772 DCHECK(IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(defined_by));
1773 return;
1774 }
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +01001775
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001776 if (!destination->HasRegister()) {
1777 // Values are eagerly spilled. Spill slot already contains appropriate value.
1778 return;
1779 }
1780
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001781 Location location_source;
1782 // `GetSiblingAt` returns the interval whose start and end cover `position`,
1783 // but does not check whether the interval is inactive at that position.
1784 // The only situation where the interval is inactive at that position is in the
1785 // presence of irreducible loops for constants and ArtMethod.
1786 if (codegen_->GetGraph()->HasIrreducibleLoops() &&
1787 (source == nullptr || !source->CoversSlow(source_position))) {
1788 DCHECK(IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(defined_by));
1789 if (defined_by->IsConstant()) {
1790 location_source = defined_by->GetLocations()->Out();
1791 } else {
1792 DCHECK(defined_by->IsCurrentMethod());
1793 location_source = parent->NeedsTwoSpillSlots()
1794 ? Location::DoubleStackSlot(parent->GetSpillSlot())
1795 : Location::StackSlot(parent->GetSpillSlot());
1796 }
1797 } else {
1798 DCHECK(source != nullptr);
1799 DCHECK(source->CoversSlow(source_position));
1800 DCHECK(destination->CoversSlow(destination_position));
1801 location_source = source->ToLocation();
1802 }
1803
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001804 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
1805 // we need to put the moves at the entry of `to`.
David Brazdild26a4112015-11-10 11:07:31 +00001806 if (from->GetNormalSuccessors().size() == 1) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001807 InsertParallelMoveAtExitOf(from,
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001808 defined_by,
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001809 location_source,
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001810 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001811 } else {
Vladimir Marko60584552015-09-03 13:35:12 +00001812 DCHECK_EQ(to->GetPredecessors().size(), 1u);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001813 InsertParallelMoveAtEntryOf(to,
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001814 defined_by,
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001815 location_source,
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001816 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001817 }
1818}
1819
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001820void RegisterAllocator::Resolve() {
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001821 codegen_->InitializeCodeGeneration(GetNumberOfSpillSlots(),
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +00001822 maximum_number_of_live_core_registers_,
1823 maximum_number_of_live_fp_registers_,
1824 reserved_out_slots_,
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001825 codegen_->GetGraph()->GetLinearOrder());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001826
1827 // Adjust the Out Location of instructions.
1828 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
1829 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1830 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1831 LiveInterval* current = instruction->GetLiveInterval();
1832 LocationSummary* locations = instruction->GetLocations();
1833 Location location = locations->Out();
Roland Levillain476df552014-10-09 17:51:36 +01001834 if (instruction->IsParameterValue()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001835 // Now that we know the frame size, adjust the parameter's location.
1836 if (location.IsStackSlot()) {
1837 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1838 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001839 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001840 } else if (location.IsDoubleStackSlot()) {
1841 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1842 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001843 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001844 } else if (current->HasSpillSlot()) {
1845 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
1846 }
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001847 } else if (instruction->IsCurrentMethod()) {
1848 // The current method is always at offset 0.
1849 DCHECK(!current->HasSpillSlot() || (current->GetSpillSlot() == 0));
David Brazdil77a48ae2015-09-15 12:34:04 +00001850 } else if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
1851 DCHECK(current->HasSpillSlot());
1852 size_t slot = current->GetSpillSlot()
1853 + GetNumberOfSpillSlots()
1854 + reserved_out_slots_
1855 - catch_phi_spill_slots_;
1856 current->SetSpillSlot(slot * kVRegSize);
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001857 } else if (current->HasSpillSlot()) {
1858 // Adjust the stack slot, now that we know the number of them for each type.
1859 // The way this implementation lays out the stack is the following:
David Brazdil77a48ae2015-09-15 12:34:04 +00001860 // [parameter slots ]
1861 // [catch phi spill slots ]
1862 // [double spill slots ]
1863 // [long spill slots ]
1864 // [float spill slots ]
1865 // [int/ref values ]
1866 // [maximum out values ] (number of arguments for calls)
1867 // [art method ].
1868 size_t slot = current->GetSpillSlot();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001869 switch (current->GetType()) {
1870 case Primitive::kPrimDouble:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001871 slot += long_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001872 FALLTHROUGH_INTENDED;
1873 case Primitive::kPrimLong:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001874 slot += float_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001875 FALLTHROUGH_INTENDED;
1876 case Primitive::kPrimFloat:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001877 slot += int_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001878 FALLTHROUGH_INTENDED;
1879 case Primitive::kPrimNot:
1880 case Primitive::kPrimInt:
1881 case Primitive::kPrimChar:
1882 case Primitive::kPrimByte:
1883 case Primitive::kPrimBoolean:
1884 case Primitive::kPrimShort:
1885 slot += reserved_out_slots_;
1886 break;
1887 case Primitive::kPrimVoid:
1888 LOG(FATAL) << "Unexpected type for interval " << current->GetType();
1889 }
1890 current->SetSpillSlot(slot * kVRegSize);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001891 }
1892
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001893 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001894
1895 if (location.IsUnallocated()) {
1896 if (location.GetPolicy() == Location::kSameAsFirstInput) {
Calin Juravled0d48522014-11-04 16:40:20 +00001897 if (locations->InAt(0).IsUnallocated()) {
1898 locations->SetInAt(0, source);
1899 } else {
1900 DCHECK(locations->InAt(0).Equals(source));
1901 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001902 }
Nicolas Geoffray829280c2015-01-28 10:20:37 +00001903 locations->UpdateOut(source);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001904 } else {
1905 DCHECK(source.Equals(location));
1906 }
1907 }
1908
1909 // Connect siblings.
1910 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1911 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1912 ConnectSiblings(instruction->GetLiveInterval());
1913 }
1914
1915 // Resolve non-linear control flow across branches. Order does not matter.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001916 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001917 HBasicBlock* block = it.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001918 if (block->IsCatchBlock() ||
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001919 (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001920 // Instructions live at the top of catch blocks or irreducible loop header
1921 // were forced to spill.
David Brazdil77a48ae2015-09-15 12:34:04 +00001922 if (kIsDebugBuild) {
1923 BitVector* live = liveness_.GetLiveInSet(*block);
1924 for (uint32_t idx : live->Indexes()) {
1925 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
1926 DCHECK(!interval->GetSiblingAt(block->GetLifetimeStart())->HasRegister());
1927 }
1928 }
1929 } else {
1930 BitVector* live = liveness_.GetLiveInSet(*block);
1931 for (uint32_t idx : live->Indexes()) {
1932 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
1933 for (HBasicBlock* predecessor : block->GetPredecessors()) {
1934 ConnectSplitSiblings(interval, predecessor, block);
1935 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001936 }
1937 }
1938 }
1939
1940 // Resolve phi inputs. Order does not matter.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001941 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001942 HBasicBlock* current = it.Current();
David Brazdil77a48ae2015-09-15 12:34:04 +00001943 if (current->IsCatchBlock()) {
1944 // Catch phi values are set at runtime by the exception delivery mechanism.
1945 } else {
1946 for (HInstructionIterator inst_it(current->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
1947 HInstruction* phi = inst_it.Current();
1948 for (size_t i = 0, e = current->GetPredecessors().size(); i < e; ++i) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001949 HBasicBlock* predecessor = current->GetPredecessors()[i];
David Brazdild26a4112015-11-10 11:07:31 +00001950 DCHECK_EQ(predecessor->GetNormalSuccessors().size(), 1u);
David Brazdil77a48ae2015-09-15 12:34:04 +00001951 HInstruction* input = phi->InputAt(i);
1952 Location source = input->GetLiveInterval()->GetLocationAt(
1953 predecessor->GetLifetimeEnd() - 1);
1954 Location destination = phi->GetLiveInterval()->ToLocation();
1955 InsertParallelMoveAtExitOf(predecessor, phi, source, destination);
1956 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001957 }
1958 }
1959 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001960
1961 // Assign temp locations.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001962 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001963 if (temp->IsHighInterval()) {
1964 // High intervals can be skipped, they are already handled by the low interval.
1965 continue;
1966 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001967 HInstruction* at = liveness_.GetTempUser(temp);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001968 size_t temp_index = liveness_.GetTempIndex(temp);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001969 LocationSummary* locations = at->GetLocations();
Roland Levillain5368c212014-11-27 15:03:41 +00001970 switch (temp->GetType()) {
1971 case Primitive::kPrimInt:
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001972 locations->SetTempAt(temp_index, Location::RegisterLocation(temp->GetRegister()));
Roland Levillain5368c212014-11-27 15:03:41 +00001973 break;
1974
1975 case Primitive::kPrimDouble:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001976 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
1977 Location location = Location::FpuRegisterPairLocation(
1978 temp->GetRegister(), temp->GetHighInterval()->GetRegister());
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001979 locations->SetTempAt(temp_index, location);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001980 } else {
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001981 locations->SetTempAt(temp_index, Location::FpuRegisterLocation(temp->GetRegister()));
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001982 }
Roland Levillain5368c212014-11-27 15:03:41 +00001983 break;
1984
1985 default:
1986 LOG(FATAL) << "Unexpected type for temporary location "
1987 << temp->GetType();
1988 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001989 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001990}
1991
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001992} // namespace art