blob: 59523a93a0cb6c2ebbd7da1ce21d54d499740dae [file] [log] [blame]
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -07001/*
2 * Copyright (C) 2016 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_allocation_resolver.h"
18
19#include "code_generator.h"
Aart Bik96202302016-10-04 17:33:56 -070020#include "linear_order.h"
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070021#include "ssa_liveness_analysis.h"
22
23namespace art {
24
25RegisterAllocationResolver::RegisterAllocationResolver(ArenaAllocator* allocator,
26 CodeGenerator* codegen,
27 const SsaLivenessAnalysis& liveness)
28 : allocator_(allocator),
29 codegen_(codegen),
30 liveness_(liveness) {}
31
Vladimir Marko70e97462016-08-09 11:04:26 +010032void RegisterAllocationResolver::Resolve(ArrayRef<HInstruction* const> safepoints,
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070033 size_t reserved_out_slots,
34 size_t int_spill_slots,
35 size_t long_spill_slots,
36 size_t float_spill_slots,
37 size_t double_spill_slots,
38 size_t catch_phi_spill_slots,
Matthew Gharrity0b110f42016-07-20 10:13:45 -070039 const ArenaVector<LiveInterval*>& temp_intervals) {
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070040 size_t spill_slots = int_spill_slots
41 + long_spill_slots
42 + float_spill_slots
43 + double_spill_slots
44 + catch_phi_spill_slots;
45
Vladimir Marko70e97462016-08-09 11:04:26 +010046 // Update safepoints and calculate the size of the spills.
47 UpdateSafepointLiveRegisters();
48 size_t maximum_safepoint_spill_size = CalculateMaximumSafepointSpillSize(safepoints);
49
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070050 // Computes frame size and spill mask.
51 codegen_->InitializeCodeGeneration(spill_slots,
Vladimir Marko70e97462016-08-09 11:04:26 +010052 maximum_safepoint_spill_size,
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070053 reserved_out_slots, // Includes slot(s) for the art method.
54 codegen_->GetGraph()->GetLinearOrder());
55
56 // Resolve outputs, including stack locations.
57 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
58 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
59 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
60 LiveInterval* current = instruction->GetLiveInterval();
61 LocationSummary* locations = instruction->GetLocations();
62 Location location = locations->Out();
63 if (instruction->IsParameterValue()) {
64 // Now that we know the frame size, adjust the parameter's location.
65 if (location.IsStackSlot()) {
66 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
67 current->SetSpillSlot(location.GetStackIndex());
68 locations->UpdateOut(location);
69 } else if (location.IsDoubleStackSlot()) {
70 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
71 current->SetSpillSlot(location.GetStackIndex());
72 locations->UpdateOut(location);
73 } else if (current->HasSpillSlot()) {
74 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
75 }
76 } else if (instruction->IsCurrentMethod()) {
77 // The current method is always at offset 0.
78 DCHECK(!current->HasSpillSlot() || (current->GetSpillSlot() == 0));
79 } else if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
80 DCHECK(current->HasSpillSlot());
81 size_t slot = current->GetSpillSlot()
82 + spill_slots
83 + reserved_out_slots
84 - catch_phi_spill_slots;
85 current->SetSpillSlot(slot * kVRegSize);
86 } else if (current->HasSpillSlot()) {
87 // Adjust the stack slot, now that we know the number of them for each type.
88 // The way this implementation lays out the stack is the following:
89 // [parameter slots ]
Mingyao Yang063fc772016-08-02 11:02:54 -070090 // [art method (caller) ]
91 // [entry spill (core) ]
92 // [entry spill (float) ]
93 // [should_deoptimize flag] (this is optional)
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -070094 // [catch phi spill slots ]
95 // [double spill slots ]
96 // [long spill slots ]
97 // [float spill slots ]
98 // [int/ref values ]
99 // [maximum out values ] (number of arguments for calls)
100 // [art method ].
101 size_t slot = current->GetSpillSlot();
102 switch (current->GetType()) {
103 case Primitive::kPrimDouble:
104 slot += long_spill_slots;
105 FALLTHROUGH_INTENDED;
106 case Primitive::kPrimLong:
107 slot += float_spill_slots;
108 FALLTHROUGH_INTENDED;
109 case Primitive::kPrimFloat:
110 slot += int_spill_slots;
111 FALLTHROUGH_INTENDED;
112 case Primitive::kPrimNot:
113 case Primitive::kPrimInt:
114 case Primitive::kPrimChar:
115 case Primitive::kPrimByte:
116 case Primitive::kPrimBoolean:
117 case Primitive::kPrimShort:
118 slot += reserved_out_slots;
119 break;
120 case Primitive::kPrimVoid:
121 LOG(FATAL) << "Unexpected type for interval " << current->GetType();
122 }
123 current->SetSpillSlot(slot * kVRegSize);
124 }
125
126 Location source = current->ToLocation();
127
128 if (location.IsUnallocated()) {
129 if (location.GetPolicy() == Location::kSameAsFirstInput) {
130 if (locations->InAt(0).IsUnallocated()) {
131 locations->SetInAt(0, source);
132 } else {
133 DCHECK(locations->InAt(0).Equals(source));
134 }
135 }
136 locations->UpdateOut(source);
137 } else {
138 DCHECK(source.Equals(location));
139 }
140 }
141
142 // Connect siblings and resolve inputs.
143 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
144 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
Vladimir Marko70e97462016-08-09 11:04:26 +0100145 ConnectSiblings(instruction->GetLiveInterval());
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700146 }
147
148 // Resolve non-linear control flow across branches. Order does not matter.
Aart Bik96202302016-10-04 17:33:56 -0700149 for (HBasicBlock* block : codegen_->GetGraph()->GetLinearOrder()) {
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700150 if (block->IsCatchBlock() ||
151 (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible())) {
152 // Instructions live at the top of catch blocks or irreducible loop header
153 // were forced to spill.
154 if (kIsDebugBuild) {
155 BitVector* live = liveness_.GetLiveInSet(*block);
156 for (uint32_t idx : live->Indexes()) {
157 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
158 LiveInterval* sibling = interval->GetSiblingAt(block->GetLifetimeStart());
159 // `GetSiblingAt` returns the sibling that contains a position, but there could be
160 // a lifetime hole in it. `CoversSlow` returns whether the interval is live at that
161 // position.
162 if ((sibling != nullptr) && sibling->CoversSlow(block->GetLifetimeStart())) {
163 DCHECK(!sibling->HasRegister());
164 }
165 }
166 }
167 } else {
168 BitVector* live = liveness_.GetLiveInSet(*block);
169 for (uint32_t idx : live->Indexes()) {
170 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
171 for (HBasicBlock* predecessor : block->GetPredecessors()) {
172 ConnectSplitSiblings(interval, predecessor, block);
173 }
174 }
175 }
176 }
177
178 // Resolve phi inputs. Order does not matter.
Aart Bik96202302016-10-04 17:33:56 -0700179 for (HBasicBlock* block : codegen_->GetGraph()->GetLinearOrder()) {
180 if (block->IsCatchBlock()) {
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700181 // Catch phi values are set at runtime by the exception delivery mechanism.
182 } else {
Aart Bik96202302016-10-04 17:33:56 -0700183 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700184 HInstruction* phi = inst_it.Current();
Aart Bik96202302016-10-04 17:33:56 -0700185 for (size_t i = 0, e = block->GetPredecessors().size(); i < e; ++i) {
186 HBasicBlock* predecessor = block->GetPredecessors()[i];
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700187 DCHECK_EQ(predecessor->GetNormalSuccessors().size(), 1u);
188 HInstruction* input = phi->InputAt(i);
189 Location source = input->GetLiveInterval()->GetLocationAt(
190 predecessor->GetLifetimeEnd() - 1);
191 Location destination = phi->GetLiveInterval()->ToLocation();
192 InsertParallelMoveAtExitOf(predecessor, phi, source, destination);
193 }
194 }
195 }
196 }
197
198 // Resolve temp locations.
199 for (LiveInterval* temp : temp_intervals) {
200 if (temp->IsHighInterval()) {
201 // High intervals can be skipped, they are already handled by the low interval.
202 continue;
203 }
204 HInstruction* at = liveness_.GetTempUser(temp);
205 size_t temp_index = liveness_.GetTempIndex(temp);
206 LocationSummary* locations = at->GetLocations();
207 switch (temp->GetType()) {
208 case Primitive::kPrimInt:
209 locations->SetTempAt(temp_index, Location::RegisterLocation(temp->GetRegister()));
210 break;
211
212 case Primitive::kPrimDouble:
213 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
214 Location location = Location::FpuRegisterPairLocation(
215 temp->GetRegister(), temp->GetHighInterval()->GetRegister());
216 locations->SetTempAt(temp_index, location);
217 } else {
218 locations->SetTempAt(temp_index, Location::FpuRegisterLocation(temp->GetRegister()));
219 }
220 break;
221
222 default:
223 LOG(FATAL) << "Unexpected type for temporary location "
224 << temp->GetType();
225 }
226 }
227}
228
Vladimir Marko70e97462016-08-09 11:04:26 +0100229void RegisterAllocationResolver::UpdateSafepointLiveRegisters() {
230 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
231 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
232 for (LiveInterval* current = instruction->GetLiveInterval();
233 current != nullptr;
234 current = current->GetNextSibling()) {
235 if (!current->HasRegister()) {
236 continue;
237 }
238 Location source = current->ToLocation();
239 for (SafepointPosition* safepoint_position = current->GetFirstSafepoint();
240 safepoint_position != nullptr;
241 safepoint_position = safepoint_position->GetNext()) {
242 DCHECK(current->CoversSlow(safepoint_position->GetPosition()));
243 LocationSummary* locations = safepoint_position->GetLocations();
244 switch (source.GetKind()) {
245 case Location::kRegister:
246 case Location::kFpuRegister: {
247 locations->AddLiveRegister(source);
248 break;
249 }
250 case Location::kRegisterPair:
251 case Location::kFpuRegisterPair: {
252 locations->AddLiveRegister(source.ToLow());
253 locations->AddLiveRegister(source.ToHigh());
254 break;
255 }
256 case Location::kStackSlot: // Fall-through
257 case Location::kDoubleStackSlot: // Fall-through
258 case Location::kConstant: {
259 // Nothing to do.
260 break;
261 }
262 default: {
263 LOG(FATAL) << "Unexpected location for object";
264 }
265 }
266 }
267 }
268 }
269}
270
271size_t RegisterAllocationResolver::CalculateMaximumSafepointSpillSize(
272 ArrayRef<HInstruction* const> safepoints) {
273 size_t core_register_spill_size = codegen_->GetWordSize();
274 size_t fp_register_spill_size = codegen_->GetFloatingPointSpillSlotSize();
275 size_t maximum_safepoint_spill_size = 0u;
276 for (HInstruction* instruction : safepoints) {
277 LocationSummary* locations = instruction->GetLocations();
278 if (locations->OnlyCallsOnSlowPath()) {
279 size_t core_spills =
280 codegen_->GetNumberOfSlowPathSpills(locations, /* core_registers */ true);
281 size_t fp_spills =
282 codegen_->GetNumberOfSlowPathSpills(locations, /* core_registers */ false);
283 size_t spill_size =
284 core_register_spill_size * core_spills + fp_register_spill_size * fp_spills;
285 maximum_safepoint_spill_size = std::max(maximum_safepoint_spill_size, spill_size);
286 } else if (locations->CallsOnMainAndSlowPath()) {
287 // Nothing to spill on the slow path if the main path already clobbers caller-saves.
288 DCHECK_EQ(0u, codegen_->GetNumberOfSlowPathSpills(locations, /* core_registers */ true));
289 DCHECK_EQ(0u, codegen_->GetNumberOfSlowPathSpills(locations, /* core_registers */ false));
290 }
291 }
292 return maximum_safepoint_spill_size;
293}
294
295void RegisterAllocationResolver::ConnectSiblings(LiveInterval* interval) {
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700296 LiveInterval* current = interval;
297 if (current->HasSpillSlot()
298 && current->HasRegister()
299 // Currently, we spill unconditionnally the current method in the code generators.
300 && !interval->GetDefinedBy()->IsCurrentMethod()) {
301 // We spill eagerly, so move must be at definition.
302 InsertMoveAfter(interval->GetDefinedBy(),
303 interval->ToLocation(),
304 interval->NeedsTwoSpillSlots()
305 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
306 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
307 }
308 UsePosition* use = current->GetFirstUse();
309 UsePosition* env_use = current->GetFirstEnvironmentUse();
310
311 // Walk over all siblings, updating locations of use positions, and
312 // connecting them when they are adjacent.
313 do {
314 Location source = current->ToLocation();
315
316 // Walk over all uses covered by this interval, and update the location
317 // information.
318
319 LiveRange* range = current->GetFirstRange();
320 while (range != nullptr) {
321 while (use != nullptr && use->GetPosition() < range->GetStart()) {
322 DCHECK(use->IsSynthesized());
323 use = use->GetNext();
324 }
325 while (use != nullptr && use->GetPosition() <= range->GetEnd()) {
326 DCHECK(!use->GetIsEnvironment());
327 DCHECK(current->CoversSlow(use->GetPosition()) || (use->GetPosition() == range->GetEnd()));
328 if (!use->IsSynthesized()) {
329 LocationSummary* locations = use->GetUser()->GetLocations();
330 Location expected_location = locations->InAt(use->GetInputIndex());
331 // The expected (actual) location may be invalid in case the input is unused. Currently
332 // this only happens for intrinsics.
333 if (expected_location.IsValid()) {
334 if (expected_location.IsUnallocated()) {
335 locations->SetInAt(use->GetInputIndex(), source);
336 } else if (!expected_location.IsConstant()) {
337 AddInputMoveFor(interval->GetDefinedBy(), use->GetUser(), source, expected_location);
338 }
339 } else {
340 DCHECK(use->GetUser()->IsInvoke());
341 DCHECK(use->GetUser()->AsInvoke()->GetIntrinsic() != Intrinsics::kNone);
342 }
343 }
344 use = use->GetNext();
345 }
346
347 // Walk over the environment uses, and update their locations.
348 while (env_use != nullptr && env_use->GetPosition() < range->GetStart()) {
349 env_use = env_use->GetNext();
350 }
351
352 while (env_use != nullptr && env_use->GetPosition() <= range->GetEnd()) {
353 DCHECK(current->CoversSlow(env_use->GetPosition())
354 || (env_use->GetPosition() == range->GetEnd()));
355 HEnvironment* environment = env_use->GetEnvironment();
356 environment->SetLocationAt(env_use->GetInputIndex(), source);
357 env_use = env_use->GetNext();
358 }
359
360 range = range->GetNext();
361 }
362
363 // If the next interval starts just after this one, and has a register,
364 // insert a move.
365 LiveInterval* next_sibling = current->GetNextSibling();
366 if (next_sibling != nullptr
367 && next_sibling->HasRegister()
368 && current->GetEnd() == next_sibling->GetStart()) {
369 Location destination = next_sibling->ToLocation();
370 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
371 }
372
373 for (SafepointPosition* safepoint_position = current->GetFirstSafepoint();
374 safepoint_position != nullptr;
375 safepoint_position = safepoint_position->GetNext()) {
376 DCHECK(current->CoversSlow(safepoint_position->GetPosition()));
377
Vladimir Marko70e97462016-08-09 11:04:26 +0100378 if (current->GetType() == Primitive::kPrimNot) {
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700379 DCHECK(interval->GetDefinedBy()->IsActualObject())
380 << interval->GetDefinedBy()->DebugName()
Roland Levillain19c54192016-11-04 13:44:09 +0000381 << '(' << interval->GetDefinedBy()->GetId() << ')'
382 << "@" << safepoint_position->GetInstruction()->DebugName()
383 << '(' << safepoint_position->GetInstruction()->GetId() << ')';
Vladimir Marko70e97462016-08-09 11:04:26 +0100384 LocationSummary* locations = safepoint_position->GetLocations();
385 if (current->GetParent()->HasSpillSlot()) {
386 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700387 }
Vladimir Marko70e97462016-08-09 11:04:26 +0100388 if (source.GetKind() == Location::kRegister) {
389 locations->SetRegisterBit(source.reg());
Matthew Gharrity5d6e27d2016-07-18 13:38:44 -0700390 }
391 }
392 }
393 current = next_sibling;
394 } while (current != nullptr);
395
396 if (kIsDebugBuild) {
397 // Following uses can only be synthesized uses.
398 while (use != nullptr) {
399 DCHECK(use->IsSynthesized());
400 use = use->GetNext();
401 }
402 }
403}
404
405static bool IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(
406 HInstruction* instruction) {
407 return instruction->GetBlock()->GetGraph()->HasIrreducibleLoops() &&
408 (instruction->IsConstant() || instruction->IsCurrentMethod());
409}
410
411void RegisterAllocationResolver::ConnectSplitSiblings(LiveInterval* interval,
412 HBasicBlock* from,
413 HBasicBlock* to) const {
414 if (interval->GetNextSibling() == nullptr) {
415 // Nothing to connect. The whole range was allocated to the same location.
416 return;
417 }
418
419 // Find the intervals that cover `from` and `to`.
420 size_t destination_position = to->GetLifetimeStart();
421 size_t source_position = from->GetLifetimeEnd() - 1;
422 LiveInterval* destination = interval->GetSiblingAt(destination_position);
423 LiveInterval* source = interval->GetSiblingAt(source_position);
424
425 if (destination == source) {
426 // Interval was not split.
427 return;
428 }
429
430 LiveInterval* parent = interval->GetParent();
431 HInstruction* defined_by = parent->GetDefinedBy();
432 if (codegen_->GetGraph()->HasIrreducibleLoops() &&
433 (destination == nullptr || !destination->CoversSlow(destination_position))) {
434 // Our live_in fixed point calculation has found that the instruction is live
435 // in the `to` block because it will eventually enter an irreducible loop. Our
436 // live interval computation however does not compute a fixed point, and
437 // therefore will not have a location for that instruction for `to`.
438 // Because the instruction is a constant or the ArtMethod, we don't need to
439 // do anything: it will be materialized in the irreducible loop.
440 DCHECK(IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(defined_by))
441 << defined_by->DebugName() << ":" << defined_by->GetId()
442 << " " << from->GetBlockId() << " -> " << to->GetBlockId();
443 return;
444 }
445
446 if (!destination->HasRegister()) {
447 // Values are eagerly spilled. Spill slot already contains appropriate value.
448 return;
449 }
450
451 Location location_source;
452 // `GetSiblingAt` returns the interval whose start and end cover `position`,
453 // but does not check whether the interval is inactive at that position.
454 // The only situation where the interval is inactive at that position is in the
455 // presence of irreducible loops for constants and ArtMethod.
456 if (codegen_->GetGraph()->HasIrreducibleLoops() &&
457 (source == nullptr || !source->CoversSlow(source_position))) {
458 DCHECK(IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(defined_by));
459 if (defined_by->IsConstant()) {
460 location_source = defined_by->GetLocations()->Out();
461 } else {
462 DCHECK(defined_by->IsCurrentMethod());
463 location_source = parent->NeedsTwoSpillSlots()
464 ? Location::DoubleStackSlot(parent->GetSpillSlot())
465 : Location::StackSlot(parent->GetSpillSlot());
466 }
467 } else {
468 DCHECK(source != nullptr);
469 DCHECK(source->CoversSlow(source_position));
470 DCHECK(destination->CoversSlow(destination_position));
471 location_source = source->ToLocation();
472 }
473
474 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
475 // we need to put the moves at the entry of `to`.
476 if (from->GetNormalSuccessors().size() == 1) {
477 InsertParallelMoveAtExitOf(from,
478 defined_by,
479 location_source,
480 destination->ToLocation());
481 } else {
482 DCHECK_EQ(to->GetPredecessors().size(), 1u);
483 InsertParallelMoveAtEntryOf(to,
484 defined_by,
485 location_source,
486 destination->ToLocation());
487 }
488}
489
490static bool IsValidDestination(Location destination) {
491 return destination.IsRegister()
492 || destination.IsRegisterPair()
493 || destination.IsFpuRegister()
494 || destination.IsFpuRegisterPair()
495 || destination.IsStackSlot()
496 || destination.IsDoubleStackSlot();
497}
498
499void RegisterAllocationResolver::AddMove(HParallelMove* move,
500 Location source,
501 Location destination,
502 HInstruction* instruction,
503 Primitive::Type type) const {
504 if (type == Primitive::kPrimLong
505 && codegen_->ShouldSplitLongMoves()
506 // The parallel move resolver knows how to deal with long constants.
507 && !source.IsConstant()) {
508 move->AddMove(source.ToLow(), destination.ToLow(), Primitive::kPrimInt, instruction);
509 move->AddMove(source.ToHigh(), destination.ToHigh(), Primitive::kPrimInt, nullptr);
510 } else {
511 move->AddMove(source, destination, type, instruction);
512 }
513}
514
515void RegisterAllocationResolver::AddInputMoveFor(HInstruction* input,
516 HInstruction* user,
517 Location source,
518 Location destination) const {
519 if (source.Equals(destination)) return;
520
521 DCHECK(!user->IsPhi());
522
523 HInstruction* previous = user->GetPrevious();
524 HParallelMove* move = nullptr;
525 if (previous == nullptr
526 || !previous->IsParallelMove()
527 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
528 move = new (allocator_) HParallelMove(allocator_);
529 move->SetLifetimePosition(user->GetLifetimePosition());
530 user->GetBlock()->InsertInstructionBefore(move, user);
531 } else {
532 move = previous->AsParallelMove();
533 }
534 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
535 AddMove(move, source, destination, nullptr, input->GetType());
536}
537
538static bool IsInstructionStart(size_t position) {
539 return (position & 1) == 0;
540}
541
542static bool IsInstructionEnd(size_t position) {
543 return (position & 1) == 1;
544}
545
546void RegisterAllocationResolver::InsertParallelMoveAt(size_t position,
547 HInstruction* instruction,
548 Location source,
549 Location destination) const {
550 DCHECK(IsValidDestination(destination)) << destination;
551 if (source.Equals(destination)) return;
552
553 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
554 HParallelMove* move;
555 if (at == nullptr) {
556 if (IsInstructionStart(position)) {
557 // Block boundary, don't do anything the connection of split siblings will handle it.
558 return;
559 } else {
560 // Move must happen before the first instruction of the block.
561 at = liveness_.GetInstructionFromPosition((position + 1) / 2);
562 // Note that parallel moves may have already been inserted, so we explicitly
563 // ask for the first instruction of the block: `GetInstructionFromPosition` does
564 // not contain the `HParallelMove` instructions.
565 at = at->GetBlock()->GetFirstInstruction();
566
567 if (at->GetLifetimePosition() < position) {
568 // We may insert moves for split siblings and phi spills at the beginning of the block.
569 // Since this is a different lifetime position, we need to go to the next instruction.
570 DCHECK(at->IsParallelMove());
571 at = at->GetNext();
572 }
573
574 if (at->GetLifetimePosition() != position) {
575 DCHECK_GT(at->GetLifetimePosition(), position);
576 move = new (allocator_) HParallelMove(allocator_);
577 move->SetLifetimePosition(position);
578 at->GetBlock()->InsertInstructionBefore(move, at);
579 } else {
580 DCHECK(at->IsParallelMove());
581 move = at->AsParallelMove();
582 }
583 }
584 } else if (IsInstructionEnd(position)) {
585 // Move must happen after the instruction.
586 DCHECK(!at->IsControlFlow());
587 move = at->GetNext()->AsParallelMove();
588 // This is a parallel move for connecting siblings in a same block. We need to
589 // differentiate it with moves for connecting blocks, and input moves.
590 if (move == nullptr || move->GetLifetimePosition() > position) {
591 move = new (allocator_) HParallelMove(allocator_);
592 move->SetLifetimePosition(position);
593 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
594 }
595 } else {
596 // Move must happen before the instruction.
597 HInstruction* previous = at->GetPrevious();
598 if (previous == nullptr
599 || !previous->IsParallelMove()
600 || previous->GetLifetimePosition() != position) {
601 // If the previous is a parallel move, then its position must be lower
602 // than the given `position`: it was added just after the non-parallel
603 // move instruction that precedes `instruction`.
604 DCHECK(previous == nullptr
605 || !previous->IsParallelMove()
606 || previous->GetLifetimePosition() < position);
607 move = new (allocator_) HParallelMove(allocator_);
608 move->SetLifetimePosition(position);
609 at->GetBlock()->InsertInstructionBefore(move, at);
610 } else {
611 move = previous->AsParallelMove();
612 }
613 }
614 DCHECK_EQ(move->GetLifetimePosition(), position);
615 AddMove(move, source, destination, instruction, instruction->GetType());
616}
617
618void RegisterAllocationResolver::InsertParallelMoveAtExitOf(HBasicBlock* block,
619 HInstruction* instruction,
620 Location source,
621 Location destination) const {
622 DCHECK(IsValidDestination(destination)) << destination;
623 if (source.Equals(destination)) return;
624
625 DCHECK_EQ(block->GetNormalSuccessors().size(), 1u);
626 HInstruction* last = block->GetLastInstruction();
627 // We insert moves at exit for phi predecessors and connecting blocks.
628 // A block ending with an if or a packed switch cannot branch to a block
629 // with phis because we do not allow critical edges. It can also not connect
630 // a split interval between two blocks: the move has to happen in the successor.
631 DCHECK(!last->IsIf() && !last->IsPackedSwitch());
632 HInstruction* previous = last->GetPrevious();
633 HParallelMove* move;
634 // This is a parallel move for connecting blocks. We need to differentiate
635 // it with moves for connecting siblings in a same block, and output moves.
636 size_t position = last->GetLifetimePosition();
637 if (previous == nullptr || !previous->IsParallelMove()
638 || previous->AsParallelMove()->GetLifetimePosition() != position) {
639 move = new (allocator_) HParallelMove(allocator_);
640 move->SetLifetimePosition(position);
641 block->InsertInstructionBefore(move, last);
642 } else {
643 move = previous->AsParallelMove();
644 }
645 AddMove(move, source, destination, instruction, instruction->GetType());
646}
647
648void RegisterAllocationResolver::InsertParallelMoveAtEntryOf(HBasicBlock* block,
649 HInstruction* instruction,
650 Location source,
651 Location destination) const {
652 DCHECK(IsValidDestination(destination)) << destination;
653 if (source.Equals(destination)) return;
654
655 HInstruction* first = block->GetFirstInstruction();
656 HParallelMove* move = first->AsParallelMove();
657 size_t position = block->GetLifetimeStart();
658 // This is a parallel move for connecting blocks. We need to differentiate
659 // it with moves for connecting siblings in a same block, and input moves.
660 if (move == nullptr || move->GetLifetimePosition() != position) {
661 move = new (allocator_) HParallelMove(allocator_);
662 move->SetLifetimePosition(position);
663 block->InsertInstructionBefore(move, first);
664 }
665 AddMove(move, source, destination, instruction, instruction->GetType());
666}
667
668void RegisterAllocationResolver::InsertMoveAfter(HInstruction* instruction,
669 Location source,
670 Location destination) const {
671 DCHECK(IsValidDestination(destination)) << destination;
672 if (source.Equals(destination)) return;
673
674 if (instruction->IsPhi()) {
675 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
676 return;
677 }
678
679 size_t position = instruction->GetLifetimePosition() + 1;
680 HParallelMove* move = instruction->GetNext()->AsParallelMove();
681 // This is a parallel move for moving the output of an instruction. We need
682 // to differentiate with input moves, moves for connecting siblings in a
683 // and moves for connecting blocks.
684 if (move == nullptr || move->GetLifetimePosition() != position) {
685 move = new (allocator_) HParallelMove(allocator_);
686 move->SetLifetimePosition(position);
687 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
688 }
689 AddMove(move, source, destination, instruction, instruction->GetType());
690}
691
692} // namespace art