blob: a4d52d7761f9e0ea02e2ed88d5a81459fdfef8c5 [file] [log] [blame]
Nicolas Geoffray804d0932014-05-02 08:46:00 +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 "ssa_liveness_analysis.h"
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010018
Ian Rogerse77493c2014-08-20 15:08:45 -070019#include "base/bit_vector-inl.h"
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010020#include "code_generator.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010021#include "nodes.h"
22
23namespace art {
24
25void SsaLivenessAnalysis::Analyze() {
Nicolas Geoffray0d3f5782014-05-14 09:43:38 +010026 LinearizeGraph();
Nicolas Geoffray804d0932014-05-02 08:46:00 +010027 NumberInstructions();
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +010028 ComputeLiveness();
Nicolas Geoffray804d0932014-05-02 08:46:00 +010029}
30
Nicolas Geoffray0d3f5782014-05-14 09:43:38 +010031static bool IsLoop(HLoopInformation* info) {
32 return info != nullptr;
33}
34
35static bool InSameLoop(HLoopInformation* first_loop, HLoopInformation* second_loop) {
36 return first_loop == second_loop;
37}
38
39static bool IsInnerLoop(HLoopInformation* outer, HLoopInformation* inner) {
40 return (inner != outer)
41 && (inner != nullptr)
42 && (outer != nullptr)
43 && inner->IsIn(*outer);
44}
45
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010046static void AddToListForLinearization(ArenaVector<HBasicBlock*>* worklist, HBasicBlock* block) {
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +000047 HLoopInformation* block_loop = block->GetLoopInformation();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010048 auto insert_pos = worklist->rbegin(); // insert_pos.base() will be the actual position.
49 for (auto end = worklist->rend(); insert_pos != end; ++insert_pos) {
50 HBasicBlock* current = *insert_pos;
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +000051 HLoopInformation* current_loop = current->GetLoopInformation();
52 if (InSameLoop(block_loop, current_loop)
53 || !IsLoop(current_loop)
54 || IsInnerLoop(current_loop, block_loop)) {
55 // The block can be processed immediately.
56 break;
Nicolas Geoffraye50fa582014-11-24 17:44:15 +000057 }
Nicolas Geoffraye50fa582014-11-24 17:44:15 +000058 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010059 worklist->insert(insert_pos.base(), block);
Nicolas Geoffray0d3f5782014-05-14 09:43:38 +010060}
61
David Brazdil30f76662016-09-02 11:42:48 +010062static bool IsLinearOrderWellFormed(const HGraph& graph) {
63 for (HBasicBlock* header : graph.GetBlocks()) {
64 if (header == nullptr || !header->IsLoopHeader()) {
65 continue;
66 }
67
68 HLoopInformation* loop = header->GetLoopInformation();
69 size_t num_blocks = loop->GetBlocks().NumSetBits();
70 size_t found_blocks = 0u;
71
72 for (HLinearOrderIterator it(graph); !it.Done(); it.Advance()) {
73 HBasicBlock* current = it.Current();
74 if (loop->Contains(*current)) {
75 found_blocks++;
76 if (found_blocks == 1u && current != header) {
77 // First block is not the header.
78 return false;
79 } else if (found_blocks == num_blocks && !loop->IsBackEdge(*current)) {
80 // Last block is not a back edge.
81 return false;
82 }
83 } else if (found_blocks != 0u && found_blocks != num_blocks) {
84 // Blocks are not adjacent.
85 return false;
86 }
87 }
88 DCHECK_EQ(found_blocks, num_blocks);
89 }
90
91 return true;
92}
93
Nicolas Geoffray0d3f5782014-05-14 09:43:38 +010094void SsaLivenessAnalysis::LinearizeGraph() {
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +000095 // Create a reverse post ordering with the following properties:
96 // - Blocks in a loop are consecutive,
97 // - Back-edge is the last block before loop exits.
98
99 // (1): Record the number of forward predecessors for each block. This is to
100 // ensure the resulting order is reverse post order. We could use the
101 // current reverse post order in the graph, but it would require making
102 // order queries to a GrowableArray, which is not the best data structure
103 // for it.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100104 ArenaVector<uint32_t> forward_predecessors(graph_->GetBlocks().size(),
105 graph_->GetArena()->Adapter(kArenaAllocSsaLiveness));
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100106 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
David Brazdil46e2a392015-03-16 17:31:52 +0000107 HBasicBlock* block = it.Current();
Vladimir Marko60584552015-09-03 13:35:12 +0000108 size_t number_of_forward_predecessors = block->GetPredecessors().size();
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000109 if (block->IsLoopHeader()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100110 number_of_forward_predecessors -= block->GetLoopInformation()->NumberOfBackEdges();
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000111 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100112 forward_predecessors[block->GetBlockId()] = number_of_forward_predecessors;
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000113 }
114
115 // (2): Following a worklist approach, first start with the entry block, and
116 // iterate over the successors. When all non-back edge predecessors of a
117 // successor block are visited, the successor block is added in the worklist
118 // following an order that satisfies the requirements to build our linear graph.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100119 graph_->linear_order_.reserve(graph_->GetReversePostOrder().size());
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100120 ArenaVector<HBasicBlock*> worklist(graph_->GetArena()->Adapter(kArenaAllocSsaLiveness));
121 worklist.push_back(graph_->GetEntryBlock());
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000122 do {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100123 HBasicBlock* current = worklist.back();
124 worklist.pop_back();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100125 graph_->linear_order_.push_back(current);
Vladimir Marko60584552015-09-03 13:35:12 +0000126 for (HBasicBlock* successor : current->GetSuccessors()) {
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000127 int block_id = successor->GetBlockId();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100128 size_t number_of_remaining_predecessors = forward_predecessors[block_id];
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000129 if (number_of_remaining_predecessors == 1) {
130 AddToListForLinearization(&worklist, successor);
131 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100132 forward_predecessors[block_id] = number_of_remaining_predecessors - 1;
Nicolas Geoffraya8eed3a2014-11-24 17:47:10 +0000133 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100134 } while (!worklist.empty());
David Brazdil30f76662016-09-02 11:42:48 +0100135
136 DCHECK(graph_->HasIrreducibleLoops() || IsLinearOrderWellFormed(*graph_));
Nicolas Geoffray0d3f5782014-05-14 09:43:38 +0100137}
138
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100139void SsaLivenessAnalysis::NumberInstructions() {
140 int ssa_index = 0;
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100141 size_t lifetime_position = 0;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100142 // Each instruction gets a lifetime position, and a block gets a lifetime
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100143 // start and end position. Non-phi instructions have a distinct lifetime position than
144 // the block they are in. Phi instructions have the lifetime start of their block as
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100145 // lifetime position.
146 //
147 // Because the register allocator will insert moves in the graph, we need
148 // to differentiate between the start and end of an instruction. Adding 2 to
149 // the lifetime position for each instruction ensures the start of an
150 // instruction is different than the end of the previous instruction.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100151 for (HLinearOrderIterator it(*graph_); !it.Done(); it.Advance()) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100152 HBasicBlock* block = it.Current();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100153 block->SetLifetimeStart(lifetime_position);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100154
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800155 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
156 HInstruction* current = inst_it.Current();
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000157 codegen_->AllocateLocations(current);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100158 LocationSummary* locations = current->GetLocations();
159 if (locations != nullptr && locations->Out().IsValid()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100160 instructions_from_ssa_index_.push_back(current);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100161 current->SetSsaIndex(ssa_index++);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100162 current->SetLiveInterval(
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100163 LiveInterval::MakeInterval(graph_->GetArena(), current->GetType(), current));
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100164 }
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100165 current->SetLifetimePosition(lifetime_position);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100166 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100167 lifetime_position += 2;
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100168
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100169 // Add a null marker to notify we are starting a block.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100170 instructions_from_lifetime_position_.push_back(nullptr);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100171
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800172 for (HInstructionIterator inst_it(block->GetInstructions()); !inst_it.Done();
173 inst_it.Advance()) {
174 HInstruction* current = inst_it.Current();
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000175 codegen_->AllocateLocations(current);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100176 LocationSummary* locations = current->GetLocations();
177 if (locations != nullptr && locations->Out().IsValid()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100178 instructions_from_ssa_index_.push_back(current);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100179 current->SetSsaIndex(ssa_index++);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100180 current->SetLiveInterval(
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100181 LiveInterval::MakeInterval(graph_->GetArena(), current->GetType(), current));
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100182 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100183 instructions_from_lifetime_position_.push_back(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100184 current->SetLifetimePosition(lifetime_position);
185 lifetime_position += 2;
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100186 }
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100187
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100188 block->SetLifetimeEnd(lifetime_position);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100189 }
190 number_of_ssa_values_ = ssa_index;
191}
192
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100193void SsaLivenessAnalysis::ComputeLiveness() {
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100194 for (HLinearOrderIterator it(*graph_); !it.Done(); it.Advance()) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100195 HBasicBlock* block = it.Current();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100196 block_infos_[block->GetBlockId()] =
197 new (graph_->GetArena()) BlockInfo(graph_->GetArena(), *block, number_of_ssa_values_);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100198 }
199
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100200 // Compute the live ranges, as well as the initial live_in, live_out, and kill sets.
201 // This method does not handle backward branches for the sets, therefore live_in
202 // and live_out sets are not yet correct.
203 ComputeLiveRanges();
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100204
205 // Do a fixed point calculation to take into account backward branches,
206 // that will update live_in of loop headers, and therefore live_out and live_in
207 // of blocks in the loop.
208 ComputeLiveInAndLiveOutSets();
209}
210
David Brazdil674f5192016-02-02 16:50:46 +0000211static void RecursivelyProcessInputs(HInstruction* current,
212 HInstruction* actual_user,
213 BitVector* live_in) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100214 HInputsRef inputs = current->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100215 for (size_t i = 0; i < inputs.size(); ++i) {
216 HInstruction* input = inputs[i];
David Brazdil674f5192016-02-02 16:50:46 +0000217 bool has_in_location = current->GetLocations()->InAt(i).IsValid();
218 bool has_out_location = input->GetLocations()->Out().IsValid();
219
220 if (has_in_location) {
221 DCHECK(has_out_location)
222 << "Instruction " << current->DebugName() << current->GetId()
223 << " expects an input value at index " << i << " but "
224 << input->DebugName() << input->GetId() << " does not produce one.";
225 DCHECK(input->HasSsaIndex());
226 // `input` generates a result used by `current`. Add use and update
227 // the live-in set.
228 input->GetLiveInterval()->AddUse(current, /* environment */ nullptr, i, actual_user);
229 live_in->SetBit(input->GetSsaIndex());
230 } else if (has_out_location) {
231 // `input` generates a result but it is not used by `current`.
232 } else {
233 // `input` is inlined into `current`. Walk over its inputs and record
234 // uses at `current`.
235 DCHECK(input->IsEmittedAtUseSite());
236 // Check that the inlined input is not a phi. Recursing on loop phis could
237 // lead to an infinite loop.
238 DCHECK(!input->IsPhi());
239 RecursivelyProcessInputs(input, actual_user, live_in);
240 }
241 }
242}
243
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100244void SsaLivenessAnalysis::ComputeLiveRanges() {
245 // Do a post order visit, adding inputs of instructions live in the block where
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100246 // that instruction is defined, and killing instructions that are being visited.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100247 for (HLinearPostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100248 HBasicBlock* block = it.Current();
249
250 BitVector* kill = GetKillSet(*block);
251 BitVector* live_in = GetLiveInSet(*block);
252
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100253 // Set phi inputs of successors of this block corresponding to this block
254 // as live_in.
Vladimir Marko60584552015-09-03 13:35:12 +0000255 for (HBasicBlock* successor : block->GetSuccessors()) {
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100256 live_in->Union(GetLiveInSet(*successor));
David Brazdil77a48ae2015-09-15 12:34:04 +0000257 if (successor->IsCatchBlock()) {
258 // Inputs of catch phis will be kept alive through their environment
259 // uses, allowing the runtime to copy their values to the corresponding
260 // catch phi spill slots when an exception is thrown.
261 // The only instructions which may not be recorded in the environments
262 // are constants created by the SSA builder as typed equivalents of
263 // untyped constants from the bytecode, or phis with only such constants
David Brazdilbadd8262016-02-02 16:28:56 +0000264 // as inputs (verified by GraphChecker). Their raw binary value must
David Brazdil77a48ae2015-09-15 12:34:04 +0000265 // therefore be the same and we only need to keep alive one.
266 } else {
267 size_t phi_input_index = successor->GetPredecessorIndexOf(block);
268 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
269 HInstruction* phi = phi_it.Current();
270 HInstruction* input = phi->InputAt(phi_input_index);
271 input->GetLiveInterval()->AddPhiUse(phi, phi_input_index, block);
272 // A phi input whose last user is the phi dies at the end of the predecessor block,
273 // and not at the phi's lifetime position.
274 live_in->SetBit(input->GetSsaIndex());
275 }
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100276 }
277 }
278
279 // Add a range that covers this block to all instructions live_in because of successors.
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +0100280 // Instructions defined in this block will have their start of the range adjusted.
Vladimir Markoa5b8fde2014-05-23 15:16:44 +0100281 for (uint32_t idx : live_in->Indexes()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100282 HInstruction* current = GetInstructionFromSsaIndex(idx);
Vladimir Markoa5b8fde2014-05-23 15:16:44 +0100283 current->GetLiveInterval()->AddRange(block->GetLifetimeStart(), block->GetLifetimeEnd());
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100284 }
285
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800286 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
287 back_it.Advance()) {
288 HInstruction* current = back_it.Current();
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100289 if (current->HasSsaIndex()) {
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100290 // Kill the instruction and shorten its interval.
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100291 kill->SetBit(current->GetSsaIndex());
292 live_in->ClearBit(current->GetSsaIndex());
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100293 current->GetLiveInterval()->SetFrom(current->GetLifetimePosition());
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100294 }
295
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +0000296 // Process the environment first, because we know their uses come after
297 // or at the same liveness position of inputs.
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100298 for (HEnvironment* environment = current->GetEnvironment();
299 environment != nullptr;
300 environment = environment->GetParent()) {
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +0000301 // Handle environment uses. See statements (b) and (c) of the
302 // SsaLivenessAnalysis.
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +0000303 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
304 HInstruction* instruction = environment->GetInstructionAt(i);
Mingyao Yang718493c2015-07-22 15:56:34 -0700305 bool should_be_live = ShouldBeLiveForEnvironment(current, instruction);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +0000306 if (should_be_live) {
307 DCHECK(instruction->HasSsaIndex());
308 live_in->SetBit(instruction->GetSsaIndex());
309 }
310 if (instruction != nullptr) {
311 instruction->GetLiveInterval()->AddUse(
David Brazdilb3e773e2016-01-26 11:28:37 +0000312 current, environment, i, /* actual_user */ nullptr, should_be_live);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +0000313 }
314 }
315 }
316
David Brazdilb3e773e2016-01-26 11:28:37 +0000317 // Process inputs of instructions.
318 if (current->IsEmittedAtUseSite()) {
319 if (kIsDebugBuild) {
320 DCHECK(!current->GetLocations()->Out().IsValid());
Vladimir Marko46817b82016-03-29 12:21:58 +0100321 for (const HUseListNode<HInstruction*>& use : current->GetUses()) {
322 HInstruction* user = use.GetUser();
323 size_t index = use.GetIndex();
David Brazdilb3e773e2016-01-26 11:28:37 +0000324 DCHECK(!user->GetLocations()->InAt(index).IsValid());
325 }
326 DCHECK(!current->HasEnvironmentUses());
327 }
328 } else {
David Brazdil674f5192016-02-02 16:50:46 +0000329 RecursivelyProcessInputs(current, current, live_in);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100330 }
331 }
332
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100333 // Kill phis defined in this block.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800334 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
335 HInstruction* current = inst_it.Current();
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100336 if (current->HasSsaIndex()) {
337 kill->SetBit(current->GetSsaIndex());
338 live_in->ClearBit(current->GetSsaIndex());
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100339 LiveInterval* interval = current->GetLiveInterval();
340 DCHECK((interval->GetFirstRange() == nullptr)
341 || (interval->GetStart() == current->GetLifetimePosition()));
342 interval->SetFrom(current->GetLifetimePosition());
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100343 }
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100344 }
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100345
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100346 if (block->IsLoopHeader()) {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100347 if (kIsDebugBuild) {
348 CheckNoLiveInIrreducibleLoop(*block);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000349 }
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100350 size_t last_position = block->GetLoopInformation()->GetLifetimeEnd();
Nicolas Geoffrayddb311f2014-05-16 09:28:54 +0100351 // For all live_in instructions at the loop header, we need to create a range
352 // that covers the full loop.
Vladimir Markoa5b8fde2014-05-23 15:16:44 +0100353 for (uint32_t idx : live_in->Indexes()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100354 HInstruction* current = GetInstructionFromSsaIndex(idx);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100355 current->GetLiveInterval()->AddLoopRange(block->GetLifetimeStart(), last_position);
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100356 }
357 }
358 }
359}
360
361void SsaLivenessAnalysis::ComputeLiveInAndLiveOutSets() {
362 bool changed;
363 do {
364 changed = false;
365
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100366 for (HPostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100367 const HBasicBlock& block = *it.Current();
368
369 // The live_in set depends on the kill set (which does not
370 // change in this loop), and the live_out set. If the live_out
371 // set does not change, there is no need to update the live_in set.
372 if (UpdateLiveOut(block) && UpdateLiveIn(block)) {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100373 if (kIsDebugBuild) {
374 CheckNoLiveInIrreducibleLoop(block);
375 }
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100376 changed = true;
377 }
378 }
379 } while (changed);
380}
381
382bool SsaLivenessAnalysis::UpdateLiveOut(const HBasicBlock& block) {
383 BitVector* live_out = GetLiveOutSet(block);
384 bool changed = false;
385 // The live_out set of a block is the union of live_in sets of its successors.
Vladimir Marko60584552015-09-03 13:35:12 +0000386 for (HBasicBlock* successor : block.GetSuccessors()) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100387 if (live_out->Union(GetLiveInSet(*successor))) {
388 changed = true;
389 }
390 }
391 return changed;
392}
393
394
395bool SsaLivenessAnalysis::UpdateLiveIn(const HBasicBlock& block) {
396 BitVector* live_out = GetLiveOutSet(block);
397 BitVector* kill = GetKillSet(block);
398 BitVector* live_in = GetLiveInSet(block);
399 // If live_out is updated (because of backward branches), we need to make
400 // sure instructions in live_out are also in live_in, unless they are killed
401 // by this block.
402 return live_in->UnionIfNotIn(live_out, kill);
403}
404
Matthew Gharrityd9ffd0d2016-06-22 10:27:55 -0700405void LiveInterval::DumpWithContext(std::ostream& stream,
406 const CodeGenerator& codegen) const {
407 Dump(stream);
408 if (IsFixed()) {
409 stream << ", register:" << GetRegister() << "(";
410 if (IsFloatingPoint()) {
411 codegen.DumpFloatingPointRegister(stream, GetRegister());
412 } else {
413 codegen.DumpCoreRegister(stream, GetRegister());
414 }
415 stream << ")";
416 } else {
417 stream << ", spill slot:" << GetSpillSlot();
418 }
419 stream << ", requires_register:" << (GetDefinedBy() != nullptr && RequiresRegister());
420 if (GetParent()->GetDefinedBy() != nullptr) {
421 stream << ", defined_by:" << GetParent()->GetDefinedBy()->GetKind();
422 stream << "(" << GetParent()->GetDefinedBy()->GetLifetimePosition() << ")";
423 }
424}
425
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000426static int RegisterOrLowRegister(Location location) {
427 return location.IsPair() ? location.low() : location.reg();
428}
429
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100430int LiveInterval::FindFirstRegisterHint(size_t* free_until,
431 const SsaLivenessAnalysis& liveness) const {
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000432 DCHECK(!IsHighInterval());
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000433 if (IsTemp()) return kNoRegister;
434
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100435 if (GetParent() == this && defined_by_ != nullptr) {
436 // This is the first interval for the instruction. Try to find
437 // a register based on its definition.
438 DCHECK_EQ(defined_by_->GetLiveInterval(), this);
439 int hint = FindHintAtDefinition();
440 if (hint != kNoRegister && free_until[hint] > GetStart()) {
441 return hint;
442 }
443 }
444
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100445 if (IsSplit() && liveness.IsAtBlockBoundary(GetStart() / 2)) {
446 // If the start of this interval is at a block boundary, we look at the
447 // location of the interval in blocks preceding the block this interval
448 // starts at. If one location is a register we return it as a hint. This
449 // will avoid a move between the two blocks.
450 HBasicBlock* block = liveness.GetBlockFromPosition(GetStart() / 2);
Nicolas Geoffray82726882015-06-01 13:51:57 +0100451 size_t next_register_use = FirstRegisterUse();
Vladimir Marko60584552015-09-03 13:35:12 +0000452 for (HBasicBlock* predecessor : block->GetPredecessors()) {
453 size_t position = predecessor->GetLifetimeEnd() - 1;
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100454 // We know positions above GetStart() do not have a location yet.
455 if (position < GetStart()) {
456 LiveInterval* existing = GetParent()->GetSiblingAt(position);
457 if (existing != nullptr
458 && existing->HasRegister()
Nicolas Geoffray82726882015-06-01 13:51:57 +0100459 // It's worth using that register if it is available until
460 // the next use.
461 && (free_until[existing->GetRegister()] >= next_register_use)) {
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100462 return existing->GetRegister();
463 }
464 }
465 }
466 }
467
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100468 UsePosition* use = first_use_;
469 size_t start = GetStart();
470 size_t end = GetEnd();
471 while (use != nullptr && use->GetPosition() <= end) {
472 size_t use_position = use->GetPosition();
Nicolas Geoffray57902602015-04-21 14:28:41 +0100473 if (use_position >= start && !use->IsSynthesized()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100474 HInstruction* user = use->GetUser();
475 size_t input_index = use->GetInputIndex();
476 if (user->IsPhi()) {
477 // If the phi has a register, try to use the same.
478 Location phi_location = user->GetLiveInterval()->ToLocation();
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000479 if (phi_location.IsRegisterKind()) {
480 DCHECK(SameRegisterKind(phi_location));
481 int reg = RegisterOrLowRegister(phi_location);
482 if (free_until[reg] >= use_position) {
483 return reg;
484 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100485 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100486 // If the instruction dies at the phi assignment, we can try having the
487 // same register.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100488 if (end == user->GetBlock()->GetPredecessors()[input_index]->GetLifetimeEnd()) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100489 HInputsRef inputs = user->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100490 for (size_t i = 0; i < inputs.size(); ++i) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100491 if (i == input_index) {
492 continue;
493 }
Vladimir Marko372f10e2016-05-17 16:30:10 +0100494 Location location = inputs[i]->GetLiveInterval()->GetLocationAt(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100495 user->GetBlock()->GetPredecessors()[i]->GetLifetimeEnd() - 1);
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000496 if (location.IsRegisterKind()) {
497 int reg = RegisterOrLowRegister(location);
498 if (free_until[reg] >= use_position) {
499 return reg;
500 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100501 }
502 }
503 }
504 } else {
505 // If the instruction is expected in a register, try to use it.
506 LocationSummary* locations = user->GetLocations();
507 Location expected = locations->InAt(use->GetInputIndex());
508 // We use the user's lifetime position - 1 (and not `use_position`) because the
509 // register is blocked at the beginning of the user.
510 size_t position = user->GetLifetimePosition() - 1;
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000511 if (expected.IsRegisterKind()) {
512 DCHECK(SameRegisterKind(expected));
513 int reg = RegisterOrLowRegister(expected);
514 if (free_until[reg] >= position) {
515 return reg;
516 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100517 }
518 }
519 }
520 use = use->GetNext();
521 }
522
523 return kNoRegister;
524}
525
526int LiveInterval::FindHintAtDefinition() const {
527 if (defined_by_->IsPhi()) {
528 // Try to use the same register as one of the inputs.
Vladimir Marko60584552015-09-03 13:35:12 +0000529 const ArenaVector<HBasicBlock*>& predecessors = defined_by_->GetBlock()->GetPredecessors();
Vladimir Markoe9004912016-06-16 16:50:52 +0100530 HInputsRef inputs = defined_by_->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100531 for (size_t i = 0; i < inputs.size(); ++i) {
Vladimir Marko60584552015-09-03 13:35:12 +0000532 size_t end = predecessors[i]->GetLifetimeEnd();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100533 LiveInterval* input_interval = inputs[i]->GetLiveInterval()->GetSiblingAt(end - 1);
David Brazdil241a4862015-04-16 17:59:03 +0100534 if (input_interval->GetEnd() == end) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100535 // If the input dies at the end of the predecessor, we know its register can
536 // be reused.
David Brazdil241a4862015-04-16 17:59:03 +0100537 Location input_location = input_interval->ToLocation();
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000538 if (input_location.IsRegisterKind()) {
539 DCHECK(SameRegisterKind(input_location));
540 return RegisterOrLowRegister(input_location);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100541 }
542 }
543 }
544 } else {
545 LocationSummary* locations = GetDefinedBy()->GetLocations();
546 Location out = locations->Out();
547 if (out.IsUnallocated() && out.GetPolicy() == Location::kSameAsFirstInput) {
548 // Try to use the same register as the first input.
David Brazdil241a4862015-04-16 17:59:03 +0100549 LiveInterval* input_interval =
550 GetDefinedBy()->InputAt(0)->GetLiveInterval()->GetSiblingAt(GetStart() - 1);
551 if (input_interval->GetEnd() == GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100552 // If the input dies at the start of this instruction, we know its register can
553 // be reused.
David Brazdil241a4862015-04-16 17:59:03 +0100554 Location location = input_interval->ToLocation();
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000555 if (location.IsRegisterKind()) {
556 DCHECK(SameRegisterKind(location));
557 return RegisterOrLowRegister(location);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100558 }
559 }
560 }
561 }
562 return kNoRegister;
563}
564
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100565bool LiveInterval::SameRegisterKind(Location other) const {
Nicolas Geoffrayda02afe2015-02-11 02:29:42 +0000566 if (IsFloatingPoint()) {
567 if (IsLowInterval() || IsHighInterval()) {
568 return other.IsFpuRegisterPair();
569 } else {
570 return other.IsFpuRegister();
571 }
572 } else {
573 if (IsLowInterval() || IsHighInterval()) {
574 return other.IsRegisterPair();
575 } else {
576 return other.IsRegister();
577 }
578 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100579}
580
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100581bool LiveInterval::NeedsTwoSpillSlots() const {
582 return type_ == Primitive::kPrimLong || type_ == Primitive::kPrimDouble;
583}
584
585Location LiveInterval::ToLocation() const {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000586 DCHECK(!IsHighInterval());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100587 if (HasRegister()) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000588 if (IsFloatingPoint()) {
589 if (HasHighInterval()) {
590 return Location::FpuRegisterPairLocation(GetRegister(), GetHighInterval()->GetRegister());
591 } else {
592 return Location::FpuRegisterLocation(GetRegister());
593 }
594 } else {
595 if (HasHighInterval()) {
596 return Location::RegisterPairLocation(GetRegister(), GetHighInterval()->GetRegister());
597 } else {
598 return Location::RegisterLocation(GetRegister());
599 }
600 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100601 } else {
602 HInstruction* defined_by = GetParent()->GetDefinedBy();
603 if (defined_by->IsConstant()) {
604 return defined_by->GetLocations()->Out();
605 } else if (GetParent()->HasSpillSlot()) {
606 if (NeedsTwoSpillSlots()) {
607 return Location::DoubleStackSlot(GetParent()->GetSpillSlot());
608 } else {
609 return Location::StackSlot(GetParent()->GetSpillSlot());
610 }
611 } else {
612 return Location();
613 }
614 }
615}
616
David Brazdil5b8e6a52015-02-25 16:17:05 +0000617Location LiveInterval::GetLocationAt(size_t position) {
David Brazdil241a4862015-04-16 17:59:03 +0100618 LiveInterval* sibling = GetSiblingAt(position);
619 DCHECK(sibling != nullptr);
620 return sibling->ToLocation();
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100621}
622
David Brazdil241a4862015-04-16 17:59:03 +0100623LiveInterval* LiveInterval::GetSiblingAt(size_t position) {
David Brazdil5b8e6a52015-02-25 16:17:05 +0000624 LiveInterval* current = this;
David Brazdil241a4862015-04-16 17:59:03 +0100625 while (current != nullptr && !current->IsDefinedAt(position)) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100626 current = current->GetNextSibling();
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100627 }
David Brazdil241a4862015-04-16 17:59:03 +0100628 return current;
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100629}
630
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100631} // namespace art