blob: adcadf5a51786ad0c122cece549dddb1622a2a44 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
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 "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010019#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000020#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000021#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000022
23namespace art {
24
25void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000026 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027 blocks_.Add(block);
28}
29
Nicolas Geoffray804d0932014-05-02 08:46:00 +010030void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000031 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000032 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000033}
34
Roland Levillainfc600dc2014-12-02 17:16:31 +000035static void RemoveAsUser(HInstruction* instruction) {
36 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000037 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000038 }
39
40 HEnvironment* environment = instruction->GetEnvironment();
41 if (environment != nullptr) {
42 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000043 if (environment->GetInstructionAt(i) != nullptr) {
44 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000045 }
46 }
47 }
48}
49
50void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
51 for (size_t i = 0; i < blocks_.Size(); ++i) {
52 if (!visited.IsBitSet(i)) {
53 HBasicBlock* block = blocks_.Get(i);
54 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
55 RemoveAsUser(it.Current());
56 }
57 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
58 RemoveAsUser(it.Current());
59 }
60 }
61 }
62}
63
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000064void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010065 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000066 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000067 HBasicBlock* block = blocks_.Get(i);
68 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
69 block->GetSuccessors().Get(j)->RemovePredecessor(block);
70 }
71 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
72 block->RemovePhi(it.Current()->AsPhi(), /*ensure_safety=*/ false);
73 }
74 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
75 block->RemoveInstruction(it.Current(), /*ensure_safety=*/ false);
76 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000077 }
78 }
79}
80
81void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
82 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010083 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000085 if (visited->IsBitSet(id)) return;
86
87 visited->SetBit(id);
88 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010089 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
90 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000091 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000092 successor->AddBackEdge(block);
93 } else {
94 VisitBlockForBackEdges(successor, visited, visiting);
95 }
96 }
97 visiting->ClearBit(id);
98}
99
100void HGraph::BuildDominatorTree() {
101 ArenaBitVector visited(arena_, blocks_.Size(), false);
102
103 // (1) Find the back edges in the graph doing a DFS traversal.
104 FindBackEdges(&visited);
105
Roland Levillainfc600dc2014-12-02 17:16:31 +0000106 // (2) Remove instructions and phis from blocks not visited during
107 // the initial DFS as users from other instructions, so that
108 // users can be safely removed before uses later.
109 RemoveInstructionsAsUsersFromDeadBlocks(visited);
110
111 // (3) Remove blocks not visited during the initial DFS.
112 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 // predecessors list of live blocks.
114 RemoveDeadBlocks(visited);
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100117 // dominators and the reverse post order.
118 SimplifyCFG();
119
Roland Levillainfc600dc2014-12-02 17:16:31 +0000120 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000121 // the successors of a block only when all its forward branches
122 // have been processed.
123 GrowableArray<size_t> visits(arena_, blocks_.Size());
124 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100125 reverse_post_order_.Add(entry_block_);
126 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
127 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000128 }
129}
130
131HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
132 ArenaBitVector visited(arena_, blocks_.Size(), false);
133 // Walk the dominator tree of the first block and mark the visited blocks.
134 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000135 visited.SetBit(first->GetBlockId());
136 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 }
138 // Walk the dominator tree of the second block until a marked block is found.
139 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000140 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 return second;
142 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000143 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144 }
145 LOG(ERROR) << "Could not find common dominator";
146 return nullptr;
147}
148
149void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
150 HBasicBlock* predecessor,
151 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000152 if (block->GetDominator() == nullptr) {
153 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000154 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 }
157
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // Once all the forward edges have been visited, we know the immediate
160 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000161 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100163 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100164 reverse_post_order_.Add(block);
165 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
166 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000167 }
168 }
169}
170
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000171void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100172 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100173 SsaBuilder ssa_builder(this);
174 ssa_builder.BuildSsa();
175}
176
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
178 // Insert a new node between `block` and `successor` to split the
179 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100180 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100181 AddBlock(new_block);
182 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100183 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 new_block->AddSuccessor(successor);
185 if (successor->IsLoopHeader()) {
186 // If we split at a back edge boundary, make the new block the back edge.
187 HLoopInformation* info = successor->GetLoopInformation();
188 if (info->IsBackEdge(block)) {
189 info->RemoveBackEdge(block);
190 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100191 }
192 }
193}
194
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100195void HGraph::SimplifyLoop(HBasicBlock* header) {
196 HLoopInformation* info = header->GetLoopInformation();
197
198 // If there are more than one back edge, make them branch to the same block that
199 // will become the only back edge. This simplifies finding natural loops in the
200 // graph.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100201 // Also, if the loop is a do/while (that is the back edge is an if), change the
202 // back edge to be a goto. This simplifies code generation of suspend cheks.
203 if (info->NumberOfBackEdges() > 1 || info->GetBackEdges().Get(0)->GetLastInstruction()->IsIf()) {
204 HBasicBlock* new_back_edge = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100205 AddBlock(new_back_edge);
206 new_back_edge->AddInstruction(new (arena_) HGoto());
207 for (size_t pred = 0, e = info->GetBackEdges().Size(); pred < e; ++pred) {
208 HBasicBlock* back_edge = info->GetBackEdges().Get(pred);
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100209 back_edge->ReplaceSuccessor(header, new_back_edge);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 }
211 info->ClearBackEdges();
212 info->AddBackEdge(new_back_edge);
213 new_back_edge->AddSuccessor(header);
214 }
215
216 // Make sure the loop has only one pre header. This simplifies SSA building by having
217 // to just look at the pre header to know which locals are initialized at entry of the
218 // loop.
219 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
220 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100221 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100222 AddBlock(pre_header);
223 pre_header->AddInstruction(new (arena_) HGoto());
224
225 ArenaBitVector back_edges(arena_, GetBlocks().Size(), false);
226 HBasicBlock* back_edge = info->GetBackEdges().Get(0);
227 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
228 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
229 if (predecessor != back_edge) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100230 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100231 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232 }
233 }
234 pre_header->AddSuccessor(header);
235 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100236
237 // Make sure the second predecessor of a loop header is the back edge.
238 if (header->GetPredecessors().Get(1) != info->GetBackEdges().Get(0)) {
239 header->SwapPredecessors();
240 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100241
242 // Place the suspend check at the beginning of the header, so that live registers
243 // will be known when allocating registers. Note that code generation can still
244 // generate the suspend check at the back edge, but needs to be careful with
245 // loop phi spill slots (which are not written to at back edge).
246 HInstruction* first_instruction = header->GetFirstInstruction();
247 if (!first_instruction->IsSuspendCheck()) {
248 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
249 header->InsertInstructionBefore(check, first_instruction);
250 first_instruction = check;
251 }
252 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100253}
254
255void HGraph::SimplifyCFG() {
256 // Simplify the CFG for future analysis, and code generation:
257 // (1): Split critical edges.
258 // (2): Simplify loops by having only one back edge, and one preheader.
259 for (size_t i = 0; i < blocks_.Size(); ++i) {
260 HBasicBlock* block = blocks_.Get(i);
261 if (block->GetSuccessors().Size() > 1) {
262 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
263 HBasicBlock* successor = block->GetSuccessors().Get(j);
264 if (successor->GetPredecessors().Size() > 1) {
265 SplitCriticalEdge(block, successor);
266 --j;
267 }
268 }
269 }
270 if (block->IsLoopHeader()) {
271 SimplifyLoop(block);
272 }
273 }
274}
275
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000276bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 for (size_t i = 0; i < blocks_.Size(); ++i) {
278 HBasicBlock* block = blocks_.Get(i);
279 if (block->IsLoopHeader()) {
280 HLoopInformation* info = block->GetLoopInformation();
281 if (!info->Populate()) {
282 // Abort if the loop is non natural. We currently bailout in such cases.
283 return false;
284 }
285 }
286 }
287 return true;
288}
289
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000290HNullConstant* HGraph::GetNullConstant() {
291 if (cached_null_constant_ == nullptr) {
292 cached_null_constant_ = new (arena_) HNullConstant();
293 entry_block_->InsertInstructionBefore(cached_null_constant_,
294 entry_block_->GetLastInstruction());
295 }
296 return cached_null_constant_;
297}
298
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000299void HLoopInformation::Add(HBasicBlock* block) {
300 blocks_.SetBit(block->GetBlockId());
301}
302
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
304 if (blocks_.IsBitSet(block->GetBlockId())) {
305 return;
306 }
307
308 blocks_.SetBit(block->GetBlockId());
309 block->SetInLoop(this);
310 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
311 PopulateRecursive(block->GetPredecessors().Get(i));
312 }
313}
314
315bool HLoopInformation::Populate() {
316 DCHECK_EQ(GetBackEdges().Size(), 1u);
317 HBasicBlock* back_edge = GetBackEdges().Get(0);
318 DCHECK(back_edge->GetDominator() != nullptr);
319 if (!header_->Dominates(back_edge)) {
320 // This loop is not natural. Do not bother going further.
321 return false;
322 }
323
324 // Populate this loop: starting with the back edge, recursively add predecessors
325 // that are not already part of that loop. Set the header as part of the loop
326 // to end the recursion.
327 // This is a recursive implementation of the algorithm described in
328 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
329 blocks_.SetBit(header_->GetBlockId());
330 PopulateRecursive(back_edge);
331 return true;
332}
333
334HBasicBlock* HLoopInformation::GetPreHeader() const {
335 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
336 return header_->GetDominator();
337}
338
339bool HLoopInformation::Contains(const HBasicBlock& block) const {
340 return blocks_.IsBitSet(block.GetBlockId());
341}
342
343bool HLoopInformation::IsIn(const HLoopInformation& other) const {
344 return other.blocks_.IsBitSet(header_->GetBlockId());
345}
346
347bool HBasicBlock::Dominates(HBasicBlock* other) const {
348 // Walk up the dominator tree from `other`, to find out if `this`
349 // is an ancestor.
350 HBasicBlock* current = other;
351 while (current != nullptr) {
352 if (current == this) {
353 return true;
354 }
355 current = current->GetDominator();
356 }
357 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100358}
359
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100360static void UpdateInputsUsers(HInstruction* instruction) {
361 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
362 instruction->InputAt(i)->AddUseAt(instruction, i);
363 }
364 // Environment should be created later.
365 DCHECK(!instruction->HasEnvironment());
366}
367
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100368void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
Roland Levillain476df552014-10-09 17:51:36 +0100369 DCHECK(!cursor->IsPhi());
370 DCHECK(!instruction->IsPhi());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100371 DCHECK_EQ(instruction->GetId(), -1);
372 DCHECK_NE(cursor->GetId(), -1);
373 DCHECK_EQ(cursor->GetBlock(), this);
374 DCHECK(!instruction->IsControlFlow());
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100375 instruction->next_ = cursor;
376 instruction->previous_ = cursor->previous_;
377 cursor->previous_ = instruction;
378 if (GetFirstInstruction() == cursor) {
379 instructions_.first_instruction_ = instruction;
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100380 } else {
381 instruction->previous_->next_ = instruction;
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100382 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100383 instruction->SetBlock(this);
384 instruction->SetId(GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100385 UpdateInputsUsers(instruction);
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100386}
387
Roland Levillainccc07a92014-09-16 14:48:16 +0100388void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
389 HInstruction* replacement) {
390 DCHECK(initial->GetBlock() == this);
391 InsertInstructionBefore(replacement, initial);
392 initial->ReplaceWith(replacement);
393 RemoveInstruction(initial);
394}
395
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100396static void Add(HInstructionList* instruction_list,
397 HBasicBlock* block,
398 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000399 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000400 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100401 instruction->SetBlock(block);
402 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100403 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100404 instruction_list->AddInstruction(instruction);
405}
406
407void HBasicBlock::AddInstruction(HInstruction* instruction) {
408 Add(&instructions_, this, instruction);
409}
410
411void HBasicBlock::AddPhi(HPhi* phi) {
412 Add(&phis_, this, phi);
413}
414
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100415void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
416 DCHECK_EQ(phi->GetId(), -1);
417 DCHECK_NE(cursor->GetId(), -1);
418 DCHECK_EQ(cursor->GetBlock(), this);
419 if (cursor->next_ == nullptr) {
420 cursor->next_ = phi;
421 phi->previous_ = cursor;
422 DCHECK(phi->next_ == nullptr);
423 } else {
424 phi->next_ = cursor->next_;
425 phi->previous_ = cursor;
426 cursor->next_ = phi;
427 phi->next_->previous_ = phi;
428 }
429 phi->SetBlock(this);
430 phi->SetId(GetGraph()->GetNextInstructionId());
431 UpdateInputsUsers(phi);
432}
433
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100434static void Remove(HInstructionList* instruction_list,
435 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000436 HInstruction* instruction,
437 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100438 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100439 instruction->SetBlock(nullptr);
440 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000441 if (ensure_safety) {
442 DCHECK(instruction->GetUses().IsEmpty());
443 DCHECK(instruction->GetEnvUses().IsEmpty());
444 RemoveAsUser(instruction);
445 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100446}
447
David Brazdil1abb4192015-02-17 18:33:36 +0000448void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
449 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100450}
451
David Brazdil1abb4192015-02-17 18:33:36 +0000452void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
453 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100454}
455
David Brazdiled596192015-01-23 10:39:45 +0000456void HEnvironment::CopyFrom(HEnvironment* env) {
457 for (size_t i = 0; i < env->Size(); i++) {
458 HInstruction* instruction = env->GetInstructionAt(i);
459 SetRawEnvAt(i, instruction);
460 if (instruction != nullptr) {
461 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100462 }
David Brazdiled596192015-01-23 10:39:45 +0000463 }
464}
465
David Brazdil1abb4192015-02-17 18:33:36 +0000466void HEnvironment::RemoveAsUserOfInput(size_t index) const {
467 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
468 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100469}
470
Calin Juravle77520bc2015-01-12 18:45:46 +0000471HInstruction* HInstruction::GetNextDisregardingMoves() const {
472 HInstruction* next = GetNext();
473 while (next != nullptr && next->IsParallelMove()) {
474 next = next->GetNext();
475 }
476 return next;
477}
478
479HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
480 HInstruction* previous = GetPrevious();
481 while (previous != nullptr && previous->IsParallelMove()) {
482 previous = previous->GetPrevious();
483 }
484 return previous;
485}
486
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100487void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000488 if (first_instruction_ == nullptr) {
489 DCHECK(last_instruction_ == nullptr);
490 first_instruction_ = last_instruction_ = instruction;
491 } else {
492 last_instruction_->next_ = instruction;
493 instruction->previous_ = last_instruction_;
494 last_instruction_ = instruction;
495 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000496}
497
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100498void HInstructionList::RemoveInstruction(HInstruction* instruction) {
499 if (instruction->previous_ != nullptr) {
500 instruction->previous_->next_ = instruction->next_;
501 }
502 if (instruction->next_ != nullptr) {
503 instruction->next_->previous_ = instruction->previous_;
504 }
505 if (instruction == first_instruction_) {
506 first_instruction_ = instruction->next_;
507 }
508 if (instruction == last_instruction_) {
509 last_instruction_ = instruction->previous_;
510 }
511}
512
Roland Levillain6b469232014-09-25 10:10:38 +0100513bool HInstructionList::Contains(HInstruction* instruction) const {
514 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
515 if (it.Current() == instruction) {
516 return true;
517 }
518 }
519 return false;
520}
521
Roland Levillainccc07a92014-09-16 14:48:16 +0100522bool HInstructionList::FoundBefore(const HInstruction* instruction1,
523 const HInstruction* instruction2) const {
524 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
525 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
526 if (it.Current() == instruction1) {
527 return true;
528 }
529 if (it.Current() == instruction2) {
530 return false;
531 }
532 }
533 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
534 return true;
535}
536
Roland Levillain6c82d402014-10-13 16:10:27 +0100537bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
538 if (other_instruction == this) {
539 // An instruction does not strictly dominate itself.
540 return false;
541 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100542 HBasicBlock* block = GetBlock();
543 HBasicBlock* other_block = other_instruction->GetBlock();
544 if (block != other_block) {
545 return GetBlock()->Dominates(other_instruction->GetBlock());
546 } else {
547 // If both instructions are in the same block, ensure this
548 // instruction comes before `other_instruction`.
549 if (IsPhi()) {
550 if (!other_instruction->IsPhi()) {
551 // Phis appear before non phi-instructions so this instruction
552 // dominates `other_instruction`.
553 return true;
554 } else {
555 // There is no order among phis.
556 LOG(FATAL) << "There is no dominance between phis of a same block.";
557 return false;
558 }
559 } else {
560 // `this` is not a phi.
561 if (other_instruction->IsPhi()) {
562 // Phis appear before non phi-instructions so this instruction
563 // does not dominate `other_instruction`.
564 return false;
565 } else {
566 // Check whether this instruction comes before
567 // `other_instruction` in the instruction list.
568 return block->GetInstructions().FoundBefore(this, other_instruction);
569 }
570 }
571 }
572}
573
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100574void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100575 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000576 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
577 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100578 HInstruction* user = current->GetUser();
579 size_t input_index = current->GetIndex();
580 user->SetRawInputAt(input_index, other);
581 other->AddUseAt(user, input_index);
582 }
583
David Brazdiled596192015-01-23 10:39:45 +0000584 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
585 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100586 HEnvironment* user = current->GetUser();
587 size_t input_index = current->GetIndex();
588 user->SetRawEnvAt(input_index, other);
589 other->AddEnvUseAt(user, input_index);
590 }
591
David Brazdiled596192015-01-23 10:39:45 +0000592 uses_.Clear();
593 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100594}
595
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100596void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000597 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100598 SetRawInputAt(index, replacement);
599 replacement->AddUseAt(this, index);
600}
601
Nicolas Geoffray39468442014-09-02 15:17:15 +0100602size_t HInstruction::EnvironmentSize() const {
603 return HasEnvironment() ? environment_->Size() : 0;
604}
605
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100606void HPhi::AddInput(HInstruction* input) {
607 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000608 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100609 input->AddUseAt(this, inputs_.Size() - 1);
610}
611
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100612#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000613void H##name::Accept(HGraphVisitor* visitor) { \
614 visitor->Visit##name(this); \
615}
616
617FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
618
619#undef DEFINE_ACCEPT
620
621void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100622 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
623 for (size_t i = 0 ; i < blocks.Size(); i++) {
624 VisitBasicBlock(blocks.Get(i));
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000625 }
626}
627
Roland Levillain633021e2014-10-01 14:12:25 +0100628void HGraphVisitor::VisitReversePostOrder() {
629 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
630 VisitBasicBlock(it.Current());
631 }
632}
633
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000634void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100635 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100636 it.Current()->Accept(this);
637 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100638 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000639 it.Current()->Accept(this);
640 }
641}
642
Roland Levillain9240d6a2014-10-20 16:47:04 +0100643HConstant* HUnaryOperation::TryStaticEvaluation() const {
644 if (GetInput()->IsIntConstant()) {
645 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
646 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
647 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100648 // TODO: Implement static evaluation of long unary operations.
649 //
650 // Do not exit with a fatal condition here. Instead, simply
651 // return `nullptr' to notify the caller that this instruction
652 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100653 return nullptr;
654 }
655 return nullptr;
656}
657
658HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100659 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
660 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
661 GetRight()->AsIntConstant()->GetValue());
Roland Levillain9240d6a2014-10-20 16:47:04 +0100662 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100663 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
664 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
665 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000666 if (GetResultType() == Primitive::kPrimLong) {
667 return new(GetBlock()->GetGraph()->GetArena()) HLongConstant(value);
668 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000669 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000670 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
671 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100672 }
673 return nullptr;
674}
Dave Allison20dfc792014-06-16 20:44:29 -0700675
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000676HConstant* HBinaryOperation::GetConstantRight() const {
677 if (GetRight()->IsConstant()) {
678 return GetRight()->AsConstant();
679 } else if (IsCommutative() && GetLeft()->IsConstant()) {
680 return GetLeft()->AsConstant();
681 } else {
682 return nullptr;
683 }
684}
685
686// If `GetConstantRight()` returns one of the input, this returns the other
687// one. Otherwise it returns nullptr.
688HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
689 HInstruction* most_constant_right = GetConstantRight();
690 if (most_constant_right == nullptr) {
691 return nullptr;
692 } else if (most_constant_right == GetLeft()) {
693 return GetRight();
694 } else {
695 return GetLeft();
696 }
697}
698
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100699bool HCondition::IsBeforeWhenDisregardMoves(HIf* if_) const {
Calin Juravle77520bc2015-01-12 18:45:46 +0000700 return this == if_->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100701}
702
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000703HConstant* HConstant::NewConstant(ArenaAllocator* allocator, Primitive::Type type, int64_t val) {
704 if (type == Primitive::kPrimInt) {
705 DCHECK(IsInt<32>(val));
706 return new (allocator) HIntConstant(val);
707 } else {
708 DCHECK_EQ(type, Primitive::kPrimLong);
709 return new (allocator) HLongConstant(val);
710 }
711}
712
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100713bool HInstruction::Equals(HInstruction* other) const {
714 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100715 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100716 if (!InstructionDataEquals(other)) return false;
717 if (GetType() != other->GetType()) return false;
718 if (InputCount() != other->InputCount()) return false;
719
720 for (size_t i = 0, e = InputCount(); i < e; ++i) {
721 if (InputAt(i) != other->InputAt(i)) return false;
722 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100723 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100724 return true;
725}
726
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700727std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
728#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
729 switch (rhs) {
730 FOR_EACH_INSTRUCTION(DECLARE_CASE)
731 default:
732 os << "Unknown instruction kind " << static_cast<int>(rhs);
733 break;
734 }
735#undef DECLARE_CASE
736 return os;
737}
738
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000739void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000740 next_->previous_ = previous_;
741 if (previous_ != nullptr) {
742 previous_->next_ = next_;
743 }
744 if (block_->instructions_.first_instruction_ == this) {
745 block_->instructions_.first_instruction_ = next_;
746 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000747 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000748
749 previous_ = cursor->previous_;
750 if (previous_ != nullptr) {
751 previous_->next_ = this;
752 }
753 next_ = cursor;
754 cursor->previous_ = this;
755 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000756
757 if (block_->instructions_.first_instruction_ == cursor) {
758 block_->instructions_.first_instruction_ = this;
759 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000760}
761
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000762HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
763 DCHECK(!cursor->IsControlFlow());
764 DCHECK_NE(instructions_.last_instruction_, cursor);
765 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000766
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000767 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
768 new_block->instructions_.first_instruction_ = cursor->GetNext();
769 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
770 cursor->next_->previous_ = nullptr;
771 cursor->next_ = nullptr;
772 instructions_.last_instruction_ = cursor;
773
774 new_block->instructions_.SetBlockOfInstructions(new_block);
775 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
776 HBasicBlock* successor = GetSuccessors().Get(i);
777 new_block->successors_.Add(successor);
778 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
779 }
780 successors_.Reset();
781
782 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
783 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
784 dominated->dominator_ = new_block;
785 new_block->dominated_blocks_.Add(dominated);
786 }
787 dominated_blocks_.Reset();
788 return new_block;
789}
790
791void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
792 for (HInstruction* current = first_instruction_;
793 current != nullptr;
794 current = current->GetNext()) {
795 current->SetBlock(block);
796 }
797}
798
799void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
800 DCHECK(Contains(cursor));
801 if (!instruction_list.IsEmpty()) {
802 if (cursor == last_instruction_) {
803 last_instruction_ = instruction_list.last_instruction_;
804 } else {
805 cursor->next_->previous_ = instruction_list.last_instruction_;
806 }
807 instruction_list.last_instruction_->next_ = cursor->next_;
808 cursor->next_ = instruction_list.first_instruction_;
809 instruction_list.first_instruction_->previous_ = cursor;
810 }
811}
812
813void HInstructionList::Add(const HInstructionList& instruction_list) {
814 DCHECK(!IsEmpty());
815 AddAfter(last_instruction_, instruction_list);
816}
817
818void HBasicBlock::MergeWith(HBasicBlock* other) {
819 DCHECK(successors_.IsEmpty()) << "Unimplemented block merge scenario";
820 DCHECK(dominated_blocks_.IsEmpty()) << "Unimplemented block merge scenario";
821 DCHECK(other->GetDominator()->IsEntryBlock() && other->GetGraph() != graph_)
822 << "Unimplemented block merge scenario";
823 DCHECK(other->GetPhis().IsEmpty());
824
825 successors_.Reset();
826 dominated_blocks_.Reset();
827 instructions_.Add(other->GetInstructions());
828 other->GetInstructions().SetBlockOfInstructions(this);
829
830 while (!other->GetSuccessors().IsEmpty()) {
831 HBasicBlock* successor = other->GetSuccessors().Get(0);
832 successor->ReplacePredecessor(other, this);
833 }
834
835 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
836 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
837 dominated_blocks_.Add(dominated);
838 dominated->SetDominator(this);
839 }
840 other->dominated_blocks_.Reset();
841 other->dominator_ = nullptr;
842 other->graph_ = nullptr;
843}
844
845void HBasicBlock::ReplaceWith(HBasicBlock* other) {
846 while (!GetPredecessors().IsEmpty()) {
847 HBasicBlock* predecessor = GetPredecessors().Get(0);
848 predecessor->ReplaceSuccessor(this, other);
849 }
850 while (!GetSuccessors().IsEmpty()) {
851 HBasicBlock* successor = GetSuccessors().Get(0);
852 successor->ReplacePredecessor(this, other);
853 }
854 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
855 other->AddDominatedBlock(dominated_blocks_.Get(i));
856 }
857 GetDominator()->ReplaceDominatedBlock(this, other);
858 other->SetDominator(GetDominator());
859 dominator_ = nullptr;
860 graph_ = nullptr;
861}
862
863// Create space in `blocks` for adding `number_of_new_blocks` entries
864// starting at location `at`. Blocks after `at` are moved accordingly.
865static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
866 size_t number_of_new_blocks,
867 size_t at) {
868 size_t old_size = blocks->Size();
869 size_t new_size = old_size + number_of_new_blocks;
870 blocks->SetSize(new_size);
871 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
872 blocks->Put(j, blocks->Get(i));
873 }
874}
875
876void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000877 // Walk over the entry block and:
878 // - Move constants from the entry block to the outer_graph's entry block,
879 // - Replace HParameterValue instructions with their real value.
880 // - Remove suspend checks, that hold an environment.
881 int parameter_index = 0;
882 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
883 HInstruction* current = it.Current();
884 if (current->IsConstant()) {
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000885 current->MoveBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000886 } else if (current->IsParameterValue()) {
887 current->ReplaceWith(invoke->InputAt(parameter_index++));
888 } else {
889 DCHECK(current->IsGoto() || current->IsSuspendCheck());
890 entry_block_->RemoveInstruction(current);
891 }
892 }
893
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000894 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000895 // Simple case of an entry block, a body block, and an exit block.
896 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000897 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000898 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
899 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000900 DCHECK(!body->IsExitBlock());
901 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000902
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000903 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
904 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000905
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000906 // Replace the invoke with the return value of the inlined graph.
907 if (last->IsReturn()) {
908 invoke->ReplaceWith(last->InputAt(0));
909 } else {
910 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000911 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000912
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000913 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000914 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000915 // Need to inline multiple blocks. We split `invoke`'s block
916 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000917 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000918 // with the second half.
919 ArenaAllocator* allocator = outer_graph->GetArena();
920 HBasicBlock* at = invoke->GetBlock();
921 HBasicBlock* to = at->SplitAfter(invoke);
922
923 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
924 DCHECK(!first->IsInLoop());
925 at->MergeWith(first);
926 exit_block_->ReplaceWith(to);
927
928 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +0000929 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000930 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +0000931 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
932 if (to->GetPredecessors().Size() == 1) {
933 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000934 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +0000935 if (!returns_void) {
936 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000937 }
938 predecessor->AddInstruction(new (allocator) HGoto());
939 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +0000940 } else {
941 if (!returns_void) {
942 // There will be multiple returns.
943 return_value = new (allocator) HPhi(allocator, kNoRegNumber, 0, invoke->GetType());
944 to->AddPhi(return_value->AsPhi());
945 }
946 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
947 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
948 HInstruction* last = predecessor->GetLastInstruction();
949 if (!returns_void) {
950 return_value->AsPhi()->AddInput(last->InputAt(0));
951 }
952 predecessor->AddInstruction(new (allocator) HGoto());
953 predecessor->RemoveInstruction(last);
954 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000955 }
956
957 if (return_value != nullptr) {
958 invoke->ReplaceWith(return_value);
959 }
960
961 // Update the meta information surrounding blocks:
962 // (1) the graph they are now in,
963 // (2) the reverse post order of that graph,
964 // (3) the potential loop information they are now in.
965
966 // We don't add the entry block, the exit block, and the first block, which
967 // has been merged with `at`.
968 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
969
970 // We add the `to` block.
971 static constexpr int kNumberOfNewBlocksInCaller = 1;
972 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
973 + kNumberOfNewBlocksInCaller;
974
975 // Find the location of `at` in the outer graph's reverse post order. The new
976 // blocks will be added after it.
977 size_t index_of_at = 0;
978 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
979 index_of_at++;
980 }
981 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
982
983 // Do a reverse post order of the blocks in the callee and do (1), (2),
984 // and (3) to the blocks that apply.
985 HLoopInformation* info = at->GetLoopInformation();
986 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
987 HBasicBlock* current = it.Current();
988 if (current != exit_block_ && current != entry_block_ && current != first) {
989 DCHECK(!current->IsInLoop());
990 DCHECK(current->GetGraph() == this);
991 current->SetGraph(outer_graph);
992 outer_graph->AddBlock(current);
993 outer_graph->reverse_post_order_.Put(++index_of_at, current);
994 if (info != nullptr) {
995 info->Add(current);
996 current->SetLoopInformation(info);
997 }
998 }
999 }
1000
1001 // Do (1), (2), and (3) to `to`.
1002 to->SetGraph(outer_graph);
1003 outer_graph->AddBlock(to);
1004 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1005 if (info != nullptr) {
1006 info->Add(to);
1007 to->SetLoopInformation(info);
1008 if (info->IsBackEdge(at)) {
1009 // Only `at` can become a back edge, as the inlined blocks
1010 // are predecessors of `at`.
1011 DCHECK_EQ(1u, info->NumberOfBackEdges());
1012 info->ClearBackEdges();
1013 info->AddBackEdge(to);
1014 }
1015 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001016 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001017
1018 // Finally remove the invoke from the caller.
1019 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001020}
1021
Calin Juravleacf735c2015-02-12 15:25:22 +00001022std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1023 ScopedObjectAccess soa(Thread::Current());
1024 os << "["
1025 << " is_top=" << rhs.IsTop()
1026 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1027 << " is_exact=" << rhs.IsExact()
1028 << " ]";
1029 return os;
1030}
1031
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001032} // namespace art